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
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
//! KvStore CRDT — a replicated key-value store with access control.
//!
//! Uses OR-Set for key membership (adds win over removes),
//! LWW semantics for values, and HashMap for content storage.
//!
//! ## Access Policies
//!
//! - **Signed**: Only the owner can write. Anyone can read. Incoming deltas
//! from non-owners are rejected. Use for app stores, agent skill registries.
//! - **Allowlisted**: Only explicitly allowed writers can write. The owner
//! manages the allowlist. Use for team workspaces, private swarms.
//! - **Encrypted**: Reserved for group-scoped encrypted stores. The current
//! KvStore sync path does not encrypt deltas; do not rely on this policy for
//! confidentiality until encrypted sync is wired.
//! - **AppendOnly**: Like `Signed` (owner-only writes), but existing keys are
//! immutable — no update, no delete, even by the owner. Use for
//! tamper-evident event logs where the author must not be able to rewrite
//! history retroactively.
use crate::identity::AgentId;
use crate::kv::{KvEntry, KvError, KvStoreDelta, Result};
use saorsa_gossip_crdt_sync::{LwwRegister, OrSet};
use saorsa_gossip_types::PeerId;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
/// Access control policy for a KvStore.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AccessPolicy {
/// Only the owner can write. Anyone can read and replicate.
/// Incoming deltas from non-owners are silently rejected.
Signed,
/// Only explicitly allowlisted agents can write.
/// The owner manages the allowlist.
Allowlisted,
/// Reserved for group-scoped encrypted stores.
///
/// The current KvStore sync path still publishes plaintext deltas and does
/// not enforce group membership by itself. Do not rely on this variant for
/// confidentiality until encrypted sync is wired.
Encrypted {
/// MLS group ID for this store.
group_id: Vec<u8>,
},
/// Owner-signed append-only store: like [`Signed`](Self::Signed), only the
/// owner can write — but existing keys are IMMUTABLE. A key, once written,
/// can never be updated or deleted, **even by the owner**, and the entry
/// is frozen in FULL (value, content type, metadata, timestamps).
/// Re-putting byte-identical content is accepted as an idempotent no-op
/// (retry-friendly, and it does not advance the checkpoint sequence).
/// The policy itself is TERMINAL: once a replica knows a store is
/// append-only, every policy transition away from it is rejected —
/// announces, checkpoints, and manifests included, regardless of
/// `policy_version`.
///
/// ## Exact guarantee (read carefully)
///
/// Keys are immutable **after first observation by a
/// continuously-persistent replica**. A replica that has seen key `k`
/// (and has not lost its state) rejects every rewrite or removal of `k`
/// at all enforcement points: local writes, remote deltas — owner-signed
/// included — and owner-signed checkpoint adoption. A **fresh joiner
/// with no prior state necessarily trusts the owner's current signed
/// snapshot**: signatures alone cannot tell it whether that snapshot is
/// the original history or a rewrite, so two fresh joiners fed different
/// owner-signed snapshots will adopt divergent states (detectable after
/// the fact by comparing adopted checkpoint content roots, never
/// auto-reconciled). Applications that need fresh-joiner rewrite
/// detection must layer content chaining on top (per-author sequence
/// numbers + previous-entry hashes, as x0x-symphony's tracker-integrity-v2
/// does — see saorsa-labs/x0x-symphony#10); witnesses/transparency logs
/// are out of scope here.
///
/// NOTE: this variant MUST stay last — bincode encodes enum variants
/// positionally, and stores/checkpoints/deltas carrying `AccessPolicy`
/// are bincode-serialized on disk and on the wire. Inserting a variant
/// mid-enum would corrupt every existing store.
AppendOnly,
}
impl std::fmt::Display for AccessPolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Signed => write!(f, "signed"),
Self::Allowlisted => write!(f, "allowlisted"),
Self::Encrypted { .. } => write!(f, "encrypted"),
Self::AppendOnly => write!(f, "append_only"),
}
}
}
/// Unique identifier for a KvStore (32 bytes).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct KvStoreId([u8; 32]);
impl KvStoreId {
/// Create from raw bytes.
#[must_use]
pub fn new(bytes: [u8; 32]) -> Self {
Self(bytes)
}
/// Get the raw bytes.
#[must_use]
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
/// Derive a store ID from a name and creator.
#[must_use]
pub fn from_content(name: &str, creator: &AgentId) -> Self {
let mut hasher = blake3::Hasher::new();
hasher.update(b"x0x.store");
hasher.update(name.as_bytes());
hasher.update(creator.as_bytes());
Self(*hasher.finalize().as_bytes())
}
/// Derive a store ID that cryptographically binds a `topic` to its
/// authoritative `owner`.
///
/// Used by BOTH the create and join paths so a creator and an anchored
/// joiner compute the *same* id — the id is the verifiable topic→owner
/// binding. A different owner yields a different id, so a rogue cannot
/// collide with a legitimate store's id by choosing the same topic.
///
/// Uses a distinct domain tag (`x0x.store.v2`) from the legacy
/// [`from_content`](Self::from_content) (`x0x.store`) so the two
/// derivations never accidentally agree.
#[must_use]
pub fn for_topic_owner(topic: &str, owner: &AgentId) -> Self {
let mut hasher = blake3::Hasher::new();
hasher.update(b"x0x.store.v2");
hasher.update(topic.as_bytes());
hasher.update(owner.as_bytes());
Self(*hasher.finalize().as_bytes())
}
}
impl std::fmt::Display for KvStoreId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", hex::encode(self.0))
}
}
fn default_seq_counter() -> Arc<AtomicU64> {
Arc::new(AtomicU64::new(0))
}
/// The authenticated channel through which a store's owner was anchored.
///
/// Pure audit metadata: the security property is the anchored `owner` itself
/// (set at construction), not which channel supplied it. Recording the channel
/// makes a misconfigured or unauthenticated anchor source visible rather than
/// silent.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnchorChannel {
/// This node created the store (`owner = self`).
Creator,
/// Owner supplied via a REST/CLI `expected_owner` parameter (the local
/// user/operator is the trust root).
RestParam,
/// Owner replayed from the persisted manifest after a restart. Stores
/// deserialized from a pre-ownership-source format use this honest label.
#[default]
Persistence,
}
/// How a store's ownership was established — surfaced on reads for
/// auditability. See the module-level "Access Policies" docs and
/// [`KvStore::learn_ownership`] for the construction-only ownership invariant.
///
/// This is a *derived view* of the authoritative `owner` field plus the last
/// observed conflict, not an independent source of truth: writes are gated on
/// `owner`/`policy`, never on this enum.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum OwnershipSource {
/// Owner supplied out-of-band at construction. This is the only state
/// that permits writes; it converges against any owner version (v0.30.1
/// included) because no announce is consulted on the data path.
Anchored {
/// The anchored owner.
owner: AgentId,
/// How the owner was supplied.
channel: AnchorChannel,
},
/// No owner anchored. Fail-closed read-only by design — writes return
/// [`KvError::OwnerUnknown`]. The protocol refuses to derive ownership
/// from the network, so this is permanent, not a pending state.
Unknown,
/// The anchored owner disagrees with a received announce. The store stays
/// on the anchored owner (writes by it still work); the conflict is
/// surfaced so a takeover attempt or misconfiguration is visible.
Conflict {
/// The anchored (construction-time) owner.
anchored: AgentId,
/// The owner claimed by the rejected announce.
announced: AgentId,
},
}
/// Wire-friendly ownership discriminant for REST/audit surfaces.
///
/// Unlike [`OwnershipSource`] (which carries `AgentId` detail for in-process
/// audit), this carries only the status tag; the owner/announced identities
/// travel as hex strings alongside it in DTOs. Strongly typed (not a string)
/// per the ownership-source design decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OwnershipStatus {
/// Owner anchored at construction; writes permitted for the owner.
Anchored,
/// No owner anchored — permanently read-only by design.
Unknown,
/// Anchored owner disagrees with a received announce; owner unchanged.
Conflict,
}
/// Domain-separation tag for owner-checkpoint signatures.
const CHECKPOINT_SIG_DOMAIN: &[u8] = b"x0x.store.checkpoint.sig.v1";
/// Domain-separation tag for content-root hashing.
const CHECKPOINT_ROOT_DOMAIN: &[u8] = b"x0x.store.checkpoint.root.v2";
/// Owner-signed content provenance for a store snapshot.
///
/// Decouples "who relays" from "who authored": the signature is content-level
/// (the owner's ML-DSA-65 key), so a re-wrapping replica cannot strip it. This
/// lets an anchored joiner cold-recover a Signed store from a non-owner
/// replica while the owner is offline — the replica relays
/// `(checkpoint + entries)` and the joiner verifies the owner's signature and
/// recomputes the content root, independent of the relayer.
///
/// **Never establishes ownership.** A checkpoint can only be adopted by a
/// replica already anchored on `expected_owner`; it proves data provenance,
/// not ownership. An unanchored replica rejects all checkpoints (fail-closed).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OwnerCheckpoint {
/// Store topic this checkpoint binds (cross-topic replay defense).
pub topic: String,
/// Store id (must equal `for_topic_owner(topic, owner)`).
pub store_id: KvStoreId,
/// Owner's ML-DSA-65 public key bytes (self-proving).
pub owner_pubkey: Vec<u8>,
/// Policy at checkpoint time.
pub policy: AccessPolicy,
/// Policy freshness counter at checkpoint time.
pub policy_version: u64,
/// Monotonic checkpoint sequence (owner-incremented). Replay/downgrade gate.
pub checkpoint_seq: u64,
/// Canonical BLAKE3 root over every security-relevant field of the active
/// entry set — see [`content_root`].
pub content_root: [u8; 32],
/// Unix ms (skew/freshness logging only; `checkpoint_seq` is authoritative).
pub timestamp: u64,
/// ML-DSA-65 signature over [`signing_bytes`](Self::signing_bytes).
pub signature: Vec<u8>,
}
impl OwnerCheckpoint {
/// The forgeable bytes covered by the signature (everything except the
/// signature itself).
#[must_use]
pub fn signing_bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(256);
buf.extend_from_slice(CHECKPOINT_SIG_DOMAIN);
buf.extend_from_slice(self.topic.as_bytes());
buf.extend_from_slice(self.store_id.as_bytes());
buf.extend_from_slice(&self.owner_pubkey);
// Policy is bincode-encoded so nested variants are unambiguous.
buf.extend_from_slice(&bincode::serialize(&self.policy).unwrap_or_default());
buf.extend_from_slice(&self.policy_version.to_le_bytes());
buf.extend_from_slice(&self.checkpoint_seq.to_le_bytes());
buf.extend_from_slice(&self.content_root);
buf.extend_from_slice(&self.timestamp.to_le_bytes());
buf
}
/// Verify owner binding, store binding, and signature against the anchored
/// `expected_owner`.
///
/// # Errors
///
/// Returns [`KvError::OwnerTokenInvalid`] if the public key does not parse,
/// does not derive to `expected_owner`, or the signature is invalid.
pub fn verify(&self, expected_owner: &AgentId) -> Result<()> {
use ant_quic::crypto::raw_public_keys::pqc::{verify_with_ml_dsa, MlDsaSignature};
let pubkey = ant_quic::MlDsaPublicKey::from_bytes(&self.owner_pubkey)
.map_err(|e| KvError::OwnerTokenInvalid(format!("bad owner pubkey: {e:?}")))?;
// Owner binding: the pubkey must derive to the anchored owner.
let derived = AgentId::from_public_key(&pubkey);
if &derived != expected_owner {
return Err(KvError::OwnerTokenInvalid(
"checkpoint owner_pubkey does not derive to the anchored owner".to_string(),
));
}
let sig = MlDsaSignature::from_bytes(&self.signature)
.map_err(|e| KvError::OwnerTokenInvalid(format!("bad signature: {e:?}")))?;
verify_with_ml_dsa(&pubkey, &self.signing_bytes(), &sig).map_err(|e| {
KvError::OwnerTokenInvalid(format!("invalid checkpoint signature: {e:?}"))
})?;
Ok(())
}
}
/// Deterministic canonical BLAKE3 root over the store name and active entry
/// set.
///
/// Computable identically by the owner (at checkpoint time) and a receiver
/// (from a relay), so a relayer cannot tamper with the store name or any
/// entry field without breaking the root. Each entry is encoded canonically
/// with length-delimited fields covering the outer map key and **every**
/// security-relevant field (inner key, value, content_hash, content_type,
/// metadata, timestamps). The store name is length-delimited and hashed
/// before the entries. Entries are sorted by outer key for determinism.
#[must_use]
pub fn content_root(store_id: &KvStoreId, name: &str, entries: &[(&str, &KvEntry)]) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(CHECKPOINT_ROOT_DOMAIN);
h.update(store_id.as_bytes());
// Store name: length-delimited so it cannot collide with entry data.
h.update(&(name.len() as u64).to_le_bytes());
h.update(name.as_bytes());
let mut sorted = entries.to_vec();
sorted.sort_by(|a, b| a.0.cmp(b.0));
for (outer_key, entry) in &sorted {
h.update(&entry_commitment_bytes(outer_key, entry));
}
*h.finalize().as_bytes()
}
/// Canonical length-delimited encoding of a single entry's security-relevant
/// fields for checkpoint commitment.
///
/// Every variable-length field is prefixed with its byte length as a 64-bit
/// little-endian integer so the encoding is unambiguous (no field-boundary
/// collisions). The outer map key is included alongside the entry's inner key
/// so a relay cannot swap an entry between map slots.
fn entry_commitment_bytes(outer_key: &str, entry: &KvEntry) -> Vec<u8> {
let mut buf = Vec::with_capacity(256);
lp_bytes(&mut buf, outer_key.as_bytes());
lp_bytes(&mut buf, entry.key.as_bytes());
lp_bytes(&mut buf, &entry.value);
lp_bytes(&mut buf, &entry.content_hash);
lp_bytes(&mut buf, entry.content_type.as_bytes());
// Metadata: canonicalize by sorting key-value pairs.
let mut meta: Vec<_> = entry.metadata.iter().collect();
meta.sort_by(|a, b| a.0.cmp(b.0));
buf.extend_from_slice(&(meta.len() as u64).to_le_bytes());
for (mk, mv) in &meta {
lp_bytes(&mut buf, mk.as_bytes());
lp_bytes(&mut buf, mv.as_bytes());
}
buf.extend_from_slice(&entry.created_at.to_le_bytes());
buf.extend_from_slice(&entry.updated_at.to_le_bytes());
buf
}
/// Write a length-prefixed byte slice (64-bit LE length + data).
fn lp_bytes(buf: &mut Vec<u8>, data: &[u8]) {
buf.extend_from_slice(&(data.len() as u64).to_le_bytes());
buf.extend_from_slice(data);
}
/// Full-field entry equality for the AppendOnly freeze.
///
/// Under [`AccessPolicy::AppendOnly`] an existing entry is frozen in FULL —
/// value, content hash, content type, metadata, and both timestamps — not
/// just its value bytes. This matches exactly the fields the owner-signed
/// checkpoint root commits to (see [`entry_commitment_bytes`]), so "equal
/// here" and "same commitment" are the same statement.
fn entry_frozen_fields_equal(a: &KvEntry, b: &KvEntry) -> bool {
a.key == b.key
&& a.value == b.value
&& a.content_hash == b.content_hash
&& a.content_type == b.content_type
&& a.metadata == b.metadata
&& a.created_at == b.created_at
&& a.updated_at == b.updated_at
}
/// Validate that a relayed entry is internally consistent before adoption.
///
/// Independently enforces:
/// - `outer_key == entry.key` (the entry has not been moved between map slots)
/// - `content_hash == blake3(value)` (the value matches its claimed hash)
///
/// Called before any mutation or high-water update caused by checkpoint
/// adoption. Failures reject the entire checkpoint adoption (fail-closed).
fn validate_entry_integrity(outer_key: &str, entry: &KvEntry) -> Result<()> {
if outer_key != entry.key {
return Err(KvError::Merge(format!(
"checkpoint entry outer key {outer_key:?} != inner key {:?}",
entry.key
)));
}
let computed = *blake3::hash(&entry.value).as_bytes();
if computed != entry.content_hash {
return Err(KvError::Merge(
"checkpoint entry content_hash != blake3(value)".to_string(),
));
}
Ok(())
}
/// Inputs required to build an owner-signed checkpoint.
pub struct OwnerCheckpointParams<'a> {
pub topic: &'a str,
pub store_id: &'a KvStoreId,
pub secret_key: &'a ant_quic::MlDsaSecretKey,
pub public_key: &'a ant_quic::MlDsaPublicKey,
pub policy: &'a AccessPolicy,
pub policy_version: u64,
pub checkpoint_seq: u64,
pub content_root: [u8; 32],
pub timestamp: u64,
}
/// Build and sign an [`OwnerCheckpoint`] with the owner's key.
///
/// This is the production side (owner only). Replicas never call this — they
/// only cache and relay checkpoints produced by the owner.
///
/// # Errors
///
/// Returns [`KvError::Gossip`] if checkpoint signing fails.
pub fn make_owner_checkpoint(params: OwnerCheckpointParams<'_>) -> Result<OwnerCheckpoint> {
use ant_quic::crypto::raw_public_keys::pqc::sign_with_ml_dsa;
let owner_pubkey = params.public_key.as_bytes().to_vec();
let cp = OwnerCheckpoint {
topic: params.topic.to_string(),
store_id: *params.store_id,
owner_pubkey,
policy: params.policy.clone(),
policy_version: params.policy_version,
checkpoint_seq: params.checkpoint_seq,
content_root: params.content_root,
timestamp: params.timestamp,
signature: Vec::new(),
};
let bytes = cp.signing_bytes();
let sig = sign_with_ml_dsa(params.secret_key, &bytes)
.map_err(|e| KvError::Gossip(format!("owner checkpoint sign failed: {e:?}")))?;
let mut cp = cp;
cp.signature = sig.as_bytes().to_vec();
Ok(cp)
}
/// A replicated key-value store using CRDTs with access control.
///
/// Combines:
/// - OR-Set for key membership (which keys exist)
/// - HashMap for entry content (the KvEntry values)
/// - LWW-Register for store metadata (name)
/// - Access control via owner, allowlist, and policy
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KvStore {
/// Unique identifier for this store.
id: KvStoreId,
/// Key membership — OR-Set ensures adds win over removes.
keys: OrSet<String>,
/// Key-value entries indexed by key name.
entries: HashMap<String, KvEntry>,
/// Store name (LWW semantics).
name: LwwRegister<String>,
/// Access control policy.
#[serde(default = "default_policy")]
policy: AccessPolicy,
/// Store owner (the agent that created it).
///
/// Ownership is established ONLY at construction — either by the creator
/// ([`new`](Self::new)) or from trusted out-of-band input at join
/// ([`new_replica`](Self::new_replica)). It is **never** adopted from an
/// untrusted network announce (see [`learn_ownership`](Self::learn_ownership)).
/// For Signed and Allowlisted policies, only the owner (and allowlisted
/// writers) can write.
#[serde(default)]
owner: Option<AgentId>,
/// Agents allowed to write (for Allowlisted policy).
/// The owner is implicitly allowed and does not need to be in this set.
#[serde(default)]
allowed_writers: HashSet<AgentId>,
/// Version counter — incremented on every mutation.
#[serde(default)]
version: u64,
// ---------------------------------------------------------------------
// TRAILING FIELDS — added after the original `KvStore` shape.
//
// bincode (wire + disk format) is positional and non-self-describing.
// Plain `#[serde(default)]` does NOT tolerate a missing field there:
// bincode returns an EOF *error* (not `Ok(None)`) at stream end, so serde
// never applies the default. Every field below is therefore (a) declared
// LAST, after the original `id..version` shape, and (b) decoded with
// `de_tolerant`, a custom deserializer that catches EOF/short streams and
// yields the field's `Default`. This lets a blob written by the original
// (pre-ownership, pre-checkpoint) `KvStore` shape — whose bytes END at
// `version` — deserialize with these fields defaulted instead of failing.
//
// INVARIANT: any NEW persisted field MUST be appended at the end of this
// block with the same `de_tolerant` treatment. Never insert a persisted
// field mid-struct, or older blobs will misalign and fail to decode.
// ---------------------------------------------------------------------
/// Latest owner-signed checkpoint this replica has merged or produced.
/// Persisted so owner restarts never regress the checkpoint sequence; a
/// blob written before this field existed decodes to `None`.
#[serde(default, deserialize_with = "de_tolerant")]
pub(crate) latest_checkpoint: Option<OwnerCheckpoint>,
/// Highest `checkpoint_seq` adopted (replay/downgrade high-water mark).
/// Persisted so owner restarts never regress the checkpoint sequence.
#[serde(default, deserialize_with = "de_tolerant")]
pub(crate) highest_checkpoint_seq: u64,
/// How the owner was anchored (audit metadata); meaningful only when
/// `owner` is `Some`.
#[serde(default, deserialize_with = "de_tolerant")]
anchor_channel: AnchorChannel,
/// Monotonic freshness counter for owner-announced policy refreshes.
///
/// A policy refresh from [`learn_ownership`](Self::learn_ownership) is
/// applied only when the announce carries a strictly greater
/// `policy_version`, which blocks a replayed authentic-but-stale announce
/// from downgrading policy. This is owner-local metadata; it is NOT a
/// CRDT-merged value.
#[serde(default, deserialize_with = "de_tolerant")]
policy_version: u64,
/// The last announce whose claimed owner conflicted with the anchored
/// owner (audit only). Cleared when the anchored owner itself refreshes
/// via a matching forward-version announce. `None` when no conflict has
/// been observed (or it has been cleared).
#[serde(default, deserialize_with = "de_tolerant")]
ownership_conflict: Option<(AgentId, AgentId)>,
/// Monotonic sequence counter for unique OR-Set tags.
#[serde(skip, default = "default_seq_counter")]
seq_counter: Arc<AtomicU64>,
}
/// Deserialize a trailing, defaultable `KvStore` field, tolerating its absence.
///
/// bincode is positional and non-self-describing: a blob written by an older
/// `KvStore` shape simply ends before these trailing fields, so bincode hits
/// EOF when asked to read them. Decoding the value if present, or falling back
/// to `T::default()` on EOF / any malformed tail, makes such a blob load with
/// the newer fields defaulted rather than failing outright. Only sound at
/// stream-EOF for genuinely trailing fields (see the struct's TRAILING note).
fn de_tolerant<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::Deserialize<'de> + Default,
{
Ok(T::deserialize(deserializer).unwrap_or_default())
}
fn default_policy() -> AccessPolicy {
AccessPolicy::Signed
}
impl KvStore {
/// Create a new empty KvStore with the given access policy.
/// Create a new empty KvStore owned by `owner` with the given access
/// policy.
///
/// This is the **creator** path: ownership is anchored on `owner` at
/// construction (channel [`AnchorChannel::Creator`]) and is immutable for
/// the life of the store.
#[must_use]
pub fn new(id: KvStoreId, name: String, owner: AgentId, policy: AccessPolicy) -> Self {
let mut name_reg = LwwRegister::new(name.clone());
// Stamp the creator-set name with a non-empty clock so it wins LWW
// merge against replicas initialized with empty names and empty
// clocks (which would otherwise be concurrent and hash-tiebroken).
name_reg.set(name, PeerId::new(owner.0));
Self {
id,
keys: OrSet::new(),
entries: HashMap::new(),
name: name_reg,
policy,
owner: Some(owner),
anchor_channel: AnchorChannel::Creator,
policy_version: 0,
ownership_conflict: None,
latest_checkpoint: None,
highest_checkpoint_seq: 0,
allowed_writers: HashSet::new(),
version: 0,
seq_counter: Arc::new(AtomicU64::new(0)),
}
}
/// Create a joined replica of a store, anchoring ownership from trusted
/// out-of-band input.
///
/// Ownership is established ONLY here, at construction:
/// - `expected_owner = Some(o)` → the replica is **anchored** on `o`
/// (`OwnershipSource::Anchored`). It accepts `o`'s deltas and (if this
/// node *is* `o`) its own local writes, converging against any owner
/// version — including a v0.30.1 owner that never announces — because
/// the data path never consults an announce.
/// - `expected_owner = None` → the replica has **no owner**
/// (`OwnershipSource::Unknown`) and is permanently read-only by design:
/// every policy-restricted write returns [`KvError::OwnerUnknown`]. This
/// is explicit incompatibility, never a silent deadlock and never a
/// permissive first-writer fallback.
///
/// `channel` records how the anchor was supplied (audit metadata).
#[must_use]
pub fn new_replica(
id: KvStoreId,
name: String,
expected_owner: Option<AgentId>,
channel: AnchorChannel,
) -> Self {
Self {
id,
keys: OrSet::new(),
entries: HashMap::new(),
name: LwwRegister::new(name),
policy: AccessPolicy::Signed,
owner: expected_owner,
anchor_channel: channel,
policy_version: 0,
ownership_conflict: None,
latest_checkpoint: None,
highest_checkpoint_seq: 0,
allowed_writers: HashSet::new(),
version: 0,
seq_counter: Arc::new(AtomicU64::new(0)),
}
}
/// Get the next monotonically-increasing sequence number.
pub fn next_seq(&self) -> u64 {
self.seq_counter.fetch_add(1, Ordering::Relaxed) + 1
}
/// Current value of the in-memory sequence counter (highest seq minted).
///
/// Snapshot persistence stores this alongside the store state so a
/// restart can restore the exact tag ceiling — `seq_counter` itself is
/// `serde(skip)` for wire/legacy-layout reasons.
pub(crate) fn seq_counter_value(&self) -> u64 {
self.seq_counter.load(Ordering::Relaxed)
}
/// Restore the in-memory sequence counter to at least `floor`.
///
/// Called on snapshot restore with the persisted counter value so a
/// restarted node can never re-mint an OR-Set `(peer, seq)` tag it used
/// before the restart. (`KvStoreHandle::put_with_delta` mints a second
/// seq per put for the published delta tag, so the counter deliberately
/// runs ahead of `version` — persisting the real counter, not a
/// version-derived floor, is what makes this bound exact.)
pub(crate) fn restore_seq_counter(&self, floor: u64) {
if self.seq_counter.load(Ordering::Relaxed) < floor {
self.seq_counter.store(floor, Ordering::Relaxed);
}
}
/// Get the current version.
#[must_use]
pub fn current_version(&self) -> u64 {
self.version
}
/// Get the store ID.
#[must_use]
pub fn id(&self) -> &KvStoreId {
&self.id
}
/// Get the store name.
#[must_use]
pub fn name(&self) -> &str {
self.name.get()
}
/// The name register, including its vector clock.
///
/// Deltas carry this whole register (not just the value) so receivers can
/// resolve a remote name change by causality rather than adopting it
/// unconditionally.
#[must_use]
pub fn name_register(&self) -> &LwwRegister<String> {
&self.name
}
/// Get the access policy.
#[must_use]
pub fn policy(&self) -> &AccessPolicy {
&self.policy
}
/// Get the store owner.
#[must_use]
pub fn owner(&self) -> Option<&AgentId> {
self.owner.as_ref()
}
/// Get the policy-version freshness counter.
#[must_use]
pub fn policy_version(&self) -> u64 {
self.policy_version
}
/// Get the channel through which the owner was anchored.
#[must_use]
pub fn anchor_channel(&self) -> AnchorChannel {
self.anchor_channel
}
/// Derive the store's ownership status for auditability.
///
/// This is a *view* of the authoritative `owner` field plus the last
/// observed conflict — writes are gated on `owner`/`policy`, never on
/// this value.
#[must_use]
pub fn ownership_source(&self) -> OwnershipSource {
match (&self.owner, &self.ownership_conflict) {
(None, _) => OwnershipSource::Unknown,
(Some(owner), None) => OwnershipSource::Anchored {
owner: *owner,
channel: self.anchor_channel,
},
(Some(owner), Some((_anchored, announced))) => OwnershipSource::Conflict {
// `anchored` is the current authoritative owner by construction.
anchored: *owner,
announced: *announced,
},
}
}
/// Get the set of allowed writers.
#[must_use]
pub fn allowed_writers(&self) -> &HashSet<AgentId> {
&self.allowed_writers
}
/// Get the number of entries.
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
/// Check if the store is empty.
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Check if an agent is authorized to write to this store.
#[must_use]
pub fn is_authorized(&self, agent_id: &AgentId) -> bool {
match &self.policy {
AccessPolicy::Signed => {
// Only the owner can write
self.owner.as_ref().is_some_and(|o| o == agent_id)
}
AccessPolicy::Allowlisted => {
// Owner + allowlisted agents can write
self.owner.as_ref().is_some_and(|o| o == agent_id)
|| self.allowed_writers.contains(agent_id)
}
AccessPolicy::Encrypted { .. } => {
// Reserved for encrypted sync. The store layer currently treats
// this as permissive; group membership enforcement belongs in
// the secure sync path once wired.
true
}
AccessPolicy::AppendOnly => {
// Owner-only writes, exactly like Signed. Immutability of
// existing keys is enforced separately at each mutation site
// (put/remove/merge_delta/checkpoint adoption).
self.owner.as_ref().is_some_and(|o| o == agent_id)
}
}
}
/// Check that `writer` may perform a local mutation on this store.
///
/// This is the local-write counterpart of the inbound check in
/// [`merge_delta`](Self::merge_delta): the same
/// [`is_authorized`](Self::is_authorized) rule is applied before a local
/// put/remove mutates the replica, so an unauthorized local write can
/// never fork
/// the replica away from what authorized peers accept.
///
/// # Errors
///
/// - [`KvError::OwnerUnknown`] if the store has a policy-restricted
/// (`Signed`/`Allowlisted`) policy but its authoritative owner has not
/// been learned yet (a freshly joined replica). Fail closed.
/// - [`KvError::Unauthorized`] if `writer` is not authorized under the
/// store's policy.
pub fn authorize_local_write(&self, writer: &AgentId) -> Result<()> {
if matches!(self.policy, AccessPolicy::Encrypted { .. }) {
// Matches the inbound path: the reserved Encrypted policy is
// currently permissive at the store layer.
return Ok(());
}
let Some(owner) = self.owner.as_ref() else {
return Err(KvError::OwnerUnknown);
};
if !self.is_authorized(writer) {
return Err(KvError::Unauthorized(format!(
"store policy is {}; owner is {}",
self.policy,
hex::encode(owner.as_bytes())
)));
}
Ok(())
}
/// Apply an owner-announced policy refresh / detect a conflict.
///
/// `verified_sender` is the cryptographically verified identity of the
/// peer that published the announcement (the pub/sub layer verifies the
/// ML-DSA-65 signature before delivery). The `claimed_owner` must equal
/// `verified_sender`: an announce can only attest to *oneself*, blocking
/// third-party ownership assignment.
///
/// **Ownership is NEVER established here.** Ownership is anchored only at
/// construction ([`new`](Self::new) / [`new_replica`](Self::new_replica)).
/// The `verified_sender == claimed_owner` check blocks third-party
/// assignment but is *trivially* satisfied by any self-claim, so accepting
/// an announce to go `None → Some(owner)` would let any agent that speaks
/// first about a topic seize it (first-self-capture). That path is removed
/// by construction.
///
/// This method therefore only ever:
/// - **refreshes policy** when the claimed owner equals the already-anchored
/// owner AND `policy_version` is strictly newer than the last applied
/// refresh (blocking a replayed authentic-but-stale announce from
/// downgrading policy); or
/// - **records a conflict** when the claimed owner differs from the
/// anchored owner (the anchored owner is unchanged; the conflict is
/// surfaced via [`ownership_source`](Self::ownership_source)).
///
/// # Errors
///
/// - [`KvError::OwnerTokenInvalid`] if `verified_sender != claimed_owner`,
/// or if the store has no anchored owner (`None` — ownership cannot be
/// learned from an untrusted announce; the caller must supply
/// `expected_owner` at join).
/// - [`KvError::OwnershipConflict`] if a different owner is anchored.
pub fn learn_ownership(
&mut self,
claimed_owner: AgentId,
policy: AccessPolicy,
policy_version: u64,
verified_sender: &AgentId,
) -> Result<()> {
if *verified_sender != claimed_owner {
return Err(KvError::OwnerTokenInvalid(
"ownership announcement sender does not match claimed owner".to_string(),
));
}
let Some(existing) = self.owner else {
// No anchored owner. Ownership is construction-only: refuse to
// derive it from an untrusted announce. Remain read-only.
return Err(KvError::OwnerTokenInvalid(
"ownership cannot be learned from an announcement; supply expected_owner at join"
.to_string(),
));
};
if existing != claimed_owner {
// Immutable owner: record the conflict for auditability and reject.
self.ownership_conflict = Some((existing, claimed_owner));
self.version += 1;
return Err(KvError::OwnershipConflict {
anchored: existing,
claimed: claimed_owner,
});
}
// Anchored owner matches. Apply the policy refresh when it is at least
// as fresh as the last applied one. `>=` (not strict `>`) is required
// so a fresh replica at version 0 adopts the owner's initial (version
// 0) policy — otherwise a non-Signed store would stay at the default
// Signed and reject legitimate writers. Equal-version replay is safe:
// a legitimate owner assigns each policy a unique monotonic version,
// so an equal version carries the same policy, and a forgery with a
// different policy at the same version cannot be signed by the owner.
// An older replay (version < current) is still dropped, preventing a
// downgrade. A matching forward refresh clears a recorded conflict.
//
// AppendOnly is TERMINAL: once this replica knows the store is
// append-only, no announce — however fresh, however genuinely
// owner-signed — may transition the policy away from it. Allowing
// that would let the owner downgrade to Signed, delete/rewrite keys,
// and (optionally) upgrade back: exactly the retroactive-rewrite
// attack AppendOnly exists to stop.
if matches!(self.policy, AccessPolicy::AppendOnly)
&& !matches!(policy, AccessPolicy::AppendOnly)
{
return Err(KvError::OwnerTokenInvalid(
"append-only policy is terminal; policy downgrade rejected".to_string(),
));
}
if policy_version >= self.policy_version {
self.policy = policy;
self.policy_version = policy_version;
self.ownership_conflict = None;
self.version += 1;
}
Ok(())
}
/// Add an agent to the allowlist (owner-only operation).
///
/// # Errors
///
/// Returns `KvError::Unauthorized` if the caller is not the owner.
pub fn allow_writer(&mut self, writer: AgentId, caller: &AgentId) -> Result<()> {
if !self.owner.as_ref().is_some_and(|o| o == caller) {
return Err(KvError::Unauthorized(
"only the store owner can modify the allowlist".to_string(),
));
}
self.allowed_writers.insert(writer);
// Bump the policy freshness counter so the owner's next announce
// carries a newer version (blocks replay of a pre-change announce).
self.policy_version = self.policy_version.saturating_add(1);
self.version += 1;
Ok(())
}
/// Remove an agent from the allowlist (owner-only operation).
///
/// # Errors
///
/// Returns `KvError::Unauthorized` if the caller is not the owner.
pub fn deny_writer(&mut self, writer: &AgentId, caller: &AgentId) -> Result<()> {
if !self.owner.as_ref().is_some_and(|o| o == caller) {
return Err(KvError::Unauthorized(
"only the store owner can modify the allowlist".to_string(),
));
}
self.allowed_writers.remove(writer);
self.policy_version = self.policy_version.saturating_add(1);
self.version += 1;
Ok(())
}
/// Put a key-value entry.
///
/// If the key already exists, the value is updated using LWW semantics —
/// except under [`AccessPolicy::AppendOnly`], where an existing key is
/// immutable: a re-put of byte-identical content (same value AND
/// content type) is accepted as an idempotent no-op so retries are safe,
/// and anything else returns [`KvError::ImmutableKey`].
pub fn put(
&mut self,
key: String,
value: Vec<u8>,
content_type: String,
peer_id: PeerId,
) -> Result<()> {
if value.len() > crate::kv::entry::MAX_INLINE_SIZE {
return Err(KvError::ValueTooLarge {
size: value.len(),
max: crate::kv::entry::MAX_INLINE_SIZE,
});
}
// AppendOnly: existing keys are immutable, even for the owner.
if matches!(self.policy, AccessPolicy::AppendOnly) {
if let Some(existing) = self.get(&key) {
if existing.value == value && existing.content_type == content_type {
return Ok(()); // idempotent re-put of identical content
}
return Err(KvError::ImmutableKey(key));
}
}
let seq = self.next_seq();
// Add key to OR-Set
self.keys
.add(key.clone(), (peer_id, seq))
.map_err(|e| KvError::Merge(format!("OR-Set add failed: {e}")))?;
// Create or update entry
if let Some(existing) = self.entries.get_mut(&key) {
existing.update_value(value, content_type);
} else {
self.entries
.insert(key.clone(), KvEntry::new(key, value, content_type));
}
self.version += 1;
Ok(())
}
/// Get an entry by key.
///
/// Gated on active-key membership so a tombstoned key never reads back.
/// `entries` is not a reliable proxy for the active set: `merge` applies a
/// remote OR-Set tombstone via `merge_state` without pruning `entries`, so
/// a key can linger in `entries` after it leaves the active set. We query
/// the OR-Set directly (an O(1) membership check) rather than materializing
/// and linearly scanning `elements()` as the previous implementation did.
#[must_use]
pub fn get(&self, key: &str) -> Option<&KvEntry> {
if self.keys.contains(&key.to_string()) {
self.entries.get(key)
} else {
None
}
}
/// Remove a key from the store.
///
/// # Errors
///
/// - [`KvError::KeyNotFound`] if the key does not exist.
/// - [`KvError::ImmutableKey`] under [`AccessPolicy::AppendOnly`]: keys
/// can never be deleted, even by the owner.
pub fn remove(&mut self, key: &str) -> Result<()> {
if !self.entries.contains_key(key) {
return Err(KvError::KeyNotFound(key.to_string()));
}
if matches!(self.policy, AccessPolicy::AppendOnly) {
return Err(KvError::ImmutableKey(key.to_string()));
}
self.keys
.remove(&key.to_string())
.map_err(|e| KvError::Merge(format!("OR-Set remove failed: {e}")))?;
self.entries.remove(key);
self.version += 1;
Ok(())
}
/// List all active keys (not tombstoned).
#[must_use]
pub fn active_keys(&self) -> Vec<&String> {
self.keys.elements().into_iter().collect()
}
/// List all active entries.
#[must_use]
pub fn active_entries(&self) -> Vec<&KvEntry> {
let active: HashSet<String> = self.keys.elements().into_iter().cloned().collect();
self.entries
.values()
.filter(|e| active.contains(&e.key))
.collect()
}
/// Active entries paired with their outer map keys, for canonical
/// checkpoint root computation. Borrows from `self` — no cloning.
pub(crate) fn checkpoint_pairs(&self) -> Vec<(&str, &KvEntry)> {
self.keys
.elements()
.into_iter()
.filter_map(|k| self.entries.get(k).map(|e| (k.as_str(), e)))
.collect()
}
/// Update the store name.
pub fn update_name(&mut self, name: String, peer_id: PeerId) {
self.name.set(name, peer_id);
self.version += 1;
}
/// Merge a delta into this store.
///
/// Enforces access control: if the store has a Signed or Allowlisted
/// policy, the `writer` must be authorized. Unauthorized deltas are
/// silently rejected (returns Ok but does not apply changes).
pub fn merge_delta(
&mut self,
delta: &KvStoreDelta,
peer_id: PeerId,
writer: Option<&AgentId>,
) -> Result<()> {
// Authoritative full-snapshot checkpoint adoption (cold-recovery path):
// if the checkpoint's content root matches the relayed entry set, adopt
// as owner-proven independent of the relayer. An incremental delta's
// single-entry set won't match a full-state root, so it falls through
// to the sender-auth path below (where the owner is authorized as
// writer==owner), and the checkpoint is cached afterward by
// maybe_cache_checkpoint if the resulting state matches.
if let Some(cp) = delta.owner_checkpoint.as_ref() {
if self.try_adopt_full_snapshot(delta, peer_id, cp) {
return Ok(());
}
// Stale-delta gate: a delta carrying a genuine owner checkpoint
// at or below the adopted high-water mark was published at or
// before the adopted checkpoint's state, so its mutations are
// already reflected in (or superseded by) that full snapshot.
// Without this gate the gossip replay/cache window re-delivers
// old owner-signed incremental deltas after a cold-recovery
// checkpoint adoption, and the sender-auth path below re-adds
// owner-DELETED keys on a fresh joiner (which holds no OR-Set
// tombstones for them) — resurrecting deleted state.
if self.is_subsumed_by_adopted_checkpoint(cp) {
tracing::debug!(
"dropped stale owner delta (checkpoint_seq {} <= adopted {}) for store {}",
cp.checkpoint_seq,
self.highest_checkpoint_seq,
self.id
);
return Ok(());
}
}
// Access control: reject unauthorized writes
if let Some(writer_id) = writer {
if !self.is_authorized(writer_id) {
tracing::warn!(
"rejected delta from unauthorized writer {} for store {}",
hex::encode(writer_id.as_bytes()),
self.id
);
return Ok(()); // Silent rejection — don't propagate errors for spam
}
} else {
// No writer identity is only tolerated for the reserved Encrypted
// policy. KvStoreSync does not decrypt or verify group membership
// here today.
match &self.policy {
AccessPolicy::Encrypted { .. } => {} // OK
_ => {
tracing::warn!(
"rejected anonymous delta for non-encrypted store {}",
self.id
);
return Ok(());
}
}
}
// Canonical-map gate, ALL policies: a delta carrying the same key in
// both `added` and `updated` is ambiguous by construction (two values
// for one key in one message) — no legitimate producer emits it
// (`for_put` is added-only, removals are removed-only, `full_delta`
// is added-only). Drop the whole delta rather than letting map
// iteration/LWW order decide which copy wins. Mirrors the adoption
// path's 5b gate; only the authorized writer can reach this point,
// so rejection cannot be used by third parties to censor writes.
for key in delta.updated.keys() {
if delta.added.contains_key(key) {
tracing::warn!(
"rejected ambiguous delta for store {}: key {key:?} appears in both added and updated",
self.id
);
return Ok(());
}
}
// Apply allowlist changes from the delta (owner-only)
if let Some(ref additions) = delta.allowlist_additions {
if writer.is_some_and(|w| self.owner.as_ref().is_some_and(|o| o == w)) {
for agent in additions {
self.allowed_writers.insert(*agent);
}
}
}
if let Some(ref removals) = delta.allowlist_removals {
if writer.is_some_and(|w| self.owner.as_ref().is_some_and(|o| o == w)) {
for agent in removals {
self.allowed_writers.remove(agent);
}
}
}
// Apply added entries
for (key, (entry, tag)) in &delta.added {
if self.append_only_rejects_entry(key, entry) {
continue; // skip this entry; the rest of the delta still applies
}
self.keys
.add(key.clone(), *tag)
.map_err(|e| KvError::Merge(format!("OR-Set add failed: {e}")))?;
if let Some(existing) = self.entries.get_mut(key) {
existing.merge(entry);
} else {
self.entries.insert(key.clone(), entry.clone());
}
}
// Apply removed keys — never for AppendOnly stores: keys are immutable
// and cannot be removed, even by an owner-signed delta (an owner
// retroactively deleting records is exactly the attack AppendOnly
// exists to stop).
if matches!(self.policy, AccessPolicy::AppendOnly) {
if !delta.removed.is_empty() {
tracing::warn!(
"append-only violation: skipped {} remote key removal(s) for store {}",
delta.removed.len(),
self.id
);
}
} else {
for key in delta.removed.keys() {
let _ = self.keys.remove(&key.to_string());
self.entries.remove(key.as_str());
}
}
// Apply updated entries (upsert)
for (key, entry) in &delta.updated {
if self.append_only_rejects_entry(key, entry) {
continue; // skip this entry; the rest of the delta still applies
}
if let Some(existing) = self.entries.get_mut(key) {
existing.merge(entry);
} else {
self.keys
.add(key.clone(), (peer_id, 0))
.map_err(|e| KvError::Merge(format!("OR-Set add failed: {e}")))?;
self.entries.insert(key.clone(), entry.clone());
}
}
// Apply name update via LWW (vector-clock) merge so a stale delta
// cannot overwrite a newer local name; mirrors the full-state merge.
if let Some(ref name_register) = delta.name_update {
self.name.merge(name_register);
}
// After an incremental mutation, cache the checkpoint if the resulting
// complete state matches the checkpoint's content root. This ensures a
// relay always carries the latest checkpoint after normal
// multi-write/update/delete operations, so a fresh anchored joiner can
// cold-recover the exact final state from a non-owner relay.
if let Some(cp) = delta.owner_checkpoint.as_ref() {
self.maybe_cache_checkpoint(cp);
}
self.version += 1;
Ok(())
}
/// AppendOnly guard for one incoming delta entry.
///
/// `true` when this store is [`AccessPolicy::AppendOnly`] and `key` is
/// already active locally — the incoming entry must be skipped WHOLESALE.
/// Existing entries are frozen in full (value, content type, metadata,
/// timestamps, content hash): even a byte-identical redelivery is not
/// merged, because [`KvEntry::merge`] resolves by LWW timestamp and could
/// otherwise mutate `metadata`/`updated_at` while the value stays equal.
/// Owner-signed deltas are NOT exempt: an owner retroactively rewriting
/// records is exactly the attack this policy exists to stop. Only a
/// content-differing skip is warn-logged; an identical redelivery is a
/// silent idempotent no-op.
fn append_only_rejects_entry(&self, key: &str, entry: &KvEntry) -> bool {
if !matches!(self.policy, AccessPolicy::AppendOnly) {
return false;
}
let Some(local) = self.get(key) else {
return false; // new key — a legitimate append
};
if !entry_frozen_fields_equal(local, entry) {
tracing::warn!(
"append-only violation: skipped remote update of existing key {key:?} for store {}",
self.id
);
}
true
}
/// Try to adopt an owner-signed checkpoint as an authoritative full
/// snapshot.
///
/// Returns `true` only when the checkpoint fully validates AND its content
/// root matches the delta's relayed entry set (a full-state relay). Every
/// relayed entry is independently integrity-checked (`outer_key ==
/// entry.key`, `content_hash == blake3(value)`) before any mutation.
/// Removals/tombstones are applied, the checkpoint is cached, and the
/// high-water mark is updated. This is what lets an anchored joiner
/// cold-recover a Signed store from a non-owner replica while the owner is
/// offline.
///
/// Returns `false` otherwise (unanchored, bad sig/owner, stale seq,
/// cross-store, entry integrity failure, root mismatch / incremental
/// delta / tamper), in which case [`merge_delta`] falls through to the
/// normal sender-auth path. Never establishes ownership (anchor gate).
fn try_adopt_full_snapshot(
&mut self,
delta: &KvStoreDelta,
peer_id: PeerId,
cp: &OwnerCheckpoint,
) -> bool {
// 1. Anchor gate: never learn the owner from a relay.
let Some(expected_owner) = self.owner else {
tracing::warn!("rejected owner checkpoint for unanchored store {}", self.id);
return false;
};
// 2. Owner binding + signature.
if let Err(e) = cp.verify(&expected_owner) {
tracing::warn!("rejected owner checkpoint for store {}: {e}", self.id);
return false;
}
// 3. Store/topic binding — store_id = for_topic_owner(topic, owner)
// binds both, and the signature covers topic + store_id, so a
// cross-store replay either mismatches the id or fails verification.
if cp.store_id != self.id {
tracing::warn!(
"rejected owner checkpoint: store_id mismatch for {}",
self.id
);
return false;
}
// 4. Replay/downgrade gate (monotonic checkpoint sequence).
if cp.checkpoint_seq <= self.highest_checkpoint_seq {
return false; // stale replay — ignore, fall through
}
// 5. Validate every relayed entry's integrity before any mutation.
// Fail-closed: a single malformed/inconsistent entry rejects the
// entire checkpoint adoption.
for (key, (entry, _)) in &delta.added {
if let Err(e) = validate_entry_integrity(key, entry) {
tracing::warn!("rejected checkpoint entry for store {}: {e}", self.id);
return false;
}
}
for (key, entry) in &delta.updated {
if let Err(e) = validate_entry_integrity(key, entry) {
tracing::warn!("rejected checkpoint entry for store {}: {e}", self.id);
return false;
}
}
// 5b. Canonical-map gate: `added` and `updated` must be DISJOINT on
// the adoption path. No legitimate producer emits the same key in
// both maps of a full-state relay (`full_delta` populates only
// `added`; incremental owner deltas are single-map), but a crafted
// delta could carry key K in both with different values — the
// validation/root pass would see one set while adoption applies
// both maps in sequence, letting the second silently rewrite what
// was validated. Reject for ALL policies: adoption is a
// security-critical full-replace and an ambiguous multiset is
// tamper by construction. Fall-through to sender-auth is safe —
// its loops re-check state sequentially per entry.
for key in delta.updated.keys() {
if delta.added.contains_key(key) {
tracing::warn!(
"rejected owner checkpoint for store {}: key {key:?} appears in both added and updated",
self.id
);
return false;
}
}
// 6. Content integrity: the canonical root over the relayed entry set
// must match. This only holds for a full-state relay; an incremental
// delta's single entry set won't match a full-state checkpoint root,
// so the checkpoint doesn't apply and we fall through to sender-auth.
let mut relayed: Vec<(&str, &KvEntry)> = delta
.added
.iter()
.map(|(k, (e, _))| (k.as_str(), e))
.collect();
relayed.extend(delta.updated.iter().map(|(k, e)| (k.as_str(), e)));
let relayed_name: &str = delta
.name_update
.as_ref()
.map(|r| r.get().as_str())
.unwrap_or("");
if content_root(&self.id, relayed_name, &relayed) != cp.content_root {
return false; // tamper / truncation / subset / incremental — fall through
}
// 6b. AppendOnly immutability gate: a checkpoint may only EXTEND the
// keyset. If adopting it would drop a locally-present key or
// change its bytes, reject the whole checkpoint and keep local
// state (fail loud) — an owner signing a rewritten/truncated
// history is exactly the attack AppendOnly exists to stop. A
// fresh joiner holds no local keys, so cold-start adoption is
// unaffected. Checked against BOTH the local policy and the
// checkpoint's claimed policy, so a hostile checkpoint cannot
// dodge the gate by flipping its own policy field.
// AppendOnly is TERMINAL: a checkpoint claiming the store is no
// longer append-only, presented to a replica that knows it is, is
// hostile by definition (adopting it would downgrade the policy in
// step 10 and unfreeze the log). Reject the whole checkpoint.
if matches!(self.policy, AccessPolicy::AppendOnly)
&& !matches!(cp.policy, AccessPolicy::AppendOnly)
{
tracing::warn!(
"append-only violation: rejected owner checkpoint seq {} for store {} — it downgrades the terminal append_only policy to {}",
cp.checkpoint_seq,
self.id,
cp.policy
);
return false;
}
if matches!(self.policy, AccessPolicy::AppendOnly)
|| matches!(cp.policy, AccessPolicy::AppendOnly)
{
let signed_entries: HashMap<&str, &KvEntry> =
relayed.iter().map(|(k, e)| (*k, *e)).collect();
for key in self.keys.elements() {
let Some(local) = self.entries.get(key) else {
continue;
};
match signed_entries.get(key.as_str()) {
None => {
tracing::warn!(
"append-only violation: rejected owner checkpoint seq {} for store {} — it drops existing key {key:?}",
cp.checkpoint_seq,
self.id
);
return false;
}
Some(remote) if !entry_frozen_fields_equal(remote, local) => {
tracing::warn!(
"append-only violation: rejected owner checkpoint seq {} for store {} — it rewrites existing key {key:?}",
cp.checkpoint_seq,
self.id
);
return false;
}
_ => {}
}
}
}
// 7. Adopt: merge the entries as owner-authorized (bypass sender-auth).
for (key, (entry, tag)) in &delta.added {
let _ = self.keys.add(key.clone(), *tag);
if let Some(existing) = self.entries.get_mut(key) {
existing.merge(entry);
} else {
self.entries.insert(key.clone(), entry.clone());
}
}
for (key, entry) in &delta.updated {
if let Some(existing) = self.entries.get_mut(key) {
existing.merge(entry);
} else {
let _ = self.keys.add(key.clone(), (peer_id, 0));
self.entries.insert(key.clone(), entry.clone());
}
}
// 8. Full-replace to the owner-signed set. Step 6 proved the relayed
// (added ∪ updated) keys ARE the owner's complete signed state, so
// the store's state after adoption must be EXACTLY that set. Drop any
// local key not in it — that reflects owner deletions on a
// cold-recovering joiner WITHOUT trusting the untrusted `delta.removed`
// field. This is the authoritative full-replace: a relay-injected
// `removed` cannot truncate (it is ignored; the signed set wins), and
// a relay cannot resurrect or hide keys (a stale/mismatched relayed
// set fails step 6 and never reaches here). `delta.removed` is
// deliberately NOT consulted on the checkpoint-adopt path.
let signed_keys: std::collections::HashSet<&str> = delta
.added
.keys()
.map(String::as_str)
.chain(delta.updated.keys().map(String::as_str))
.collect();
let stale: Vec<String> = self
.keys
.elements()
.into_iter()
.filter(|k| !signed_keys.contains(k.as_str()))
.cloned()
.collect();
for key in stale {
let _ = self.keys.remove(&key);
self.entries.remove(&key);
}
// 9. Apply name update.
if let Some(name_register) = &delta.name_update {
self.name.merge(name_register);
}
// 10. Refresh policy (forward only) and cache the checkpoint.
// Belt-and-braces: AppendOnly is terminal — the 6b gate already
// rejected any checkpoint that would downgrade it, so this branch
// can only keep or adopt AppendOnly, never leave it.
let downgrades_terminal_policy = matches!(self.policy, AccessPolicy::AppendOnly)
&& !matches!(cp.policy, AccessPolicy::AppendOnly);
if cp.policy_version >= self.policy_version && !downgrades_terminal_policy {
self.policy = cp.policy.clone();
self.policy_version = cp.policy_version;
}
self.latest_checkpoint = Some(cp.clone());
self.highest_checkpoint_seq = cp.checkpoint_seq;
self.version += 1;
true
}
/// True when `cp` is a genuine checkpoint for this store's anchored owner
/// whose sequence is at or below the adopted high-water mark.
///
/// Only a verified owner checkpoint bound to this store may trigger the
/// stale-delta drop: an unverifiable or cross-store checkpoint falls
/// through to the sender-auth path unchanged, so a forged checkpoint
/// cannot be used to suppress legitimate writes. The writer's wire
/// signature covers the whole delta (checkpoint included), so a relay
/// cannot graft a stale checkpoint onto a fresh owner delta either.
fn is_subsumed_by_adopted_checkpoint(&self, cp: &OwnerCheckpoint) -> bool {
if cp.checkpoint_seq > self.highest_checkpoint_seq {
return false;
}
let Some(expected_owner) = self.owner else {
return false;
};
if cp.verify(&expected_owner).is_err() {
return false;
}
cp.store_id == self.id
}
/// After applying an incremental mutation via the sender-auth path, cache
/// the checkpoint if the resulting complete state matches the checkpoint's
/// content root.
///
/// This ensures a relay always carries the latest checkpoint after normal
/// multi-write/update/delete operations: after the owner publishes an
/// incremental delta (single-entry), the relay applies it, then
/// recomputes the root over its *complete* state. If it matches the
/// checkpoint root, the relay caches the checkpoint — so a subsequent
/// `full_delta` relays the correct, up-to-date checkpoint.
///
/// Does not mutate entries (already applied by the caller); only updates
/// `latest_checkpoint` and `highest_checkpoint_seq`.
fn maybe_cache_checkpoint(&mut self, cp: &OwnerCheckpoint) {
// Only advance for strictly newer checkpoints.
if cp.checkpoint_seq <= self.highest_checkpoint_seq {
return;
}
// Verify owner binding + signature (the checkpoint must be genuine).
let Some(expected_owner) = self.owner else {
return;
};
if cp.verify(&expected_owner).is_err() {
return;
}
if cp.store_id != self.id {
return;
}
// Cache only if the resulting complete state matches the checkpoint.
let matches = {
let pairs = self.checkpoint_pairs();
content_root(&self.id, self.name(), &pairs) == cp.content_root
};
if matches {
self.latest_checkpoint = Some(cp.clone());
self.highest_checkpoint_seq = cp.checkpoint_seq;
}
}
/// Merge another store into this one.
///
/// # Errors
///
/// - [`KvError::StoreIdMismatch`] if the ids differ.
/// - [`KvError::ImmutableKey`] under [`AccessPolicy::AppendOnly`] if the
/// merge would remove any locally-active key or change any of its
/// frozen fields. The merge is applied transactionally: on violation
/// NOTHING is applied (no partial merge). This closes the bypass where
/// a full-state merge (which skips every `merge_delta` gate) could
/// rewrite or tombstone append-only history. Currently this method has
/// no non-test callers — the live sync path is
/// [`merge_delta`](Self::merge_delta) — but it is public API, so the
/// invariant is enforced here too rather than removed (removal would be
/// a semver break; flagged for v0.33.0).
pub fn merge(&mut self, other: &KvStore) -> Result<()> {
if self.id != other.id {
return Err(KvError::StoreIdMismatch);
}
// AppendOnly: run the merge on a trial clone and verify the freeze
// invariant before committing, so a violating merge cannot leave
// partial state behind.
if matches!(self.policy, AccessPolicy::AppendOnly) {
let mut trial = self.clone();
trial.merge_unchecked(other)?;
for key in self.keys.elements() {
let Some(local) = self.get(key) else { continue };
match trial.get(key) {
None => {
return Err(KvError::ImmutableKey(key.clone()));
}
Some(merged) if !entry_frozen_fields_equal(merged, local) => {
return Err(KvError::ImmutableKey(key.clone()));
}
_ => {}
}
}
*self = trial;
return Ok(());
}
self.merge_unchecked(other)
}
/// The raw CRDT merge, without the AppendOnly freeze check.
fn merge_unchecked(&mut self, other: &KvStore) -> Result<()> {
self.keys
.merge_state(&other.keys)
.map_err(|e| KvError::Merge(format!("OR-Set merge failed: {e}")))?;
for (key, other_entry) in &other.entries {
if let Some(our_entry) = self.entries.get_mut(key) {
our_entry.merge(other_entry);
} else {
self.entries.insert(key.clone(), other_entry.clone());
}
}
// Merge allowlists (union)
for writer in &other.allowed_writers {
self.allowed_writers.insert(*writer);
}
self.name.merge(&other.name);
self.version += 1;
Ok(())
}
/// Generate a delta containing all state (for initial sync).
#[must_use]
pub fn full_delta(&self) -> KvStoreDelta {
let mut delta = KvStoreDelta::new(self.version);
// Walk the active-key OR-Set directly and look entries up, rather than
// cloning the whole key set into an intermediate HashSet first.
for key in self.keys.elements() {
if let Some(entry) = self.entries.get(key) {
let tag = (PeerId::new([0u8; 32]), 0);
delta.added.insert(key.clone(), (entry.clone(), tag));
}
}
delta.name_update = Some(self.name.clone());
// Include allowlist in full delta
if !self.allowed_writers.is_empty() {
delta.allowlist_additions = Some(self.allowed_writers.iter().copied().collect());
}
// Relay the latest owner-signed checkpoint so an anchored joiner can
// cold-recover this store's content even when relayed by a non-owner
// (the checkpoint's owner signature survives re-wrap).
delta.owner_checkpoint = self.latest_checkpoint.clone();
delta
}
}
#[cfg(test)]
mod tests {
use super::*;
fn agent(n: u8) -> AgentId {
AgentId([n; 32])
}
fn peer(n: u8) -> PeerId {
PeerId::new([n; 32])
}
fn store_id(n: u8) -> KvStoreId {
KvStoreId::new([n; 32])
}
#[test]
fn test_new_store() {
let owner = agent(1);
let store = KvStore::new(store_id(1), "Test".to_string(), owner, AccessPolicy::Signed);
assert_eq!(store.name(), "Test");
assert_eq!(store.len(), 0);
assert!(store.is_empty());
assert_eq!(store.owner(), Some(&owner));
assert_eq!(*store.policy(), AccessPolicy::Signed);
}
#[test]
fn test_put_and_get() {
let p = peer(1);
let mut store = KvStore::new(
store_id(1),
"Test".to_string(),
agent(1),
AccessPolicy::Signed,
);
store
.put(
"key1".to_string(),
b"hello".to_vec(),
"text/plain".to_string(),
p,
)
.expect("put");
let entry = store.get("key1").expect("get");
assert_eq!(entry.value, b"hello");
assert_eq!(store.len(), 1);
}
#[test]
fn test_put_update() {
let p = peer(1);
let mut store = KvStore::new(
store_id(1),
"Test".to_string(),
agent(1),
AccessPolicy::Signed,
);
store
.put(
"key1".to_string(),
b"old".to_vec(),
"text/plain".to_string(),
p,
)
.expect("put");
store
.put(
"key1".to_string(),
b"new".to_vec(),
"text/plain".to_string(),
p,
)
.expect("put");
assert_eq!(store.get("key1").expect("get").value, b"new");
assert_eq!(store.len(), 1);
}
#[test]
fn test_remove() {
let p = peer(1);
let mut store = KvStore::new(
store_id(1),
"Test".to_string(),
agent(1),
AccessPolicy::Signed,
);
store
.put(
"key1".to_string(),
b"val".to_vec(),
"text/plain".to_string(),
p,
)
.expect("put");
store.remove("key1").expect("remove");
assert!(store.get("key1").is_none());
}
#[test]
fn test_remove_nonexistent() {
let mut store = KvStore::new(
store_id(1),
"Test".to_string(),
agent(1),
AccessPolicy::Signed,
);
assert!(store.remove("nope").is_err());
}
#[test]
fn test_value_too_large() {
let p = peer(1);
let mut store = KvStore::new(
store_id(1),
"Test".to_string(),
agent(1),
AccessPolicy::Signed,
);
let big = vec![0u8; 100_000];
let result = store.put(
"big".to_string(),
big,
"application/octet-stream".to_string(),
p,
);
assert!(result.is_err());
}
#[test]
fn test_active_keys() {
let p = peer(1);
let mut store = KvStore::new(
store_id(1),
"Test".to_string(),
agent(1),
AccessPolicy::Signed,
);
store
.put("a".to_string(), b"1".to_vec(), "text/plain".to_string(), p)
.expect("put");
store
.put("b".to_string(), b"2".to_vec(), "text/plain".to_string(), p)
.expect("put");
store
.put("c".to_string(), b"3".to_vec(), "text/plain".to_string(), p)
.expect("put");
assert_eq!(store.active_keys().len(), 3);
}
#[test]
fn test_merge_stores() {
let p1 = peer(1);
let p2 = peer(2);
let id = store_id(1);
let owner = agent(1);
let mut s1 = KvStore::new(id, "Store".to_string(), owner, AccessPolicy::Signed);
let mut s2 = KvStore::new(id, "Store".to_string(), owner, AccessPolicy::Signed);
s1.put("a".to_string(), b"1".to_vec(), "text/plain".to_string(), p1)
.expect("put");
s2.put("b".to_string(), b"2".to_vec(), "text/plain".to_string(), p2)
.expect("put");
s1.merge(&s2).expect("merge");
assert_eq!(s1.len(), 2);
}
#[test]
fn test_merge_different_ids_fails() {
let owner = agent(1);
let mut s1 = KvStore::new(store_id(1), "A".to_string(), owner, AccessPolicy::Signed);
let s2 = KvStore::new(store_id(2), "B".to_string(), owner, AccessPolicy::Signed);
assert!(s1.merge(&s2).is_err());
}
#[test]
fn test_version_increments() {
let p = peer(1);
let mut store = KvStore::new(
store_id(1),
"Test".to_string(),
agent(1),
AccessPolicy::Signed,
);
assert_eq!(store.current_version(), 0);
store
.put("k".to_string(), b"v".to_vec(), "text/plain".to_string(), p)
.expect("put");
assert_eq!(store.current_version(), 1);
store.remove("k").expect("remove");
assert_eq!(store.current_version(), 2);
}
#[test]
fn test_store_id_from_content() {
let a = agent(1);
let id1 = KvStoreId::from_content("store1", &a);
let id2 = KvStoreId::from_content("store1", &a);
let id3 = KvStoreId::from_content("store2", &a);
assert_eq!(id1, id2);
assert_ne!(id1, id3);
}
#[test]
fn test_serialization_roundtrip() {
let p = peer(1);
let mut store = KvStore::new(
store_id(1),
"Test".to_string(),
agent(1),
AccessPolicy::Signed,
);
store
.put(
"key1".to_string(),
b"val".to_vec(),
"text/plain".to_string(),
p,
)
.expect("put");
let bytes = bincode::serialize(&store).expect("serialize");
let restored: KvStore = bincode::deserialize(&bytes).expect("deserialize");
assert_eq!(store.id(), restored.id());
assert_eq!(store.name(), restored.name());
assert_eq!(store.len(), restored.len());
}
#[test]
fn pre_wave_kvstore_blob_decodes_with_trailing_fields_defaulted() {
// Regression guard for the mid-struct bincode footgun. The ownership
// (anchor_channel, policy_version, ownership_conflict) and checkpoint
// (latest_checkpoint, highest_checkpoint_seq) fields were added by the
// security wave. bincode is positional, so those fields MUST be trailing
// AND decoded with `de_tolerant`; otherwise a blob written by the
// original `KvStore` shape (id..version) fails with UnexpectedEof.
//
// This mirror is the EXACT original serialized shape at commit b573441:
// id, keys, entries, name, policy, owner, allowed_writers, version.
#[derive(Serialize)]
struct PreWaveKvStore<'a> {
id: &'a KvStoreId,
keys: &'a OrSet<String>,
entries: &'a HashMap<String, KvEntry>,
name: &'a LwwRegister<String>,
policy: &'a AccessPolicy,
owner: &'a Option<AgentId>,
allowed_writers: &'a HashSet<AgentId>,
version: u64,
}
let owner = agent(1);
let mut store = KvStore::new(
store_id(1),
"Legacy".to_string(),
owner,
AccessPolicy::Signed,
);
store
.put(
"k".to_string(),
b"v".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put");
let legacy = PreWaveKvStore {
id: &store.id,
keys: &store.keys,
entries: &store.entries,
name: &store.name,
policy: &store.policy,
owner: &store.owner,
allowed_writers: &store.allowed_writers,
version: store.version,
};
let bytes = bincode::serialize(&legacy).expect("serialize pre-wave shape");
let restored: KvStore =
bincode::deserialize(&bytes).expect("pre-wave blob (id..version) must decode");
// Original content survives.
assert_eq!(restored.id(), store.id(), "id preserved");
assert_eq!(restored.len(), 1, "entries preserved");
assert_eq!(restored.owner, store.owner, "owner preserved");
// All five wave-added trailing fields default cleanly.
assert!(
restored.latest_checkpoint.is_none(),
"latest_checkpoint defaults"
);
assert_eq!(restored.highest_checkpoint_seq, 0, "high-water defaults");
assert_eq!(
restored.anchor_channel,
AnchorChannel::default(),
"anchor_channel defaults"
);
assert_eq!(restored.policy_version, 0, "policy_version defaults");
assert!(
restored.ownership_conflict.is_none(),
"ownership_conflict defaults"
);
}
#[test]
fn test_next_seq_monotonic() {
let store = KvStore::new(
store_id(1),
"Test".to_string(),
agent(1),
AccessPolicy::Signed,
);
let s1 = store.next_seq();
let s2 = store.next_seq();
assert!(s2 > s1);
}
// -- Access control tests --
#[test]
fn test_signed_policy_owner_authorized() {
let owner = agent(1);
let store = KvStore::new(store_id(1), "Test".to_string(), owner, AccessPolicy::Signed);
assert!(store.is_authorized(&owner));
}
#[test]
fn test_signed_policy_non_owner_rejected() {
let owner = agent(1);
let other = agent(2);
let store = KvStore::new(store_id(1), "Test".to_string(), owner, AccessPolicy::Signed);
assert!(!store.is_authorized(&other));
}
#[test]
fn test_signed_policy_rejects_unauthorized_delta() {
let owner = agent(1);
let attacker = agent(99);
let mut store = KvStore::new(store_id(1), "Test".to_string(), owner, AccessPolicy::Signed);
let entry = KvEntry::new(
"spam".to_string(),
b"junk".to_vec(),
"text/plain".to_string(),
);
let delta = KvStoreDelta::for_put("spam".to_string(), entry, (peer(99), 1), 1);
// Merge should succeed (silent rejection) but not apply the delta
store
.merge_delta(&delta, peer(99), Some(&attacker))
.expect("should not error");
assert!(store.get("spam").is_none(), "spam should be rejected");
}
#[test]
fn test_signed_policy_accepts_owner_delta() {
let owner = agent(1);
let mut store = KvStore::new(store_id(1), "Test".to_string(), owner, AccessPolicy::Signed);
let entry = KvEntry::new(
"legit".to_string(),
b"data".to_vec(),
"text/plain".to_string(),
);
let delta = KvStoreDelta::for_put("legit".to_string(), entry, (peer(1), 1), 1);
store
.merge_delta(&delta, peer(1), Some(&owner))
.expect("merge");
assert!(store.get("legit").is_some());
}
#[test]
fn test_allowlisted_policy() {
let owner = agent(1);
let writer = agent(2);
let outsider = agent(3);
let mut store = KvStore::new(
store_id(1),
"Team".to_string(),
owner,
AccessPolicy::Allowlisted,
);
// Owner can add writers
store.allow_writer(writer, &owner).expect("allow");
assert!(store.is_authorized(&owner));
assert!(store.is_authorized(&writer));
assert!(!store.is_authorized(&outsider));
}
#[test]
fn test_allowlisted_rejects_non_owner_allowlist_change() {
let owner = agent(1);
let other = agent(2);
let mut store = KvStore::new(
store_id(1),
"Team".to_string(),
owner,
AccessPolicy::Allowlisted,
);
let result = store.allow_writer(agent(3), &other);
assert!(result.is_err());
}
#[test]
fn test_deny_writer() {
let owner = agent(1);
let writer = agent(2);
let mut store = KvStore::new(
store_id(1),
"Team".to_string(),
owner,
AccessPolicy::Allowlisted,
);
store.allow_writer(writer, &owner).expect("allow");
assert!(store.is_authorized(&writer));
store.deny_writer(&writer, &owner).expect("deny");
assert!(!store.is_authorized(&writer));
}
#[test]
fn test_allowlist_delta_propagation() {
let owner = agent(1);
let writer = agent(2);
let mut store = KvStore::new(
store_id(1),
"Team".to_string(),
owner,
AccessPolicy::Allowlisted,
);
store.allow_writer(writer, &owner).expect("allow");
// Full delta should include the allowlist
let delta = store.full_delta();
assert!(delta.allowlist_additions.is_some());
assert!(delta
.allowlist_additions
.as_ref()
.is_some_and(|a| a.contains(&writer)));
}
#[test]
fn test_anonymous_delta_rejected_for_signed_store() {
let owner = agent(1);
let mut store = KvStore::new(store_id(1), "Test".to_string(), owner, AccessPolicy::Signed);
let entry = KvEntry::new(
"anon".to_string(),
b"spam".to_vec(),
"text/plain".to_string(),
);
let delta = KvStoreDelta::for_put("anon".to_string(), entry, (peer(99), 1), 1);
// No writer identity → rejected silently
store
.merge_delta(&delta, peer(99), None)
.expect("silent rejection");
assert!(store.get("anon").is_none());
}
// -- Local write authorization (fail closed) --
//
// WHY: a non-owner joiner that mutates its local replica creates a fork
// the owner's replica rejects — the local path must enforce the same
// policy as the inbound path.
#[test]
fn test_local_write_owner_authorized_on_signed_store() {
let owner = agent(1);
let store = KvStore::new(store_id(1), "Test".to_string(), owner, AccessPolicy::Signed);
store
.authorize_local_write(&owner)
.expect("owner must be able to write locally");
}
#[test]
fn test_local_write_non_owner_rejected_on_signed_store() {
let owner = agent(1);
let joiner = agent(2);
let store = KvStore::new(store_id(1), "Test".to_string(), owner, AccessPolicy::Signed);
let err = store
.authorize_local_write(&joiner)
.expect_err("non-owner local write must be rejected, not silently applied");
assert!(matches!(err, KvError::Unauthorized(_)));
assert!(
format!("{err}").contains(&hex::encode(owner.as_bytes())),
"rejection must name the true owner so the caller can tell why"
);
}
#[test]
fn test_no_anchor_join_is_read_only_unknown() {
// A joined replica with no expected owner is permanently read-only by
// design — the protocol never derives ownership from the network.
let joiner = agent(2);
let store =
KvStore::new_replica(store_id(1), String::new(), None, AnchorChannel::Persistence);
assert!(
store.owner().is_none(),
"no-anchor replica must not claim an owner"
);
assert!(matches!(store.ownership_source(), OwnershipSource::Unknown));
let err = store
.authorize_local_write(&joiner)
.expect_err("write on no-anchor store must fail closed");
assert!(matches!(err, KvError::OwnerUnknown));
}
#[test]
fn test_no_anchor_replica_rejects_inbound_deltas() {
// Fail closed on the inbound side too: without an anchored owner there
// is no authorized writer, so nothing merges (no silent mutation).
let mut store =
KvStore::new_replica(store_id(1), String::new(), None, AnchorChannel::Persistence);
let entry = KvEntry::new("k".to_string(), b"v".to_vec(), "text/plain".to_string());
let delta = KvStoreDelta::for_put("k".to_string(), entry, (peer(9), 1), 1);
store
.merge_delta(&delta, peer(9), Some(&agent(9)))
.expect("silent rejection");
assert!(store.get("k").is_none());
}
// -- learn_ownership: ownership is construction-only; announce can only
// refresh policy or record a conflict. It can NEVER establish ownership. --
#[test]
fn test_learn_ownership_rejects_third_party_assignment() {
// A third party must not assign ownership: the verified sender must
// equal the claimed owner.
let mut store =
KvStore::new_replica(store_id(1), String::new(), None, AnchorChannel::Persistence);
let owner = agent(1);
let rogue = agent(9);
let err = store
.learn_ownership(owner, AccessPolicy::Signed, 0, &rogue)
.expect_err("third-party ownership claim must be rejected");
assert!(matches!(err, KvError::OwnerTokenInvalid(_)));
assert!(store.owner().is_none());
}
#[test]
fn test_learn_ownership_rejects_none_to_some_first_capture_guard() {
// THE REGRESSION GUARD: even a verified SELF-claim must NOT establish
// ownership on a store that has none. `verified_sender == owner` is
// trivially satisfied by any self-claim, so allowing None→Some would
// let any agent that speaks first seize the topic (first-self-capture).
let mut store =
KvStore::new_replica(store_id(1), String::new(), None, AnchorChannel::Persistence);
let rogue = agent(9);
let err = store
.learn_ownership(rogue, AccessPolicy::Signed, 0, &rogue)
.expect_err("self-claim must not establish ownership on a no-anchor store");
assert!(matches!(err, KvError::OwnerTokenInvalid(_)));
assert!(
store.owner().is_none(),
"ownership must remain unestablished"
);
assert!(matches!(store.ownership_source(), OwnershipSource::Unknown));
}
#[test]
fn test_anchored_join_merges_owner_deltas_rejects_rogue() {
// Legitimate expected owner: anchored at construction. The owner's
// deltas merge; a rogue's are rejected. This also covers the
// v0.30.1-owner path — no announce is consulted on the data path.
let owner = agent(1);
let joiner = agent(2);
let rogue = agent(9);
let mut store = KvStore::new_replica(
store_id(1),
String::new(),
Some(owner),
AnchorChannel::RestParam,
);
assert_eq!(store.owner(), Some(&owner));
assert!(matches!(
store.ownership_source(),
OwnershipSource::Anchored {
owner: _,
channel: AnchorChannel::RestParam
}
));
// Local write by the joiner (not the owner): rejected.
assert!(matches!(
store.authorize_local_write(&joiner),
Err(KvError::Unauthorized(_))
));
// Inbound owner delta: accepted.
let entry = KvEntry::new("ok".to_string(), b"v".to_vec(), "text/plain".to_string());
let delta = KvStoreDelta::for_put("ok".to_string(), entry, (peer(1), 1), 1);
store
.merge_delta(&delta, peer(1), Some(&owner))
.expect("owner delta merges");
assert!(store.get("ok").is_some());
// Inbound rogue delta: rejected.
let entry = KvEntry::new("bad".to_string(), b"x".to_vec(), "text/plain".to_string());
let delta = KvStoreDelta::for_put("bad".to_string(), entry, (peer(9), 1), 2);
store
.merge_delta(&delta, peer(9), Some(&rogue))
.expect("silent rejection");
assert!(store.get("bad").is_none());
}
#[test]
fn test_first_capture_impossible_against_anchored_joiner() {
// An anchored joiner ignores a rogue's self-announce that arrives
// first; the legitimate owner's later announce refreshes policy only.
let owner = agent(1);
let rogue = agent(9);
let mut store = KvStore::new_replica(
store_id(1),
String::new(),
Some(owner),
AnchorChannel::RestParam,
);
// Rogue speaks first, attesting to itself.
let err = store
.learn_ownership(rogue, AccessPolicy::Allowlisted, 5, &rogue)
.expect_err("rogue self-claim against anchored owner must conflict");
assert!(
matches!(err, KvError::OwnershipConflict { anchored, claimed } if anchored == owner && claimed == rogue)
);
assert_eq!(store.owner(), Some(&owner), "anchored owner unchanged");
assert!(matches!(
store.ownership_source(),
OwnershipSource::Conflict { anchored, announced }
if anchored == owner && announced == rogue
));
// Legitimate owner announces with a forward policy_version: refresh is
// applied and the recorded conflict is cleared.
store
.learn_ownership(owner, AccessPolicy::Allowlisted, 1, &owner)
.expect("owner policy refresh");
assert_eq!(*store.policy(), AccessPolicy::Allowlisted);
assert!(matches!(
store.ownership_source(),
OwnershipSource::Anchored {
owner: _,
channel: AnchorChannel::RestParam
}
));
}
#[test]
fn test_ownership_immutable_conflict() {
// Once anchored, ownership is immutable; a conflicting claim is
// rejected and the conflict surfaced (ownership_status: conflict).
let owner = agent(1);
let hijacker = agent(9);
let mut store = KvStore::new_replica(
store_id(1),
String::new(),
Some(owner),
AnchorChannel::RestParam,
);
let err = store
.learn_ownership(hijacker, AccessPolicy::Signed, 0, &hijacker)
.expect_err("conflicting ownership claim must be rejected");
assert!(
matches!(err, KvError::OwnershipConflict { anchored, claimed } if anchored == owner && claimed == hijacker)
);
assert_eq!(store.owner(), Some(&owner));
assert!(matches!(
store.ownership_source(),
OwnershipSource::Conflict { anchored, announced }
if anchored == owner && announced == hijacker
));
}
#[test]
fn test_policy_refresh_monotonic_blocks_replay_downgrade() {
// A forward policy_version refresh applies; a replayed older one is
// dropped (no downgrade).
let owner = agent(1);
let mut store = KvStore::new_replica(
store_id(1),
String::new(),
Some(owner),
AnchorChannel::RestParam,
);
// Owner refreshes to Allowlisted at version 2.
store
.learn_ownership(owner, AccessPolicy::Allowlisted, 2, &owner)
.expect("forward refresh applies");
assert_eq!(*store.policy(), AccessPolicy::Allowlisted);
assert_eq!(store.policy_version(), 2);
// Replayed older announce (version 1, Signed) must NOT downgrade.
store
.learn_ownership(owner, AccessPolicy::Signed, 1, &owner)
.expect("stale replay dropped without error");
assert_eq!(
*store.policy(),
AccessPolicy::Allowlisted,
"policy not downgraded"
);
assert_eq!(store.policy_version(), 2);
}
#[test]
fn test_store_id_for_topic_owner_binds_owner() {
// for_topic_owner is the verifiable topic→owner binding: creator and
// anchored joiner agree, and a different owner yields a different id.
let owner = agent(1);
let rogue = agent(9);
let creator_id = KvStoreId::for_topic_owner("store/x", &owner);
let joiner_id = KvStoreId::for_topic_owner("store/x", &owner);
assert_eq!(creator_id, joiner_id, "creator and joiner agree on id");
assert_ne!(
KvStoreId::for_topic_owner("store/x", &owner),
KvStoreId::for_topic_owner("store/x", &rogue),
"different owner => different id"
);
// Distinct from the legacy from_content domain.
assert_ne!(
KvStoreId::for_topic_owner("store/x", &owner),
KvStoreId::from_content("store/x", &owner)
);
}
#[test]
fn test_v0_30_1_owner_converges_with_anchored_joiner_no_announce() {
// A v0.30.1 owner NEVER announces ownership. An anchored v0.31 joiner
// still converges because the data path (merge_delta) authorizes
// against the construction-time owner — no announce is consulted.
let owner = agent(1);
let joiner_agent = agent(2);
// Owner-side store with a written key, republished as a full delta
// (exactly what a holder — including a v0.30.1 owner — sends on a
// StateRequest).
let mut owner_store =
KvStore::new(store_id(1), "S".to_string(), owner, AccessPolicy::Signed);
owner_store
.put(
"k".to_string(),
b"v".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("owner put");
let full = owner_store.full_delta();
// Anchored joiner — no learn_ownership / announce ever happens.
let mut joiner = KvStore::new_replica(
store_id(1),
String::new(),
Some(owner),
AnchorChannel::RestParam,
);
joiner
.merge_delta(&full, peer(1), Some(&owner))
.expect("owner full-delta merges on an anchored joiner");
assert!(
joiner.get("k").is_some(),
"anchored joiner converges against a v0.30.1 owner with no announce"
);
// The joiner is not the owner, so it still cannot write locally.
assert!(matches!(
joiner.authorize_local_write(&joiner_agent),
Err(KvError::Unauthorized(_))
));
// And a no-anchor joiner in the same scenario stays empty (fail
// closed) — explicit incompatibility, not a silent deadlock.
let mut unanchored =
KvStore::new_replica(store_id(1), String::new(), None, AnchorChannel::Persistence);
unanchored
.merge_delta(&full, peer(1), Some(&owner))
.expect("silent rejection");
assert!(unanchored.get("k").is_none());
}
#[test]
fn test_local_write_encrypted_policy_stays_permissive() {
// The reserved Encrypted policy is permissive at the store layer on
// the inbound path; the local path must match it, not diverge.
let store = KvStore::new(
store_id(1),
"Test".to_string(),
agent(1),
AccessPolicy::Encrypted { group_id: vec![1] },
);
store
.authorize_local_write(&agent(9))
.expect("encrypted policy is permissive at the store layer");
}
#[test]
fn test_policy_display() {
assert_eq!(format!("{}", AccessPolicy::Signed), "signed");
assert_eq!(format!("{}", AccessPolicy::Allowlisted), "allowlisted");
assert_eq!(
format!(
"{}",
AccessPolicy::Encrypted {
group_id: vec![1, 2, 3]
}
),
"encrypted"
);
}
// -- Owner-signed checkpoint protocol (cold-recovery while owner offline) --
/// Build an owner-signed checkpoint for a store's current content.
fn checkpoint_for(
store: &KvStore,
topic: &str,
kp: &crate::identity::AgentKeypair,
seq: u64,
) -> OwnerCheckpoint {
let pairs = store.checkpoint_pairs();
let root = content_root(store.id(), store.name(), &pairs);
make_owner_checkpoint(OwnerCheckpointParams {
topic,
store_id: store.id(),
secret_key: kp.secret_key(),
public_key: kp.public_key(),
policy: store.policy(),
policy_version: store.policy_version(),
checkpoint_seq: seq,
content_root: root,
timestamp: 0,
})
.expect("sign checkpoint")
}
#[test]
fn cold_join_from_replica_with_owner_offline() {
// Owner writes + checkpoints, then is offline. A non-owner replica
// relays full_delta + checkpoint. An anchored joiner verifies the
// owner signature + content root and adopts — independent of relayer.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let relayer = agent(9);
let topic = "store/cold";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
owner_store
.put(
"k".to_string(),
b"v".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put");
let cp = checkpoint_for(&owner_store, topic, &kp, 1);
let mut delta = owner_store.full_delta();
delta.owner_checkpoint = Some(cp.clone());
// Anchored joiner; the relayer is NOT the owner.
let mut joiner =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
joiner
.merge_delta(&delta, peer(9), Some(&relayer))
.expect("checkpoint-gated merge");
assert!(joiner.get("k").is_some(), "adopted relayed owner content");
assert_eq!(joiner.highest_checkpoint_seq, 1);
}
#[test]
fn full_replace_ignores_relay_injected_removed() {
// A non-owner relay copies the owner's valid full-snapshot checkpoint of
// {k} and injects removed={k}. The full-replace adopt path IGNORES the
// untrusted `delta.removed` — the owner-signed set {k} is authoritative —
// so the injection cannot truncate the joiner's recovered state.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/inject";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
owner_store
.put(
"k".to_string(),
b"v".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put");
let cp = checkpoint_for(&owner_store, topic, &kp, 1);
let mut delta = owner_store.full_delta();
delta.owner_checkpoint = Some(cp);
let mut tags = std::collections::HashSet::new();
tags.insert((peer(9), 1));
delta.removed.insert("k".to_string(), tags);
let mut joiner =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
joiner
.merge_delta(&delta, peer(9), Some(&agent(9)))
.expect("merge");
assert!(
joiner.get("k").is_some(),
"injected removed must not truncate the owner-signed set"
);
assert_eq!(joiner.highest_checkpoint_seq, 1, "checkpoint adopted");
}
#[test]
fn stale_owner_delta_below_adopted_checkpoint_cannot_resurrect_deleted_keys() {
// v0.31.1 retest defect: owner writes k1 (checkpoint 1), later
// deletes it and writes k_final (checkpoint 2). A fresh anchored
// joiner cold-recovers checkpoint 2 ({k_final} only) from a relay,
// then the gossip replay/cache window re-delivers the owner's OLD
// k1 delta (still genuinely owner-signed, checkpoint 1 attached).
// The joiner holds no OR-Set tombstone for k1 — it never observed
// that add — so without the stale-delta gate the sender-auth path
// re-adds it, resurrecting an owner-deleted key.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/resurrect";
let id = KvStoreId::for_topic_owner(topic, &owner);
// Owner at time 1: state {k1}; the broadcast delta carries cp seq 1.
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
owner_store
.put(
"k1".to_string(),
b"alpha".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put k1");
let cp1 = checkpoint_for(&owner_store, topic, &kp, 1);
let mut stale_delta = owner_store.full_delta();
stale_delta.owner_checkpoint = Some(cp1);
// Owner at time 2: k1 deleted, k_final written; checkpoint seq 2.
owner_store.remove("k1").expect("remove k1");
owner_store
.put(
"k_final".to_string(),
b"final".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put k_final");
let cp2 = checkpoint_for(&owner_store, topic, &kp, 2);
let mut snapshot = owner_store.full_delta();
snapshot.owner_checkpoint = Some(cp2);
// Fresh anchored joiner cold-recovers checkpoint 2 via a relay.
let mut joiner =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
joiner
.merge_delta(&snapshot, peer(9), Some(&agent(9)))
.expect("adopt checkpoint 2");
assert!(joiner.get("k_final").is_some(), "recovered final state");
assert!(joiner.get("k1").is_none(), "k1 deleted in checkpoint 2");
assert_eq!(joiner.highest_checkpoint_seq, 2);
// Replay the stale owner delta (writer == owner, so the sender-auth
// path WOULD authorize it). The stale-delta gate must drop it.
joiner
.merge_delta(&stale_delta, peer(1), Some(&owner))
.expect("stale replay merge");
assert!(
joiner.get("k1").is_none(),
"owner-deleted key must not resurrect from a stale owner-signed delta"
);
assert_eq!(joiner.highest_checkpoint_seq, 2, "high-water unchanged");
}
#[test]
fn full_replace_drops_keys_absent_from_newer_checkpoint() {
// A replica holding {k1,k2} (from a seq-1 checkpoint) adopts a NEWER
// seq-2 checkpoint whose signed set is {k1} — the owner deleted k2.
// Full-replace drops k2; it is NOT resurrected. Proves checkpoint
// adoption is authoritative full-state, not additive (the exact
// delete-recovery invariant the soak's owner_offline gate exercises).
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/delrec";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
owner_store
.put(
"k1".to_string(),
b"a".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put k1");
owner_store
.put(
"k2".to_string(),
b"b".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put k2");
let cp1 = checkpoint_for(&owner_store, topic, &kp, 1);
let mut d1 = owner_store.full_delta();
d1.owner_checkpoint = Some(cp1);
let mut joiner =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
joiner
.merge_delta(&d1, peer(9), Some(&agent(9)))
.expect("adopt cp1");
assert!(
joiner.get("k1").is_some() && joiner.get("k2").is_some(),
"joiner recovered both keys from cp1"
);
// Owner deletes k2 and cuts a newer checkpoint over {k1}.
owner_store.remove("k2").expect("delete k2");
let cp2 = checkpoint_for(&owner_store, topic, &kp, 2);
let mut d2 = owner_store.full_delta();
d2.owner_checkpoint = Some(cp2);
joiner
.merge_delta(&d2, peer(9), Some(&agent(9)))
.expect("adopt cp2");
assert!(joiner.get("k1").is_some(), "k1 survives");
assert!(
joiner.get("k2").is_none(),
"k2 dropped by full-replace, not resurrected"
);
assert_eq!(joiner.highest_checkpoint_seq, 2);
}
#[test]
fn relay_tamper_rejected() {
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/tamper";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
owner_store
.put(
"k".to_string(),
b"v".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put");
let cp = checkpoint_for(&owner_store, topic, &kp, 1);
let mut delta = owner_store.full_delta();
// Tamper: mutate value AND recompute content_hash (an honest re-hash).
// The recomputed content_root no longer matches the checkpoint root.
if let Some((e, _)) = delta.added.get_mut("k") {
e.value = b"TAMPERED".to_vec();
e.content_hash = *blake3::hash(b"TAMPERED").as_bytes();
}
delta.owner_checkpoint = Some(cp);
let mut joiner =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
joiner
.merge_delta(&delta, peer(9), Some(&agent(9)))
.expect("no error");
assert!(
joiner.get("k").is_none(),
"tampered relay must not be adopted"
);
assert_eq!(joiner.highest_checkpoint_seq, 0);
}
#[test]
fn checkpoint_replay_downgrade_rejected() {
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/replay";
let id = KvStoreId::for_topic_owner(topic, &owner);
let owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
let cp_old = checkpoint_for(&owner_store, topic, &kp, 1);
let mut joiner =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
joiner.highest_checkpoint_seq = 5; // already adopted a newer checkpoint
let mut delta = KvStoreDelta::new(0);
delta.owner_checkpoint = Some(cp_old);
joiner
.merge_delta(&delta, peer(9), Some(&agent(9)))
.expect("no error");
assert_eq!(joiner.highest_checkpoint_seq, 5, "stale replay dropped");
}
#[test]
fn unanchored_joiner_rejects_checkpoint() {
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/unanchored";
let id = KvStoreId::for_topic_owner(topic, &owner);
let owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
let cp = checkpoint_for(&owner_store, topic, &kp, 1);
let mut delta = KvStoreDelta::new(0);
delta.owner_checkpoint = Some(cp);
// No-anchor replica: must never learn the owner from a relay.
let mut joiner = KvStore::new_replica(id, String::new(), None, AnchorChannel::Persistence);
joiner
.merge_delta(&delta, peer(9), Some(&agent(9)))
.expect("no error");
assert!(
joiner.owner().is_none(),
"owner never learned from checkpoint"
);
assert!(joiner.get("k").is_none());
}
#[test]
fn cross_store_checkpoint_replay_rejected() {
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic_a = "store/A";
let id_a = KvStoreId::for_topic_owner(topic_a, &owner);
let owner_store = KvStore::new(id_a, "A".to_string(), owner, AccessPolicy::Signed);
let cp = checkpoint_for(&owner_store, topic_a, &kp, 1);
// Replay onto a different store B (different topic -> different id).
let id_b = KvStoreId::for_topic_owner("store/B", &owner);
let mut delta = KvStoreDelta::new(0);
delta.owner_checkpoint = Some(cp);
let mut joiner_b =
KvStore::new_replica(id_b, String::new(), Some(owner), AnchorChannel::RestParam);
joiner_b
.merge_delta(&delta, peer(9), Some(&agent(9)))
.expect("no error");
assert_eq!(
joiner_b.highest_checkpoint_seq, 0,
"cross-store replay rejected"
);
}
#[test]
fn checkpoint_verify_rejects_forged_owner() {
// A checkpoint signed by a rogue key claiming a different owner must
// fail verification (owner binding + signature).
let owner = agent(1);
let rogue_kp = crate::identity::AgentKeypair::generate().expect("rogue keypair");
let topic = "store/forged";
let id = KvStoreId::for_topic_owner(topic, &owner);
// Rogue signs a checkpoint whose owner_pubkey is the ROGUE's key.
let cp = make_owner_checkpoint(OwnerCheckpointParams {
topic,
store_id: &id,
secret_key: rogue_kp.secret_key(),
public_key: rogue_kp.public_key(),
policy: &AccessPolicy::Signed,
policy_version: 0,
checkpoint_seq: 1,
content_root: [0u8; 32],
timestamp: 0,
})
.expect("sign");
// Verify against the REAL owner -> must fail (rogue pubkey != owner).
let err = cp.verify(&owner).expect_err("forged checkpoint rejected");
assert!(matches!(err, KvError::OwnerTokenInvalid(_)));
}
#[test]
fn owner_returns_advances_high_water_mark() {
// After a relay-adopt at seq N, a live owner delta (sender-auth) at a
// higher checkpoint seq merges and advances the high-water mark. No
// conflict between relay-adopt and live owner writes.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/return";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
owner_store
.put(
"k".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put");
let cp1 = checkpoint_for(&owner_store, topic, &kp, 1);
let mut relay = owner_store.full_delta();
relay.owner_checkpoint = Some(cp1);
// Joiner adopts the relay at seq 1.
let mut joiner =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
joiner
.merge_delta(&relay, peer(9), Some(&agent(9)))
.expect("relay adopt");
assert_eq!(joiner.highest_checkpoint_seq, 1);
// Owner writes a new key, then republishes its FULL state with a
// forward checkpoint at seq 2. The joiner re-verifies the owner sig +
// content root and adopts, advancing the high-water mark. (An
// incremental live delta would merge via sender-auth but not advance
// the mark, since the mark reflects root-verified full state.)
owner_store
.put(
"k2".to_string(),
b"v2".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put");
let cp2 = checkpoint_for(&owner_store, topic, &kp, 2);
let mut full2 = owner_store.full_delta();
full2.owner_checkpoint = Some(cp2);
joiner
.merge_delta(&full2, peer(9), Some(&agent(9)))
.expect("full relay adopt");
assert!(joiner.get("k2").is_some());
assert_eq!(joiner.highest_checkpoint_seq, 2);
}
// ====================================================================
// P0/P1 regression suite — owner-checkpoint relay integrity, full-state
// reconciliation, and durable high-water mark.
//
// These target the FIXED contract (v2 content_root binding every adopted
// field; content_hash==blake3(value) & outer_key==inner_key enforced
// before any mutation; incremental vs full-snapshot reconciliation;
// persisted checkpoint epoch). Each fails on the pre-fix tree and passes
// only with the complete commitment + full-snapshot reconciliation.
// ====================================================================
/// Deterministic (key, value, content_hash) view of a store's active state,
/// sorted by key, so two stores can be compared for EXACT equality
/// independent of HashMap iteration order.
fn snapshot(s: &KvStore) -> Vec<(String, Vec<u8>, [u8; 32])> {
let active = s.active_entries();
let mut v: Vec<_> = active
.iter()
.map(|e| (e.key.clone(), e.value.clone(), e.content_hash))
.collect();
v.sort_by(|a, b| a.0.cmp(&b.0));
v
}
/// Mirror of `Daemon::put_with_delta` + `produce_checkpoint`: perform an
/// owner local write, then build the incremental put-delta carrying an
/// owner-signed full-state checkpoint at the next sequence — exactly what
/// the live sync path publishes.
#[allow(clippy::too_many_arguments)]
fn owner_put_delta(
owner: &mut KvStore,
key: &str,
value: &[u8],
content_type: &str,
topic: &str,
kp: &crate::identity::AgentKeypair,
seq: u64,
p: PeerId,
) -> KvStoreDelta {
owner
.put(key.to_string(), value.to_vec(), content_type.to_string(), p)
.expect("owner put");
let entry = owner.get(key).cloned().expect("entry readable after put");
let version = owner.current_version();
let mut delta =
KvStoreDelta::for_put(key.to_string(), entry, (p, owner.next_seq()), version);
delta.owner_checkpoint = Some(checkpoint_for(owner, topic, kp, seq));
// Attach the owner's authoritative name so a fresh replica (name="")
// learns it from the incremental delta before maybe_cache_checkpoint
// recomputes the root — mirrors the lib.rs put_with_delta fix.
delta.name_update = Some(owner.name_register().clone());
delta
}
/// Mirror of `Daemon::remove_with_delta` + `produce_checkpoint`: remove a
/// key and build the incremental remove-delta carrying an owner-signed
/// full-state checkpoint at the next sequence.
fn owner_remove_delta(
owner: &mut KvStore,
key: &str,
topic: &str,
kp: &crate::identity::AgentKeypair,
seq: u64,
) -> KvStoreDelta {
owner.remove(key).expect("owner remove");
let mut d = KvStoreDelta::new(owner.current_version());
d.removed
.insert(key.to_string(), std::collections::HashSet::new());
d.owner_checkpoint = Some(checkpoint_for(owner, topic, kp, seq));
// Attach the owner's authoritative name (mirrors remove_with_delta).
d.name_update = Some(owner.name_register().clone());
d
}
#[test]
fn relay_forgery_per_field_tamper_rejected() {
// P0: a non-owner relay copies a valid full-snapshot checkpoint and
// mutates a SINGLE field the old content_root did not bind. The v2
// commitment (outer+inner key, value, content_hash, content_type,
// metadata, timestamps, name) plus the independent
// content_hash==blake3(value) / outer_key==inner_key checks must reject
// every variant WITHOUT mutating entries, policy, the checkpoint cache,
// or the high-water mark. The OR-Set `UniqueTag` is deliberately NOT
// bound (it is add/remove bookkeeping, not content provenance, and
// removals work by key), so a tag-only tamper is out of scope here.
//
// The pre-existing `relay_tamper_rejected` test mutated value AND
// recomputed content_hash (an honest re-hash); it therefore never
// exercised the actual exploit — swapping value while LEAVING
// content_hash untouched. This closes that gap and binds the rest.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/forgery";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "Legit".to_string(), owner, AccessPolicy::Signed);
owner_store
.put(
"k".to_string(),
b"v".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("owner put");
let cp = checkpoint_for(&owner_store, topic, &kp, 1);
// Legit control: an un-tampered non-owner relay IS adopted. This proves
// every rejection below is tamper detection, not the relayer identity.
{
let mut legit = owner_store.full_delta();
legit.owner_checkpoint = Some(cp.clone());
let mut j =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
j.merge_delta(&legit, peer(9), Some(&agent(9)))
.expect("legit adopt");
assert!(j.get("k").is_some(), "legit relay must adopt");
assert_eq!(j.highest_checkpoint_seq, 1);
}
#[allow(clippy::type_complexity)]
let mutators: Vec<(&str, Box<dyn FnOnce(&mut KvStoreDelta)>)> = vec![
// The real exploit: swap value, KEEP content_hash unchanged.
(
"value_swap_unchanged_hash",
Box::new(|d| {
d.added.get_mut("k").unwrap().0.value = b"PWNED".to_vec();
}),
),
(
"content_type",
Box::new(|d| {
d.added.get_mut("k").unwrap().0.content_type = "evil/x".to_string();
}),
),
(
"metadata",
Box::new(|d| {
d.added
.get_mut("k")
.unwrap()
.0
.metadata
.insert("injected".to_string(), "yes".to_string());
}),
),
(
"created_at",
Box::new(|d| {
d.added.get_mut("k").unwrap().0.created_at = 0;
}),
),
(
"updated_at",
Box::new(|d| {
d.added.get_mut("k").unwrap().0.updated_at = 0;
}),
),
(
"outer_key",
Box::new(|d| {
let pair = d.added.remove("k").unwrap();
d.added.insert("k2".to_string(), pair);
}),
),
(
"inner_key",
Box::new(|d| {
d.added.get_mut("k").unwrap().0.key = "k2".to_string();
}),
),
// OR-Set `UniqueTag` is intentionally NOT a case here: it is not
// bound by the checkpoint (removals work by key, not tag), so a
// tag-only tamper cannot forge owner-attributed content.
(
"store_name",
Box::new(|d| {
d.name_update
.as_mut()
.unwrap()
.set("EVIL".to_string(), peer(9));
}),
),
];
for (name, mutate) in mutators {
let mut delta = owner_store.full_delta();
delta.owner_checkpoint = Some(cp.clone());
mutate(&mut delta);
let mut joiner =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
joiner
.merge_delta(&delta, peer(9), Some(&agent(9)))
.expect("silent rejection never errors");
assert!(
joiner.get("k").is_none(),
"{name}: forged entry not adopted"
);
assert!(
joiner.get("k2").is_none(),
"{name}: forged outer-key entry not adopted"
);
assert!(joiner.entries.is_empty(), "{name}: entries untouched");
assert_eq!(
*joiner.policy(),
AccessPolicy::Signed,
"{name}: policy unchanged"
);
assert!(
joiner.latest_checkpoint.is_none(),
"{name}: checkpoint cache empty"
);
assert_eq!(
joiner.highest_checkpoint_seq, 0,
"{name}: high-water mark unchanged"
);
assert_ne!(joiner.name(), "EVIL", "{name}: store name not forged");
}
}
#[test]
fn relay_matches_owner_through_put_update_delete_sequence() {
// P0: checkpoint recovery must not break after normal multi-write /
// update / delete use. The relay receives the owner's published
// incremental deltas (each carrying an owner-signed full-state
// checkpoint) and must (a) match the owner's exact state after every
// step and (b) cache each checkpoint via maybe_cache_checkpoint.
// Pre-fix, an incremental put-delta carried a full-state root that did
// not match its single-entry set, so the checkpoint was never cached
// and a delete-to-empty short-circuited without applying `removed`.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/relay-exact";
let id = KvStoreId::for_topic_owner(topic, &owner);
let p = peer(1);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
let mut relay =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
let d1 = owner_put_delta(
&mut owner_store,
"k1",
b"v1",
"text/plain",
topic,
&kp,
1,
p,
);
relay.merge_delta(&d1, p, Some(&owner)).expect("relay k1");
assert_eq!(snapshot(&owner_store), snapshot(&relay), "after k1");
assert_eq!(
relay.highest_checkpoint_seq, 1,
"seq1 caches on a fresh replica (name propagated via the incremental delta)"
);
assert_eq!(
relay.name(),
"S",
"owner's real name propagated to the fresh replica"
);
let d2 = owner_put_delta(
&mut owner_store,
"k2",
b"v2",
"text/plain",
topic,
&kp,
2,
p,
);
relay.merge_delta(&d2, p, Some(&owner)).expect("relay k2");
assert_eq!(snapshot(&owner_store), snapshot(&relay), "after k2");
assert_eq!(
relay.highest_checkpoint_seq, 2,
"relay cached cp2 after incremental write (maybe_cache_checkpoint)"
);
let d3 = owner_put_delta(
&mut owner_store,
"k1",
b"v1b",
"application/json",
topic,
&kp,
3,
p,
);
relay
.merge_delta(&d3, p, Some(&owner))
.expect("relay update k1");
assert_eq!(snapshot(&owner_store), snapshot(&relay), "after update k1");
assert_eq!(relay.highest_checkpoint_seq, 3, "relay cached cp3");
let d4 = owner_remove_delta(&mut owner_store, "k1", topic, &kp, 4);
relay
.merge_delta(&d4, p, Some(&owner))
.expect("relay delete k1");
assert_eq!(snapshot(&owner_store), snapshot(&relay), "after delete k1");
assert!(relay.get("k1").is_none());
assert_eq!(relay.highest_checkpoint_seq, 4, "relay cached cp4");
// Delete down to empty — the case where the empty resulting root
// matched the empty relayed set and pre-fix short-circuited without
// applying `removed`, leaving replicas retaining the deleted key.
let d5 = owner_remove_delta(&mut owner_store, "k2", topic, &kp, 5);
relay
.merge_delta(&d5, p, Some(&owner))
.expect("relay delete k2");
assert_eq!(snapshot(&owner_store), snapshot(&relay), "after delete k2");
assert!(
relay.get("k2").is_none(),
"delete-to-empty reconciled on the checkpoint path"
);
assert!(
relay.active_entries().is_empty(),
"relay is empty, exactly matching the owner"
);
assert_eq!(relay.highest_checkpoint_seq, 5, "relay cached cp5");
}
#[test]
fn offline_anchored_joiner_recovers_multikey_state_from_relay() {
// P0: while the owner is offline, a fresh anchored joiner connected only
// to a non-owner relay must recover the owner's exact multi-key final
// state from the relayed owner checkpoint. Pre-fix, the relay never
// cached the post-second-write checkpoint (it held a stale one-key
// root), so its full delta's root mismatched the two-key relayed set
// and the joiner rejected recovery, ending empty.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/offline-recovery";
let id = KvStoreId::for_topic_owner(topic, &owner);
let p = peer(1);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
let mut relay =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
let d1 = owner_put_delta(
&mut owner_store,
"k1",
b"v1",
"text/plain",
topic,
&kp,
1,
p,
);
relay.merge_delta(&d1, p, Some(&owner)).expect("relay k1");
let d2 = owner_put_delta(
&mut owner_store,
"k2",
b"v2",
"text/plain",
topic,
&kp,
2,
p,
);
relay.merge_delta(&d2, p, Some(&owner)).expect("relay k2");
assert_eq!(
relay.highest_checkpoint_seq, 2,
"relay cached the two-key checkpoint"
);
// Owner offline: only the relay serves a full delta.
let relay_full = relay.full_delta();
assert!(
relay_full.owner_checkpoint.is_some(),
"relay carries a cached owner checkpoint for cold recovery"
);
let mut joiner =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
joiner
.merge_delta(&relay_full, peer(9), Some(&agent(9)))
.expect("cold-recovery merge");
assert_eq!(
snapshot(&joiner),
snapshot(&owner_store),
"joiner recovers the exact owner state from the relay"
);
assert_eq!(joiner.highest_checkpoint_seq, 2);
}
#[test]
fn checkpoint_high_water_mark_survives_restart_and_rejects_replay() {
// P0 durability: the checkpoint epoch / high-water mark must be durable.
// Pre-fix `highest_checkpoint_seq` and `latest_checkpoint` were
// `#[serde(skip)]`, so a restart reset them to 0 / None; a replayed
// already-adopted checkpoint was then treated as fresh and re-adopted.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/restart-replay";
let id = KvStoreId::for_topic_owner(topic, &owner);
let p = peer(1);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
owner_store
.put("k".to_string(), b"v".to_vec(), "text/plain".to_string(), p)
.expect("owner put");
let cp1 = checkpoint_for(&owner_store, topic, &kp, 1);
let mut snap1 = owner_store.full_delta();
snap1.owner_checkpoint = Some(cp1);
let mut replica =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
replica
.merge_delta(&snap1, peer(9), Some(&agent(9)))
.expect("adopt full snapshot");
assert_eq!(replica.highest_checkpoint_seq, 1);
assert!(replica.latest_checkpoint.is_some());
assert!(replica.get("k").is_some());
// Restart modeled as a durable bincode reload.
let bytes = bincode::serialize(&replica).expect("serialize");
let mut restarted: KvStore = bincode::deserialize(&bytes).expect("deserialize");
assert_eq!(
restarted.highest_checkpoint_seq, 1,
"highest_checkpoint_seq persisted across restart (no longer serde(skip))"
);
assert!(
restarted.latest_checkpoint.is_some(),
"latest_checkpoint persisted across restart"
);
// Replay the exact same full snapshot (seq 1): must be a stale no-op.
let v_before = restarted.current_version();
restarted
.merge_delta(&snap1, peer(9), Some(&agent(9)))
.expect("no error");
assert_eq!(
restarted.current_version(),
v_before,
"replay of already-adopted checkpoint must not mutate after restart"
);
assert_eq!(restarted.highest_checkpoint_seq, 1);
// A monotonically newer owner checkpoint still advances the mark.
owner_store
.put(
"k2".to_string(),
b"v2".to_vec(),
"text/plain".to_string(),
p,
)
.expect("owner put k2");
let cp2 = checkpoint_for(&owner_store, topic, &kp, 2);
let mut snap2 = owner_store.full_delta();
snap2.owner_checkpoint = Some(cp2);
restarted
.merge_delta(&snap2, peer(9), Some(&agent(9)))
.expect("adopt newer");
assert_eq!(
restarted.highest_checkpoint_seq, 2,
"newer checkpoint advances"
);
assert!(restarted.get("k2").is_some());
}
// ── AppendOnly policy ───────────────────────────────────────────────
//
// WHY these tests exist: AppendOnly makes an owner-signed store
// tamper-evident against its OWN author. Every path an owner (or anyone)
// could use to rewrite or truncate history — local put/remove, remote
// deltas, owner-signed checkpoint adoption — must refuse to touch an
// existing key. If any of these tests can pass while an existing key's
// bytes change or disappear, the policy's entire guarantee is void.
fn append_only_owner_store(owner: AgentId) -> KvStore {
let mut store = KvStore::new(
store_id(7),
"log".to_string(),
owner,
AccessPolicy::AppendOnly,
);
store
.put(
"k1".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("initial append");
store
}
#[test]
fn append_only_put_existing_key_different_content_rejected() {
let owner = agent(1);
let mut store = append_only_owner_store(owner);
let err = store
.put(
"k1".to_string(),
b"REWRITTEN".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect_err("owner must not be able to rewrite an existing key");
assert!(matches!(err, KvError::ImmutableKey(ref k) if k == "k1"));
assert_eq!(
store.get("k1").map(|e| e.value.clone()),
Some(b"v1".to_vec()),
"original bytes retained"
);
}
#[test]
fn append_only_put_identical_content_is_idempotent_noop() {
let owner = agent(1);
let mut store = append_only_owner_store(owner);
let v_before = store.current_version();
store
.put(
"k1".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("byte-identical re-put is accepted (retry-friendly)");
assert_eq!(
store.current_version(),
v_before,
"idempotent re-put is a no-op: no version bump, no state change"
);
// Same bytes but a different content type is a mutation — rejected.
let err = store
.put(
"k1".to_string(),
b"v1".to_vec(),
"application/json".to_string(),
peer(1),
)
.expect_err("content-type change on an existing key is a mutation");
assert!(matches!(err, KvError::ImmutableKey(_)));
}
#[test]
fn append_only_remove_rejected() {
let owner = agent(1);
let mut store = append_only_owner_store(owner);
let err = store
.remove("k1")
.expect_err("owner must not be able to delete an existing key");
assert!(matches!(err, KvError::ImmutableKey(ref k) if k == "k1"));
assert!(
store.get("k1").is_some(),
"key retained after rejected delete"
);
// A key that never existed still reports KeyNotFound (unchanged).
assert!(matches!(
store.remove("ghost"),
Err(KvError::KeyNotFound(_))
));
}
#[test]
fn append_only_owner_delta_rewrite_skipped_value_retained() {
// A hostile delta authored by the OWNER updating an existing key must
// be skipped: owner-signed is not exempt from immutability.
let owner = agent(1);
let mut store = append_only_owner_store(owner);
let mut delta = KvStoreDelta::new(99);
delta.added.insert(
"k1".to_string(),
(
KvEntry::new(
"k1".to_string(),
b"REWRITTEN".to_vec(),
"text/plain".to_string(),
),
(peer(2), 42),
),
);
// New keys in the same delta must still append fine. (k1 must NOT
// also appear in `updated` here — the global canonical-map gate
// drops any delta carrying one key in both maps; that shape has its
// own tests.)
delta.added.insert(
"k2".to_string(),
(
KvEntry::new("k2".to_string(), b"v2".to_vec(), "text/plain".to_string()),
(peer(2), 43),
),
);
store
.merge_delta(&delta, peer(2), Some(&owner))
.expect("violations are skipped, not errors — delta not poisoned");
assert_eq!(
store.get("k1").map(|e| e.value.clone()),
Some(b"v1".to_vec()),
"existing key retained its original bytes"
);
assert_eq!(
store.get("k2").map(|e| e.value.clone()),
Some(b"v2".to_vec()),
"appends in the same delta still apply"
);
// The `updated` path is gated identically (separate delta so the
// canonical-map gate does not trigger).
let mut delta2 = KvStoreDelta::new(100);
delta2.updated.insert(
"k1".to_string(),
KvEntry::new(
"k1".to_string(),
b"REWRITTEN-2".to_vec(),
"text/plain".to_string(),
),
);
store
.merge_delta(&delta2, peer(2), Some(&owner))
.expect("updated-path violation skipped");
assert_eq!(
store.get("k1").map(|e| e.value.clone()),
Some(b"v1".to_vec()),
"updated-path rewrite skipped too"
);
}
#[test]
fn append_only_owner_delta_removal_skipped_key_retained() {
let owner = agent(1);
let mut store = append_only_owner_store(owner);
let mut delta = KvStoreDelta::new(99);
delta.removed.insert("k1".to_string(), HashSet::new());
store
.merge_delta(&delta, peer(2), Some(&owner))
.expect("removal is skipped, not an error");
assert!(
store.get("k1").is_some(),
"owner-signed removal must not delete an append-only key"
);
}
#[test]
fn append_only_fresh_joiner_adopts_first_checkpoint() {
// Cold start: a fresh anchored joiner has no local keys, so the
// immutability gate is trivially satisfied and adoption proceeds.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/ao-cold";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::AppendOnly);
owner_store
.put(
"k1".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("owner append");
let cp = checkpoint_for(&owner_store, topic, &kp, 1);
let mut snap = owner_store.full_delta();
snap.owner_checkpoint = Some(cp);
let mut joiner =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
joiner
.merge_delta(&snap, peer(9), Some(&agent(9)))
.expect("fresh joiner adopts");
assert_eq!(joiner.highest_checkpoint_seq, 1);
assert_eq!(
joiner.get("k1").map(|e| e.value.clone()),
Some(b"v1".to_vec())
);
assert_eq!(
*joiner.policy(),
AccessPolicy::AppendOnly,
"joiner learns the append-only policy from the checkpoint"
);
}
/// Build an owner-signed "rewritten history" snapshot: a fresh store with
/// the given entries, checkpointed at `seq`. Models an owner forging a
/// past-state replacement offline.
fn forged_snapshot(
id: KvStoreId,
owner: AgentId,
kp: &crate::identity::AgentKeypair,
topic: &str,
entries: &[(&str, &[u8])],
seq: u64,
) -> KvStoreDelta {
let mut forged = KvStore::new(id, "S".to_string(), owner, AccessPolicy::AppendOnly);
for (k, v) in entries {
forged
.put(
(*k).to_string(),
v.to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("forge put");
}
let cp = checkpoint_for(&forged, topic, kp, seq);
let mut snap = forged.full_delta();
snap.owner_checkpoint = Some(cp);
snap
}
#[test]
fn append_only_checkpoint_shrinking_keyset_rejected() {
// An owner-signed checkpoint that DROPS an existing key must be
// rejected on a non-fresh replica: local state intact, high-water
// mark not advanced. An owner truncating its own log is exactly the
// attack this policy exists to stop.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/ao-shrink";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::AppendOnly);
for (k, v) in [("k1", b"v1".as_slice()), ("k2", b"v2".as_slice())] {
owner_store
.put(k.to_string(), v.to_vec(), "text/plain".to_string(), peer(1))
.expect("owner append");
}
let cp1 = checkpoint_for(&owner_store, topic, &kp, 1);
let mut snap1 = owner_store.full_delta();
snap1.owner_checkpoint = Some(cp1);
let mut replica =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
replica
.merge_delta(&snap1, peer(9), Some(&agent(9)))
.expect("initial adoption");
assert_eq!(replica.highest_checkpoint_seq, 1);
// Owner forges history without k2.
let snap2 = forged_snapshot(id, owner, &kp, topic, &[("k1", b"v1")], 2);
replica
.merge_delta(&snap2, peer(9), Some(&owner))
.expect("rejection is loud in logs but not an error");
assert!(
replica.get("k2").is_some(),
"checkpoint that shrinks the keyset must not delete k2"
);
assert_eq!(
replica.highest_checkpoint_seq, 1,
"forged checkpoint must not advance the high-water mark"
);
}
#[test]
fn append_only_checkpoint_rewriting_value_rejected() {
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/ao-rewrite";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::AppendOnly);
owner_store
.put(
"k1".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("owner append");
let cp1 = checkpoint_for(&owner_store, topic, &kp, 1);
let mut snap1 = owner_store.full_delta();
snap1.owner_checkpoint = Some(cp1);
let mut replica =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
replica
.merge_delta(&snap1, peer(9), Some(&agent(9)))
.expect("initial adoption");
// Owner forges history with k1 rewritten (same keyset, new bytes).
let snap2 = forged_snapshot(id, owner, &kp, topic, &[("k1", b"REWRITTEN")], 2);
replica
.merge_delta(&snap2, peer(9), Some(&owner))
.expect("rejection is loud in logs but not an error");
assert_eq!(
replica.get("k1").map(|e| e.value.clone()),
Some(b"v1".to_vec()),
"checkpoint rewriting an existing key must not change its bytes"
);
assert_eq!(replica.highest_checkpoint_seq, 1);
}
#[test]
fn signed_store_owner_update_and_delete_still_allowed() {
// Regression guard: AppendOnly enforcement must not leak into Signed
// stores — the owner's normal update/delete cycle is unchanged.
let owner = agent(1);
let mut store = KvStore::new(
store_id(8),
"plain".to_string(),
owner,
AccessPolicy::Signed,
);
store
.put(
"k".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put");
store
.put(
"k".to_string(),
b"v2".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("Signed store update must still work");
assert_eq!(
store.get("k").map(|e| e.value.clone()),
Some(b"v2".to_vec())
);
store
.remove("k")
.expect("Signed store delete must still work");
assert!(store.get("k").is_none());
}
// ── AppendOnly hardening (adversarial-review wave) ──────────────────
#[test]
fn append_only_downgrade_announce_rejected() {
// WHY: if an owner-signed announce could flip append_only back to
// signed, the owner could downgrade, delete freely, and re-upgrade —
// the policy would be decorative. AppendOnly must be terminal for
// ANY policy_version (forward or equal).
let owner = agent(1);
let mut store = append_only_owner_store(owner);
let v = store.policy_version();
// Forward-version downgrade: rejected.
let err = store
.learn_ownership(owner, AccessPolicy::Signed, v + 10, &owner)
.expect_err("forward-version downgrade must be rejected");
assert!(matches!(err, KvError::OwnerTokenInvalid(_)));
assert_eq!(*store.policy(), AccessPolicy::AppendOnly);
// Equal-version downgrade: rejected.
let err = store
.learn_ownership(owner, AccessPolicy::Signed, v, &owner)
.expect_err("equal-version downgrade must be rejected");
assert!(matches!(err, KvError::OwnerTokenInvalid(_)));
assert_eq!(*store.policy(), AccessPolicy::AppendOnly);
// A refresh that KEEPS append_only is still fine.
store
.learn_ownership(owner, AccessPolicy::AppendOnly, v + 1, &owner)
.expect("append_only-preserving refresh is allowed");
assert_eq!(*store.policy(), AccessPolicy::AppendOnly);
}
#[test]
fn append_only_checkpoint_policy_downgrade_rejected() {
// WHY: the checkpoint adoption path refreshes policy from cp.policy
// (step 10). A content-identical checkpoint whose only change is
// policy=Signed would otherwise downgrade the replica, unfreezing
// the log. Content equality means the immutability gate alone
// cannot catch this — the terminal-policy gate must.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/ao-downgrade";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::AppendOnly);
owner_store
.put(
"k1".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("owner append");
let cp1 = checkpoint_for(&owner_store, topic, &kp, 1);
let mut snap1 = owner_store.full_delta();
snap1.owner_checkpoint = Some(cp1.clone());
let mut replica =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
replica
.merge_delta(&snap1, peer(9), Some(&agent(9)))
.expect("initial adoption");
assert_eq!(*replica.policy(), AccessPolicy::AppendOnly);
// Forge: identical content, policy flipped to Signed, newer seq +
// newer policy_version.
let mut forged = KvStore::new(id, "S".to_string(), owner, AccessPolicy::Signed);
forged
.put(
"k1".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("forge put");
let cp2 = checkpoint_for(&forged, topic, &kp, 2);
let mut snap2 = forged.full_delta();
snap2.owner_checkpoint = Some(cp2);
replica
.merge_delta(&snap2, peer(9), Some(&owner))
.expect("rejection is loud in logs but not an error");
assert_eq!(
*replica.policy(),
AccessPolicy::AppendOnly,
"append_only is terminal: a policy-downgrading checkpoint must not apply"
);
assert_eq!(replica.highest_checkpoint_seq, 1);
}
#[test]
fn adoption_rejects_key_in_both_added_and_updated() {
// WHY: adoption validates one merged view of (added ∪ updated) but
// applies both maps in sequence — a crafted delta carrying the same
// key twice with different values could rewrite what was validated.
// The canonical-map gate must reject the ambiguity outright.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/ao-dup";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::AppendOnly);
owner_store
.put(
"k1".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("owner append");
let cp1 = checkpoint_for(&owner_store, topic, &kp, 1);
let mut snap1 = owner_store.full_delta();
snap1.owner_checkpoint = Some(cp1.clone());
let mut replica =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
replica
.merge_delta(&snap1, peer(9), Some(&agent(9)))
.expect("initial adoption");
// Craft the REAL attack: k1 in `added` with EVIL bytes and a maxed
// LWW timestamp (so adoption's entry merge would keep it), k1 in
// `updated` with the benign local entry (so a last-wins validation
// map sees only the benign copy), and a checkpoint the "owner"
// signed over the DUPLICATED relayed multiset — which is exactly
// what step 6's root computation hashes, so without the
// canonical-map gate the root check passes while adoption ends on
// the evil bytes.
let benign = replica.get("k1").expect("local k1").clone();
let mut evil = KvEntry::new(
"k1".to_string(),
b"REWRITTEN".to_vec(),
"text/plain".to_string(),
);
evil.updated_at = u64::MAX;
let multiset_root = content_root(&id, "S", &[("k1", &evil), ("k1", &benign)]);
let cp2 = make_owner_checkpoint(OwnerCheckpointParams {
topic,
store_id: &id,
secret_key: kp.secret_key(),
public_key: kp.public_key(),
policy: &AccessPolicy::AppendOnly,
policy_version: 0,
checkpoint_seq: 2,
content_root: multiset_root,
timestamp: 0,
})
.expect("sign forged multiset checkpoint");
let mut dup = KvStoreDelta::new(99);
dup.added.insert("k1".to_string(), (evil, (peer(2), 42)));
dup.updated.insert("k1".to_string(), benign);
dup.name_update = Some(owner_store.name_register().clone());
dup.owner_checkpoint = Some(cp2);
replica
.merge_delta(&dup, peer(9), Some(&owner))
.expect("rejected adoption falls through safely");
assert_eq!(
replica.get("k1").map(|e| e.value.clone()),
Some(b"v1".to_vec()),
"duplicate-key delta must not rewrite the validated value"
);
assert_eq!(
replica.highest_checkpoint_seq, 1,
"forged multiset checkpoint must not advance the high-water mark"
);
}
#[test]
fn append_only_public_merge_rejected_transactionally() {
// WHY: KvStore::merge is public API that bypasses every merge_delta
// gate. It must enforce the same freeze — and atomically, so a
// violating merge cannot leave partial state behind.
let owner = agent(1);
let mut store = append_only_owner_store(owner);
let v_before = store.current_version();
// Hostile full-state replica: k1 rewritten (newer LWW timestamp so
// the entry merge would pick it), plus an innocent new key k9 that
// must NOT survive the rejected transaction.
let mut hostile = KvStore::new(
*store.id(),
"log".to_string(),
owner,
AccessPolicy::AppendOnly,
);
hostile
.put(
"k1".to_string(),
b"REWRITTEN".to_vec(),
"text/plain".to_string(),
peer(2),
)
.expect("hostile put");
hostile
.put(
"k9".to_string(),
b"new".to_vec(),
"text/plain".to_string(),
peer(2),
)
.expect("hostile put");
if let Some(e) = hostile.entries.get_mut("k1") {
e.updated_at = u64::MAX; // guarantee LWW would pick the rewrite
}
let err = store
.merge(&hostile)
.expect_err("public merge must reject an append-only rewrite");
assert!(matches!(err, KvError::ImmutableKey(_)));
assert_eq!(
store.get("k1").map(|e| e.value.clone()),
Some(b"v1".to_vec()),
"value retained"
);
assert!(
store.get("k9").is_none(),
"rejected merge must be transactional — no partial application"
);
assert_eq!(store.current_version(), v_before, "no state change at all");
// A purely-additive merge still works.
let mut additive = KvStore::new(
*store.id(),
"log".to_string(),
owner,
AccessPolicy::AppendOnly,
);
additive
.put(
"k2".to_string(),
b"v2".to_vec(),
"text/plain".to_string(),
peer(2),
)
.expect("additive put");
store.merge(&additive).expect("additive merge is allowed");
assert!(store.get("k1").is_some() && store.get("k2").is_some());
}
#[test]
fn append_only_delta_metadata_mutation_with_identical_bytes_skipped() {
// WHY: entries are frozen in FULL. KvEntry::merge is LWW on
// updated_at and replaces metadata wholesale — a same-value entry
// with a newer timestamp could otherwise mutate metadata/updated_at
// while the bytes "look" unchanged.
let owner = agent(1);
let mut store = append_only_owner_store(owner);
let (meta_before, updated_before) = {
let e = store.get("k1").expect("k1");
(e.metadata.clone(), e.updated_at)
};
let mut sneaky = KvEntry::new("k1".to_string(), b"v1".to_vec(), "text/plain".to_string());
sneaky
.metadata
.insert("injected".to_string(), "gotcha".to_string());
sneaky.updated_at = u64::MAX; // LWW would pick this entry
let mut delta = KvStoreDelta::new(99);
delta.added.insert("k1".to_string(), (sneaky, (peer(2), 7)));
store
.merge_delta(&delta, peer(2), Some(&owner))
.expect("skipped, not an error");
let e = store.get("k1").expect("k1 retained");
assert_eq!(e.metadata, meta_before, "metadata frozen");
assert_eq!(e.updated_at, updated_before, "updated_at frozen");
}
#[test]
fn two_fresh_joiners_conflicting_snapshots_diverge_detectably() {
// WHY (documented limitation, P0-D): a fresh joiner has no prior
// state, so it MUST trust the owner's current signed snapshot —
// signatures cannot distinguish original history from a rewrite.
// Two fresh joiners fed different owner-signed snapshots therefore
// diverge. The detection surface is the adopted checkpoint content
// root: they differ, and neither replica auto-reconciles (later
// cross-delivered snapshots hit the immutability gate).
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/ao-fork";
let id = KvStoreId::for_topic_owner(topic, &owner);
let snap_x = forged_snapshot(id, owner, &kp, topic, &[("k", b"x")], 1);
let snap_y = forged_snapshot(id, owner, &kp, topic, &[("k", b"y")], 1);
let mut a = KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
let mut b = KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
a.merge_delta(&snap_x, peer(9), Some(&agent(9)))
.expect("A adopts X");
b.merge_delta(&snap_y, peer(9), Some(&agent(9)))
.expect("B adopts Y");
assert_eq!(a.get("k").map(|e| e.value.clone()), Some(b"x".to_vec()));
assert_eq!(b.get("k").map(|e| e.value.clone()), Some(b"y".to_vec()));
assert_eq!(a.highest_checkpoint_seq, 1);
assert_eq!(b.highest_checkpoint_seq, 1);
let root_a = a.latest_checkpoint.as_ref().expect("A cp").content_root;
let root_b = b.latest_checkpoint.as_ref().expect("B cp").content_root;
assert_ne!(
root_a, root_b,
"divergence is detectable by comparing adopted checkpoint roots"
);
// Cross-feed: A now DROPS the other snapshot (same seq → the
// stale-delta gate; a newer-seq rewrite would hit the immutability
// gate instead) — the fork is sticky and visible, never silently
// reconciled.
a.merge_delta(&snap_y, peer(9), Some(&owner))
.expect("skip, not error");
assert_eq!(
a.get("k").map(|e| e.value.clone()),
Some(b"x".to_vec()),
"A keeps its observed history"
);
}
#[test]
fn rejected_truncated_checkpoint_does_not_poison_later_legit_flow() {
// WHY: interaction with the PR #230 stale-delta gate. A rejected
// forged checkpoint must not advance the high-water mark (else it
// would stale-drop legitimate owner deltas), and a later LEGITIMATE
// superset checkpoint must still adopt normally, while replays of
// old snapshots stay stale-dropped.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/ao-truncate";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::AppendOnly);
for (k, v) in [("k1", b"v1".as_slice()), ("k2", b"v2".as_slice())] {
owner_store
.put(k.to_string(), v.to_vec(), "text/plain".to_string(), peer(1))
.expect("owner append");
}
let cp1 = checkpoint_for(&owner_store, topic, &kp, 1);
let mut snap1 = owner_store.full_delta();
snap1.owner_checkpoint = Some(cp1);
let mut replica =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
replica
.merge_delta(&snap1, peer(9), Some(&agent(9)))
.expect("initial adoption");
assert_eq!(replica.highest_checkpoint_seq, 1);
// Forged truncation at seq 2: rejected, HWM must NOT move.
let forged = forged_snapshot(id, owner, &kp, topic, &[("k1", b"v1")], 2);
replica
.merge_delta(&forged, peer(9), Some(&owner))
.expect("skip, not error");
assert!(replica.get("k2").is_some(), "truncation rejected");
assert_eq!(
replica.highest_checkpoint_seq, 1,
"rejected forge must not advance HWM (would stale-drop legit deltas)"
);
// Legit superset at seq 3 still adopts.
owner_store
.put(
"k3".to_string(),
b"v3".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("owner append k3");
let cp3 = checkpoint_for(&owner_store, topic, &kp, 3);
let mut snap3 = owner_store.full_delta();
snap3.owner_checkpoint = Some(cp3);
replica
.merge_delta(&snap3, peer(9), Some(&agent(9)))
.expect("legit superset adopts");
assert_eq!(replica.highest_checkpoint_seq, 3);
assert!(replica.get("k3").is_some());
// Replay of the old seq-1 snapshot: stale-dropped, no mutation.
let v_before = replica.current_version();
replica
.merge_delta(&snap1, peer(9), Some(&agent(9)))
.expect("stale replay is a no-op");
assert_eq!(replica.current_version(), v_before);
assert_eq!(replica.highest_checkpoint_seq, 3);
}
#[test]
fn skip_only_delta_does_not_advance_hwm_or_replace_checkpoint() {
// WHY: when every mutation in a hostile delta is skipped, the
// attached (genuine, newer-seq) checkpoint must not be cached either
// — the post-merge state root does not match it. HWM and
// latest_checkpoint must be exactly what they were.
let kp = crate::identity::AgentKeypair::generate().expect("keypair");
let owner = kp.agent_id();
let topic = "store/ao-skiponly";
let id = KvStoreId::for_topic_owner(topic, &owner);
let mut owner_store = KvStore::new(id, "S".to_string(), owner, AccessPolicy::AppendOnly);
owner_store
.put(
"k1".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("owner append");
let cp1 = checkpoint_for(&owner_store, topic, &kp, 1);
let mut snap1 = owner_store.full_delta();
snap1.owner_checkpoint = Some(cp1.clone());
let mut replica =
KvStore::new_replica(id, String::new(), Some(owner), AnchorChannel::RestParam);
replica
.merge_delta(&snap1, peer(9), Some(&agent(9)))
.expect("initial adoption");
let root_before = replica
.latest_checkpoint
.as_ref()
.expect("cp cached")
.content_root;
// Hostile: rewrite-only delta with a genuine seq-2 checkpoint over
// the forged state.
let hostile = forged_snapshot(id, owner, &kp, topic, &[("k1", b"REWRITTEN")], 2);
replica
.merge_delta(&hostile, peer(9), Some(&owner))
.expect("skip, not error");
assert_eq!(replica.highest_checkpoint_seq, 1, "HWM unchanged");
assert_eq!(
replica
.latest_checkpoint
.as_ref()
.expect("cp still cached")
.content_root,
root_before,
"latest_checkpoint unchanged after a skip-only delta"
);
}
#[test]
fn append_only_ambiguous_delta_dropped_without_checkpoint() {
// Standalone global-gate case: no checkpoint attached, so the
// adoption path is never entered — this exercises merge_delta's own
// canonical-map gate on an AppendOnly store. Even a NEW key (no
// immutability conflict at all) carried in both maps drops the
// whole delta.
let owner = agent(1);
let mut store = append_only_owner_store(owner);
let v_before = store.current_version();
let mut dup = KvStoreDelta::new(77);
dup.added.insert(
"fresh".to_string(),
(
KvEntry::new("fresh".to_string(), b"a".to_vec(), "text/plain".to_string()),
(peer(2), 11),
),
);
dup.updated.insert(
"fresh".to_string(),
KvEntry::new("fresh".to_string(), b"b".to_vec(), "text/plain".to_string()),
);
store
.merge_delta(&dup, peer(2), Some(&owner))
.expect("dropped, not an error");
assert!(
store.get("fresh").is_none(),
"ambiguous delta dropped whole — neither copy of the new key applies"
);
assert_eq!(store.current_version(), v_before, "no state change");
}
#[test]
fn signed_store_ambiguous_added_updated_delta_dropped() {
// WHY: the canonical-map rule is global, not AppendOnly-only. A delta
// carrying one key in both `added` and `updated` holds two values for
// one key in one message — which copy wins would be decided by map
// iteration/LWW ordering, not by anything the producer expressed. No
// legitimate producer emits this shape, so merge_delta drops the
// whole delta for EVERY policy.
let owner = agent(1);
let mut store = KvStore::new(
store_id(9),
"plain".to_string(),
owner,
AccessPolicy::Signed,
);
store
.put(
"k".to_string(),
b"v1".to_vec(),
"text/plain".to_string(),
peer(1),
)
.expect("put");
let v_before = store.current_version();
let mut dup = KvStoreDelta::new(99);
dup.added.insert(
"k".to_string(),
(
KvEntry::new("k".to_string(), b"v2".to_vec(), "text/plain".to_string()),
(peer(2), 7),
),
);
dup.updated.insert(
"k".to_string(),
KvEntry::new("k".to_string(), b"v3".to_vec(), "text/plain".to_string()),
);
// An innocent sibling key must not survive either: the ambiguity
// poisons the whole delta.
dup.added.insert(
"other".to_string(),
(
KvEntry::new("other".to_string(), b"x".to_vec(), "text/plain".to_string()),
(peer(2), 8),
),
);
store
.merge_delta(&dup, peer(2), Some(&owner))
.expect("dropped, not an error");
assert_eq!(
store.get("k").map(|e| e.value.clone()),
Some(b"v1".to_vec()),
"ambiguous delta must not change the key on a Signed store"
);
assert!(store.get("other").is_none(), "whole delta dropped");
assert_eq!(store.current_version(), v_before, "no state change");
}
#[test]
fn access_policy_bincode_discriminants_are_pinned() {
// WHY: AccessPolicy is bincode-encoded positionally in persisted
// stores, checkpoints (wire + signing bytes), and deltas. If anyone
// reorders or inserts a variant mid-enum, every existing store
// corrupts. This test pins the exact on-wire indices 0..=3.
let cases: [(AccessPolicy, u32); 4] = [
(AccessPolicy::Signed, 0),
(AccessPolicy::Allowlisted, 1),
(
AccessPolicy::Encrypted {
group_id: Vec::new(),
},
2,
),
(AccessPolicy::AppendOnly, 3),
];
for (policy, index) in cases {
let bytes = bincode::serialize(&policy).expect("serialize");
assert!(bytes.len() >= 4, "bincode enum tag is a u32");
let tag = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
assert_eq!(
tag, index,
"bincode discriminant for {policy} moved — this BREAKS every existing store/checkpoint"
);
}
}
}