-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_test.go
More file actions
2341 lines (2154 loc) · 110 KB
/
Copy pathserver_test.go
File metadata and controls
2341 lines (2154 loc) · 110 KB
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
package main
import (
"bufio"
"bytes"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
)
type recordingVerifier struct {
message []byte
}
func (v *recordingVerifier) Verify(publicKey, message, signature []byte) bool {
v.message = append(v.message[:0], message...)
return len(publicKey) == mlDSA44PublicKeySize && len(signature) == mlDSA44SignatureSize
}
func testServer(t *testing.T) (*Server, *Store, *recordingVerifier) {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "ksync-test.db")
store, err := OpenStore(dbPath)
if err != nil {
t.Fatal(err)
}
verifier := &recordingVerifier{}
server := NewServer(Config{
Addr: "127.0.0.1:0",
BaseURL: "http://127.0.0.1:0",
DBPath: dbPath,
ChallengeTTL: time.Minute,
TokenTTL: time.Hour,
TokenSecret: bytes.Repeat([]byte{0x99}, 32),
MaxBodyBytes: 1 << 20,
}, store, verifier)
t.Cleanup(func() { _ = store.Close() })
return server, store, verifier
}
type testIdentity struct {
PublicKey []byte
UserID string
Signature string
Token string
}
func newTestIdentity(t *testing.T, target any, seed byte) testIdentity {
return newTestIdentityAt(t, target, "", seed)
}
func newTestIdentityAt(t *testing.T, target any, baseURL string, seed byte) testIdentity {
t.Helper()
publicKey := bytes.Repeat([]byte{seed}, mlDSA44PublicKeySize)
userHash := sha256.Sum256(publicKey)
userID := hex.EncodeToString(userHash[:])
signature := hex.EncodeToString(bytes.Repeat([]byte{seed + 0x11}, mlDSA44SignatureSize))
token, _ := loginWithKey(t, target, baseURL, userID, hex.EncodeToString(publicKey), signature)
return testIdentity{PublicKey: publicKey, UserID: userID, Signature: signature, Token: token}
}
func TestDocsEndpoints(t *testing.T) {
server, _, _ := testServer(t)
handler := server.Routes()
root := httptest.NewRecorder()
handler.ServeHTTP(root, httptest.NewRequest(http.MethodGet, "/", nil))
if root.Code != http.StatusOK {
t.Fatalf("root status = %d", root.Code)
}
if !strings.Contains(root.Body.String(), "Ksync Sync API") {
t.Fatalf("root docs missing title: %s", root.Body.String())
}
for _, want := range []string{"Users", "Storage", "/"} {
if !strings.Contains(root.Body.String(), want) {
t.Fatalf("root docs missing %q: %s", want, root.Body.String())
}
}
spec := httptest.NewRecorder()
handler.ServeHTTP(spec, httptest.NewRequest(http.MethodGet, "/openapi.json", nil))
if spec.Code != http.StatusOK {
t.Fatalf("openapi status = %d", spec.Code)
}
var decoded map[string]any
if err := json.Unmarshal(spec.Body.Bytes(), &decoded); err != nil {
t.Fatal(err)
}
if decoded["openapi"] != "3.1.0" {
t.Fatalf("unexpected openapi version: %#v", decoded["openapi"])
}
}
func TestHeaderSignedSyncAndDelete(t *testing.T) {
server, store, verifier := testServer(t)
handler := server.Routes()
publicKey := bytes.Repeat([]byte{0x42}, mlDSA44PublicKeySize)
userHash := sha256.Sum256(publicKey)
userID := hex.EncodeToString(userHash[:])
signature := hex.EncodeToString(bytes.Repeat([]byte{0x33}, mlDSA44SignatureSize))
token, loginNonce := loginWithKey(t, handler, "", userID, hex.EncodeToString(publicKey), signature)
body := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-1","habits":[{"id":"habit-1","name":"Meditate","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":2,"counter_enabled":1,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-19T00:00:00Z"}],"habit_days":[{"habit_id":"habit-1","local_date":20260619,"completed":true,"count":4,"updated_at":"2026-06-19T00:00:00Z"}],"sessions":[{"id":"session-1","started_at":"2026-06-19T00:00:00Z","local_date":20260619,"topic":"0","activity":1,"source":"test","rounds_hash":"abc","deleted_at":0,"updated_at":"2026-06-19T00:00:00Z","rounds":[{"round_index":0,"breaths":0,"hold_seconds":60}]}]}`)
res := syncWithBody(t, handler, "", userID, token, body)
if res.Code != http.StatusOK {
t.Fatalf("sync status = %d body=%s", res.Code, res.Body.String())
}
var syncResponse SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &syncResponse); err != nil {
t.Fatal(err)
}
if syncResponse.Status != "ok" || syncResponse.ServerVersion == 0 ||
len(syncResponse.Changes.Habits) != 1 || len(syncResponse.Changes.HabitDays) != 1 ||
len(syncResponse.Changes.Sessions) != 1 {
t.Fatalf("unexpected sync changes: %#v", syncResponse)
}
if syncResponse.Changes.HabitDays[0].Count != 4 {
t.Fatalf("habit day count = %d, want 4", syncResponse.Changes.HabitDays[0].Count)
}
if syncResponse.Changes.Habits[0].CounterEnabled != 1 {
t.Fatalf("habit counter_enabled = %d, want 1", syncResponse.Changes.Habits[0].CounterEnabled)
}
loginBody := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-1","public_key":"` + hex.EncodeToString(publicKey) + `"}`)
wantMessage := string(canonicalMessage(mustDecodeHex(t, loginNonce), http.MethodPost, "/api/v1/sync/login", loginBody))
if string(verifier.message) != wantMessage {
t.Fatalf("signed message mismatch\n got: %q\nwant: %q", string(verifier.message), wantMessage)
}
assertCount(t, store, "server_users", 1)
assertCount(t, store, "server_habits", 1)
assertCount(t, store, "server_habit_days", 1)
assertCount(t, store, "server_sessions", 1)
assertCount(t, store, "server_session_rounds", 1)
nonce := issueChallenge(t, handler, "", userID)
deleteBody := []byte(`{"user_id_hash":"` + userID + `"}`)
deleteReq := httptest.NewRequest(http.MethodDelete, "/api/v1/account", bytes.NewReader(deleteBody))
deleteReq.Header.Set("Content-Type", "application/json")
deleteReq.Header.Set("X-Ksync-User", userID)
deleteReq.Header.Set("X-Ksync-Signature", signature)
deleteRes := httptest.NewRecorder()
handler.ServeHTTP(deleteRes, deleteReq)
if deleteRes.Code != http.StatusOK {
t.Fatalf("delete status = %d body=%s", deleteRes.Code, deleteRes.Body.String())
}
wantMessage = string(canonicalMessage(mustDecodeHex(t, nonce), http.MethodDelete, "/api/v1/account", deleteBody))
if string(verifier.message) != wantMessage {
t.Fatalf("delete signed message mismatch\n got: %q\nwant: %q", string(verifier.message), wantMessage)
}
assertCount(t, store, "server_users", 0)
assertCount(t, store, "server_habits", 0)
assertCount(t, store, "server_habit_days", 0)
assertCount(t, store, "server_sessions", 0)
assertCount(t, store, "server_session_rounds", 0)
}
func TestLegacyInbeSignedLoginDeleteAndBearerHeaders(t *testing.T) {
server, store, verifier := testServer(t)
handler := server.Routes()
publicKey := bytes.Repeat([]byte{0x45}, mlDSA44PublicKeySize)
userHash := sha256.Sum256(publicKey)
userID := hex.EncodeToString(userHash[:])
signature := hex.EncodeToString(bytes.Repeat([]byte{0x55}, mlDSA44SignatureSize))
loginNonce := issueChallenge(t, handler, "", userID)
loginBody := []byte(`{"user_id_hash":"` + userID + `","client_id":"legacy-inbe-client","public_key":"` + hex.EncodeToString(publicKey) + `"}`)
loginReq := httptest.NewRequest(http.MethodPost, "/api/v1/sync/login", bytes.NewReader(loginBody))
loginReq.Header.Set("Content-Type", "application/json")
loginReq.Header.Set("X-Inbe-User", userID)
loginReq.Header.Set("X-Inbe-Signature", signature)
loginRes := httptest.NewRecorder()
handler.ServeHTTP(loginRes, loginReq)
if loginRes.Code != http.StatusOK {
t.Fatalf("legacy login status = %d body=%s", loginRes.Code, loginRes.Body.String())
}
wantMessage := string(canonicalMessageWithContext("inbe-sync-v1", mustDecodeHex(t, loginNonce), http.MethodPost, "/api/v1/sync/login", loginBody))
if string(verifier.message) != wantMessage {
t.Fatalf("legacy login signed message mismatch\n got: %q\nwant: %q", string(verifier.message), wantMessage)
}
var login LoginResponse
if err := json.Unmarshal(loginRes.Body.Bytes(), &login); err != nil {
t.Fatal(err)
}
if login.AuthToken == "" {
t.Fatal("missing legacy auth token")
}
syncBody := []byte(`{"user_id_hash":"` + userID + `","client_id":"legacy-inbe-client","since_server_version":0}`)
syncReq := httptest.NewRequest(http.MethodPost, "/api/v1/sync", bytes.NewReader(syncBody))
syncReq.Header.Set("Content-Type", "application/json")
syncReq.Header.Set("X-Inbe-User", userID)
syncReq.Header.Set("Authorization", "Bearer "+login.AuthToken)
syncRes := httptest.NewRecorder()
handler.ServeHTTP(syncRes, syncReq)
if syncRes.Code != http.StatusOK {
t.Fatalf("legacy sync status = %d body=%s", syncRes.Code, syncRes.Body.String())
}
deleteNonce := issueChallenge(t, handler, "", userID)
deleteBody := []byte(`{"user_id_hash":"` + userID + `"}`)
deleteReq := httptest.NewRequest(http.MethodDelete, "/api/v1/account", bytes.NewReader(deleteBody))
deleteReq.Header.Set("Content-Type", "application/json")
deleteReq.Header.Set("X-Inbe-User", userID)
deleteReq.Header.Set("X-Inbe-Signature", signature)
deleteRes := httptest.NewRecorder()
handler.ServeHTTP(deleteRes, deleteReq)
if deleteRes.Code != http.StatusOK {
t.Fatalf("legacy delete status = %d body=%s", deleteRes.Code, deleteRes.Body.String())
}
wantMessage = string(canonicalMessageWithContext("inbe-sync-v1", mustDecodeHex(t, deleteNonce), http.MethodDelete, "/api/v1/account", deleteBody))
if string(verifier.message) != wantMessage {
t.Fatalf("legacy delete signed message mismatch\n got: %q\nwant: %q", string(verifier.message), wantMessage)
}
assertCount(t, store, "server_users", 0)
}
func TestSyncReturnsRemoteChangesSinceVersion(t *testing.T) {
server, _, _ := testServer(t)
handler := server.Routes()
publicKey := bytes.Repeat([]byte{0x42}, mlDSA44PublicKeySize)
userHash := sha256.Sum256(publicKey)
userID := hex.EncodeToString(userHash[:])
signature := hex.EncodeToString(bytes.Repeat([]byte{0x33}, mlDSA44SignatureSize))
token, _ := loginWithKey(t, handler, "", userID, hex.EncodeToString(publicKey), signature)
body := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-1","habits":[{"id":"habit-1","name":"Meditate","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":2,"counter_enabled":1,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-19T00:00:00Z"}],"habit_days":[{"habit_id":"habit-1","local_date":20260619,"completed":true,"count":4,"updated_at":"2026-06-19T00:00:00Z"}]}`)
res := syncWithBody(t, handler, "", userID, token, body)
var first SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &first); err != nil {
t.Fatal(err)
}
if first.ServerVersion == 0 || len(first.Changes.Habits) != 1 || len(first.Changes.HabitDays) != 1 {
t.Fatalf("first changes = %#v", first)
}
if first.Changes.HabitDays[0].Count != 4 {
t.Fatalf("first habit day count = %d, want 4", first.Changes.HabitDays[0].Count)
}
if first.Changes.Habits[0].CounterEnabled != 1 {
t.Fatalf("first habit counter_enabled = %d, want 1", first.Changes.Habits[0].CounterEnabled)
}
emptyBody := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-1","since_server_version":` + strconv.FormatInt(first.ServerVersion, 10) + `}`)
res = syncWithBody(t, handler, "", userID, token, emptyBody)
var payload SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Changes.Habits) != 0 || len(payload.Changes.HabitDays) != 0 {
t.Fatalf("expected no changes after latest version: %#v", payload.Changes)
}
updateBody := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-1","since_server_version":` + strconv.FormatInt(first.ServerVersion, 10) + `,"habit_days":[{"habit_id":"habit-1","local_date":20260619,"completed":true,"count":7,"updated_at":"2026-06-19T00:01:00Z"}]}`)
res = syncWithBody(t, handler, "", userID, token, updateBody)
if err := json.Unmarshal(res.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Changes.Habits) != 0 || len(payload.Changes.HabitDays) != 1 ||
!payload.Changes.HabitDays[0].Completed ||
payload.Changes.HabitDays[0].Count != 7 {
t.Fatalf("expected only changed habit day: %#v", payload.Changes)
}
}
func TestHashMismatchRequiresFullSnapshotWithoutApplyingUpload(t *testing.T) {
server, _, _ := testServer(t)
handler := server.Routes()
publicKey := bytes.Repeat([]byte{0x49}, mlDSA44PublicKeySize)
userHash := sha256.Sum256(publicKey)
userID := hex.EncodeToString(userHash[:])
signature := hex.EncodeToString(bytes.Repeat([]byte{0x5a}, mlDSA44SignatureSize))
habit1ID := "00000000-0000-4000-8000-000000000001"
habit2ID := "00000000-0000-4000-8000-000000000002"
token, _ := loginWithKey(t, handler, "", userID, hex.EncodeToString(publicKey), signature)
body := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-1","habits":[{"id":"` + habit1ID + `","name":"Remote","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":2,"counter_enabled":1,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-19T00:00:00Z"}]}`)
res := syncWithBody(t, handler, "", userID, token, body)
var first SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &first); err != nil {
t.Fatal(err)
}
if first.ServerStateHash == "" || !first.ChangesComplete || first.FullSnapshotRequired {
t.Fatalf("first response = %#v", first)
}
staleHash := strings.Repeat("0", 64)
staleBody := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-2","since_server_version":` + strconv.FormatInt(first.ServerVersion, 10) + `,"last_server_state_hash":"` + staleHash + `","habits":[{"id":"` + habit2ID + `","name":"Local stale upload","color_r":9,"color_g":9,"color_b":9,"sync_mode":1,"sync_activity":2,"counter_enabled":0,"sort_order":1,"deleted_at":0,"updated_at":"2026-06-20T00:00:00Z"}]}`)
res = syncWithBody(t, handler, "", userID, token, staleBody)
var mismatch SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &mismatch); err != nil {
t.Fatal(err)
}
if !mismatch.FullSnapshotRequired || mismatch.ChangesComplete || mismatch.Applied.Habits != 0 {
t.Fatalf("mismatch response = %#v", mismatch)
}
if len(mismatch.Changes.Habits) != 1 || mismatch.Changes.Habits[0].ID != habit1ID {
t.Fatalf("mismatch snapshot = %#v", mismatch.Changes.Habits)
}
fullBody := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-3","since_server_version":0}`)
res = syncWithBody(t, handler, "", userID, token, fullBody)
var full SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &full); err != nil {
t.Fatal(err)
}
if len(full.Changes.Habits) != 1 || full.Changes.Habits[0].ID != habit1ID {
t.Fatalf("stale upload was applied: %#v", full.Changes.Habits)
}
replaceBody := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-2","since_server_version":0,"full_sync_requested":true,"habits":[{"id":"` + habit2ID + `","name":"Local replacement","color_r":9,"color_g":9,"color_b":9,"sync_mode":1,"sync_activity":2,"counter_enabled":0,"sort_order":1,"deleted_at":0,"updated_at":"2026-06-20T00:00:00Z"}]}`)
res = syncWithBody(t, handler, "", userID, token, replaceBody)
var replaced SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &replaced); err != nil {
t.Fatal(err)
}
if replaced.FullSnapshotRequired || !replaced.ChangesComplete || replaced.Applied.Habits != 1 {
t.Fatalf("replace response = %#v", replaced)
}
fullBody = []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-3","since_server_version":0}`)
res = syncWithBody(t, handler, "", userID, token, fullBody)
if err := json.Unmarshal(res.Body.Bytes(), &full); err != nil {
t.Fatal(err)
}
if len(full.Changes.Habits) != 1 || full.Changes.Habits[0].ID != habit2ID {
t.Fatalf("remote was not replaced: %#v", full.Changes.Habits)
}
}
func TestSyncV2AppliesOpsIdempotentlyAndReturnsRemoteOps(t *testing.T) {
server, store, _ := testServer(t)
handler := server.Routes()
identity := newTestIdentity(t, handler, 0x61)
opPayload := `{"id":"habit-v2","name":"Yoga","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":4,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-24T10:00:00Z"}`
body := []byte(`{"protocol_version":2,"user_id_hash":"` + identity.UserID + `","client_id":"client-a","client_clock":0,"ops":[{"op_id":"client-a:1","client_id":"client-a","seq":1,"entity_type":"habit","entity_id":"habit-v2","op_type":"upsert","payload":` + opPayload + `,"created_at":"2026-06-24T10:00:00Z"}]}`)
res := syncWithBody(t, handler, "", identity.UserID, identity.Token, body)
if res.Code != http.StatusOK {
t.Fatalf("v2 sync status = %d body=%s", res.Code, res.Body.String())
}
var first SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &first); err != nil {
t.Fatal(err)
}
if first.ProtocolVersion != 2 || first.ServerClock == 0 || len(first.AcceptedOps) != 1 || first.AcceptedOps[0] != "client-a:1" {
t.Fatalf("first v2 response = %#v", first)
}
assertCount(t, store, "server_habits", 1)
assertCount(t, store, "server_sync_ops", 1)
res = syncWithBody(t, handler, "", identity.UserID, identity.Token, body)
if res.Code != http.StatusOK {
t.Fatalf("duplicate v2 sync status = %d body=%s", res.Code, res.Body.String())
}
var duplicate SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &duplicate); err != nil {
t.Fatal(err)
}
if len(duplicate.AcceptedOps) != 1 || duplicate.AcceptedOps[0] != "client-a:1" {
t.Fatalf("duplicate accepted ops = %#v", duplicate.AcceptedOps)
}
assertCount(t, store, "server_habits", 1)
assertCount(t, store, "server_sync_ops", 1)
readBody := []byte(`{"protocol_version":2,"user_id_hash":"` + identity.UserID + `","client_id":"client-b","client_clock":0}`)
res = syncWithBody(t, handler, "", identity.UserID, identity.Token, readBody)
if res.Code != http.StatusOK {
t.Fatalf("v2 read status = %d body=%s", res.Code, res.Body.String())
}
var read SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &read); err != nil {
t.Fatal(err)
}
if len(read.Ops) != 1 || read.Ops[0].OpID != "client-a:1" || read.Ops[0].EntityType != "habit" {
t.Fatalf("remote ops = %#v", read.Ops)
}
if len(read.Changes.Habits) != 1 || !isCanonicalHabitID(read.Changes.Habits[0].ID) {
t.Fatalf("materialized changes = %#v", read.Changes.Habits)
}
}
func TestAccountExportReturnsOnlyAuthenticatedAccountData(t *testing.T) {
server, store, _ := testServer(t)
handler := server.Routes()
alice := newTestIdentity(t, handler, 0x65)
bob := newTestIdentity(t, handler, 0x66)
aliceBody := []byte(`{"protocol_version":2,"user_id_hash":"` + alice.UserID + `","client_id":"client-a","client_clock":0,"habits":[{"id":"alice-habit","name":"Alice Habit","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":4,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-24T10:00:00Z"}],"ops":[{"op_id":"client-a:1","client_id":"client-a","seq":1,"entity_type":"artifact","entity_id":"odd-one","op_type":"upsert","payload":{"kind":"weird"},"created_at":"2026-06-24T10:00:00Z"}]}`)
if res := syncWithBody(t, handler, "", alice.UserID, alice.Token, aliceBody); res.Code != http.StatusOK {
t.Fatalf("alice sync status = %d body=%s", res.Code, res.Body.String())
}
if _, err := store.db.Exec(`INSERT INTO server_social_snapshots(user_id_hash,kind,json,updated_at,server_version) VALUES(?1,'friends.list','{"friends":[]}','2026-06-24T10:00:00Z',99)`, alice.UserID); err != nil {
t.Fatal(err)
}
bobBody := []byte(`{"user_id_hash":"` + bob.UserID + `","client_id":"client-b","habits":[{"id":"bob-habit","name":"Bob Habit","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":4,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-24T10:00:00Z"}]}`)
if res := syncWithBody(t, handler, "", bob.UserID, bob.Token, bobBody); res.Code != http.StatusOK {
t.Fatalf("bob sync status = %d body=%s", res.Code, res.Body.String())
}
req := httptest.NewRequest(http.MethodGet, "/api/v1/account/export", nil)
req.Header.Set("Authorization", "Bearer "+alice.Token)
res := httptest.NewRecorder()
handler.ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("export status = %d body=%s", res.Code, res.Body.String())
}
var payload AccountExportResponse
if err := json.Unmarshal(res.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.UserIDHash != alice.UserID {
t.Fatalf("export user = %s, want %s", payload.UserIDHash, alice.UserID)
}
if len(payload.Tables["habits"]) != 1 {
t.Fatalf("export habits = %#v", payload.Tables["habits"])
}
id, _ := payload.Tables["habits"][0]["id"].(string)
if !isCanonicalHabitID(id) {
t.Fatalf("export habits = %#v", payload.Tables["habits"])
}
if len(payload.Tables["social_snapshots"]) != 1 {
t.Fatalf("export social cache = %#v", payload.Tables["social_snapshots"])
}
if len(payload.Tables["sync_ops"]) != 1 || payload.Tables["sync_ops"][0]["entity_type"] != "artifact" {
t.Fatalf("export sync ops = %#v", payload.Tables["sync_ops"])
}
for _, row := range payload.Tables["habits"] {
if row["id"] == "bob-habit" {
t.Fatalf("export leaked bob data: %#v", payload.Tables["habits"])
}
}
unauth := httptest.NewRecorder()
handler.ServeHTTP(unauth, httptest.NewRequest(http.MethodGet, "/api/v1/account/export", nil))
if unauth.Code != http.StatusUnauthorized {
t.Fatalf("unauth export status = %d body=%s", unauth.Code, unauth.Body.String())
}
}
func TestHabitDayZeroCountIncompleteIsSyncedState(t *testing.T) {
server, store, _ := testServer(t)
handler := server.Routes()
identity := newTestIdentity(t, handler, 0x64)
createBody := []byte(`{"user_id_hash":"` + identity.UserID + `","client_id":"client-a","habits":[{"id":"push-ups","name":"Push Ups","color_r":1,"color_g":2,"color_b":3,"sync_mode":0,"sync_activity":0,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-28T10:00:00Z"}],"habit_days":[{"habit_id":"push-ups","local_date":20260628,"completed":true,"count":1,"updated_at":"2026-06-28T10:00:00Z"}]}`)
res := syncWithBody(t, handler, "", identity.UserID, identity.Token, createBody)
if res.Code != http.StatusOK {
t.Fatalf("create status = %d body=%s", res.Code, res.Body.String())
}
zeroBody := []byte(`{"user_id_hash":"` + identity.UserID + `","client_id":"client-b","since_server_version":0,"habit_days":[{"habit_id":"push-ups","local_date":20260628,"completed":false,"count":0,"updated_at":"2026-06-28T11:00:00Z"}]}`)
res = syncWithBody(t, handler, "", identity.UserID, identity.Token, zeroBody)
if res.Code != http.StatusOK {
t.Fatalf("zero status = %d body=%s", res.Code, res.Body.String())
}
assertCount(t, store, "server_habit_days", 1)
readBody := []byte(`{"user_id_hash":"` + identity.UserID + `","client_id":"client-c","since_server_version":0}`)
res = syncWithBody(t, handler, "", identity.UserID, identity.Token, readBody)
if res.Code != http.StatusOK {
t.Fatalf("read status = %d body=%s", res.Code, res.Body.String())
}
var read SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &read); err != nil {
t.Fatal(err)
}
if len(read.Changes.HabitDays) != 1 || read.Changes.HabitDays[0].Completed || read.Changes.HabitDays[0].Count != 0 {
t.Fatalf("zero count habit day not preserved: %#v", read.Changes.HabitDays)
}
}
func TestSyncV2DeleteHabitKeepsSessions(t *testing.T) {
server, store, _ := testServer(t)
handler := server.Routes()
identity := newTestIdentity(t, handler, 0x62)
body := []byte(`{"protocol_version":2,"user_id_hash":"` + identity.UserID + `","client_id":"client-a","client_clock":0,"ops":[` +
`{"op_id":"client-a:1","client_id":"client-a","seq":1,"entity_type":"habit","entity_id":"yoga","op_type":"upsert","payload":{"id":"yoga","name":"Yoga","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":4,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-24T10:00:00Z"},"created_at":"2026-06-24T10:00:00Z"},` +
`{"op_id":"client-a:2","client_id":"client-a","seq":2,"entity_type":"session","entity_id":"sun-1","op_type":"upsert","payload":{"id":"sun-1","started_at":"2026-06-24T10:05:00Z","local_date":20260624,"topic":"0","activity":2,"source":"sun","rounds_hash":"1","deleted_at":0,"updated_at":"2026-06-24T10:05:00Z","rounds":[{"round_index":0,"breaths":0,"hold_seconds":1}]},"created_at":"2026-06-24T10:05:00Z"},` +
`{"op_id":"client-a:3","client_id":"client-a","seq":3,"entity_type":"habit","entity_id":"yoga","op_type":"delete","payload":{"id":"yoga","name":"Yoga","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":4,"counter_enabled":0,"sort_order":0,"deleted_at":1782300600,"updated_at":"2026-06-24T10:10:00Z"},"created_at":"2026-06-24T10:10:00Z"}` +
`]}`)
res := syncWithBody(t, handler, "", identity.UserID, identity.Token, body)
if res.Code != http.StatusOK {
t.Fatalf("v2 delete sync status = %d body=%s", res.Code, res.Body.String())
}
var response SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if len(response.AcceptedOps) != 3 {
t.Fatalf("accepted delete ops = %#v", response.AcceptedOps)
}
assertCount(t, store, "server_sync_ops", 3)
assertCount(t, store, "server_sessions", 1)
assertCount(t, store, "server_session_rounds", 1)
assertCount(t, store, "server_habits", 0)
}
func TestSyncV2CompactsAcknowledgedOpsAndFallsBackToSnapshot(t *testing.T) {
server, store, _ := testServer(t)
handler := server.Routes()
identity := newTestIdentity(t, handler, 0x63)
writeBody := []byte(`{"protocol_version":2,"user_id_hash":"` + identity.UserID + `","client_id":"client-a","client_clock":0,"ops":[{"op_id":"client-a:1","client_id":"client-a","seq":1,"entity_type":"habit","entity_id":"habit-v2","op_type":"upsert","payload":{"id":"habit-v2","name":"Yoga","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":4,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-24T10:00:00Z"},"created_at":"2026-06-24T10:00:00Z"}]}`)
res := syncWithBody(t, handler, "", identity.UserID, identity.Token, writeBody)
if res.Code != http.StatusOK {
t.Fatalf("v2 write status = %d body=%s", res.Code, res.Body.String())
}
var written SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &written); err != nil {
t.Fatal(err)
}
assertCount(t, store, "server_sync_ops", 1)
readBody := []byte(`{"protocol_version":2,"user_id_hash":"` + identity.UserID + `","client_id":"client-b","client_clock":0}`)
res = syncWithBody(t, handler, "", identity.UserID, identity.Token, readBody)
if res.Code != http.StatusOK {
t.Fatalf("v2 read status = %d body=%s", res.Code, res.Body.String())
}
var read SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &read); err != nil {
t.Fatal(err)
}
if read.FullSnapshotRequired || len(read.Ops) != 1 || read.ServerClock == 0 {
t.Fatalf("expected op replay before compaction: %#v", read)
}
assertCount(t, store, "server_sync_ops", 1)
ackBody := []byte(`{"protocol_version":2,"user_id_hash":"` + identity.UserID + `","client_id":"client-b","client_clock":` + strconv.FormatInt(read.ServerClock, 10) + `}`)
res = syncWithBody(t, handler, "", identity.UserID, identity.Token, ackBody)
if res.Code != http.StatusOK {
t.Fatalf("v2 ack status = %d body=%s", res.Code, res.Body.String())
}
assertCount(t, store, "server_sync_ops", 0)
staleBody := []byte(`{"protocol_version":2,"user_id_hash":"` + identity.UserID + `","client_id":"client-c","client_clock":0,"ops":[{"op_id":"client-c:1","client_id":"client-c","seq":1,"entity_type":"habit","entity_id":"stale-local","op_type":"upsert","payload":{"id":"stale-local","name":"Stale local","color_r":9,"color_g":9,"color_b":9,"sync_mode":0,"sync_activity":0,"counter_enabled":0,"sort_order":1,"deleted_at":0,"updated_at":"2026-06-24T10:30:00Z"},"created_at":"2026-06-24T10:30:00Z"}]}`)
res = syncWithBody(t, handler, "", identity.UserID, identity.Token, staleBody)
if res.Code != http.StatusOK {
t.Fatalf("v2 stale status = %d body=%s", res.Code, res.Body.String())
}
var stale SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &stale); err != nil {
t.Fatal(err)
}
if !stale.FullSnapshotRequired || stale.ChangesComplete || len(stale.Ops) != 0 || stale.Applied.Habits != 0 {
t.Fatalf("expected full snapshot fallback for compacted ops: %#v", stale)
}
if len(stale.Changes.Habits) != 1 || !isCanonicalHabitID(stale.Changes.Habits[0].ID) {
t.Fatalf("stale fallback snapshot = %#v", stale.Changes.Habits)
}
assertCount(t, store, "server_habits", 1)
assertCount(t, store, "server_sync_ops", 0)
}
func TestProtocolV3CleanDataHidesDeletedAndOrphanHabits(t *testing.T) {
server, store, _ := testServer(t)
handler := server.Routes()
identity := newTestIdentity(t, handler, 0x73)
body := []byte(`{"user_id_hash":"` + identity.UserID + `","client_id":"client-v2","habits":[{"id":"habit-8","name":"Old Habit","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":2,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-24T10:00:00Z"}],"habit_days":[{"habit_id":"habit-8","local_date":20260624,"completed":true,"count":1,"updated_at":"2026-06-24T10:00:00Z"}]}`)
if res := syncWithBody(t, handler, "", identity.UserID, identity.Token, body); res.Code != http.StatusOK {
t.Fatalf("initial sync status=%d body=%s", res.Code, res.Body.String())
}
deleteBody := []byte(`{"user_id_hash":"` + identity.UserID + `","client_id":"client-v2","habits":[{"id":"habit-8","name":"Old Habit","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":2,"counter_enabled":0,"sort_order":0,"deleted_at":1782300600,"updated_at":"2026-06-24T10:10:00Z"}]}`)
if res := syncWithBody(t, handler, "", identity.UserID, identity.Token, deleteBody); res.Code != http.StatusOK {
t.Fatalf("delete sync status=%d body=%s", res.Code, res.Body.String())
}
if _, err := store.db.Exec(`INSERT INTO server_habit_days(user_id_hash,habit_id,local_date,completed,count,updated_at,server_version) VALUES(?1,'habit-8',20260625,0,0,'2026-06-25T00:00:00Z',999)`, identity.UserID); err != nil {
t.Fatal(err)
}
readBody := []byte(`{"protocol_version":3,"user_id_hash":"` + identity.UserID + `","client_id":"client-v3","client_clock":0,"since_server_version":0}`)
res := syncWithBody(t, handler, "", identity.UserID, identity.Token, readBody)
if res.Code != http.StatusOK {
t.Fatalf("v3 sync status=%d body=%s", res.Code, res.Body.String())
}
var decoded SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &decoded); err != nil {
t.Fatal(err)
}
if decoded.Data == nil {
t.Fatalf("v3 response missing clean data: %s", res.Body.String())
}
if len(decoded.Data.Habits) != 0 || len(decoded.Data.HabitDays) != 0 {
t.Fatalf("deleted/orphan habit leaked into v3 data: %#v %#v", decoded.Data.Habits, decoded.Data.HabitDays)
}
var orphanCount int
if err := store.db.QueryRow(`SELECT COUNT(*) FROM server_habit_days WHERE user_id_hash=?1 AND habit_id='habit-8'`, identity.UserID).Scan(&orphanCount); err != nil {
t.Fatal(err)
}
if orphanCount != 0 {
t.Fatalf("orphan habit days were not cleaned: %d", orphanCount)
}
}
func TestProtocolV3MaterializesLegacyOrphanHabitDays(t *testing.T) {
server, store, _ := testServer(t)
handler := server.Routes()
identity := newTestIdentity(t, handler, 0x75)
if _, err := store.db.Exec(`INSERT INTO server_habit_days(user_id_hash,habit_id,local_date,completed,count,updated_at,server_version) VALUES(?1,'habit-8',20260625,1,2,'2026-06-25T00:00:00Z',9)`, identity.UserID); err != nil {
t.Fatal(err)
}
readBody := []byte(`{"protocol_version":3,"user_id_hash":"` + identity.UserID + `","client_id":"client-v3","client_clock":0,"since_server_version":0}`)
res := syncWithBody(t, handler, "", identity.UserID, identity.Token, readBody)
if res.Code != http.StatusOK {
t.Fatalf("v3 sync status=%d body=%s", res.Code, res.Body.String())
}
var decoded SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &decoded); err != nil {
t.Fatal(err)
}
if decoded.Data == nil || len(decoded.Data.Habits) != 1 {
t.Fatalf("unexpected clean habits: %#v body=%s", decoded.Data, res.Body.String())
}
if !isCanonicalHabitID(decoded.Data.Habits[0].ID) || decoded.Data.Habits[0].Name != "Habit 8" {
t.Fatalf("legacy habit was not materialized with a readable name: %#v", decoded.Data.Habits[0])
}
if len(decoded.Data.HabitDays) != 1 || decoded.Data.HabitDays[0].HabitID != decoded.Data.Habits[0].ID || decoded.Data.HabitDays[0].HabitName != "Habit 8" || decoded.Data.HabitDays[0].Count != 2 {
t.Fatalf("legacy habit day was not attached to materialized habit: %#v", decoded.Data.HabitDays)
}
var habitRows int
if err := store.db.QueryRow(`SELECT COUNT(*) FROM server_habits WHERE user_id_hash=?1 AND id=?2 AND name='Habit 8'`, identity.UserID, decoded.Data.Habits[0].ID).Scan(&habitRows); err != nil {
t.Fatal(err)
}
if habitRows != 1 {
t.Fatalf("materialized habit row missing: %d", habitRows)
}
}
func TestProtocolV3AutoMigratesSunSalutationHabitIDAndKeepsLegacyClient(t *testing.T) {
server, store, _ := testServer(t)
handler := server.Routes()
identity := newTestIdentity(t, handler, 0x74)
legacyBody := []byte(`{"protocol_version":2,"user_id_hash":"` + identity.UserID + `","client_id":"old-inbe","habits":[{"id":"yoga","name":"Yoga","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":4,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-24T10:00:00Z"}],"habit_days":[{"habit_id":"yoga","local_date":20260624,"completed":true,"count":3,"updated_at":"2026-06-24T10:00:00Z"}]}`)
if res := syncWithBody(t, handler, "", identity.UserID, identity.Token, legacyBody); res.Code != http.StatusOK {
t.Fatalf("legacy sync status=%d body=%s", res.Code, res.Body.String())
}
readBody := []byte(`{"protocol_version":3,"user_id_hash":"` + identity.UserID + `","client_id":"new-inbe","client_clock":0,"since_server_version":0}`)
res := syncWithBody(t, handler, "", identity.UserID, identity.Token, readBody)
if res.Code != http.StatusOK {
t.Fatalf("v3 sync status=%d body=%s", res.Code, res.Body.String())
}
var decoded SyncResponse
if err := json.Unmarshal(res.Body.Bytes(), &decoded); err != nil {
t.Fatal(err)
}
if decoded.Data == nil || len(decoded.Data.Habits) != 1 {
t.Fatalf("unexpected clean habits: %#v body=%s", decoded.Data, res.Body.String())
}
if !isCanonicalHabitID(decoded.Data.Habits[0].ID) {
t.Fatalf("habit was not canonicalized: %#v", decoded.Data.Habits[0])
}
if len(decoded.Data.HabitDays) != 1 || decoded.Data.HabitDays[0].HabitID != decoded.Data.Habits[0].ID || decoded.Data.HabitDays[0].HabitName != "Yoga" {
t.Fatalf("habit day was not canonicalized with name: %#v", decoded.Data.HabitDays)
}
if len(decoded.LegacyClients) == 0 {
t.Fatalf("legacy client diagnostics missing: clients=%#v", decoded.LegacyClients)
}
if decoded.UpgradeNotice != "" {
t.Fatalf("dual-mode compatibility should not warn: %q", decoded.UpgradeNotice)
}
var oldRows int
if err := store.db.QueryRow(`SELECT COUNT(*) FROM server_habits WHERE user_id_hash=?1 AND id='yoga'`, identity.UserID).Scan(&oldRows); err != nil {
t.Fatal(err)
}
if oldRows != 0 {
t.Fatalf("legacy yoga row still exists: %d", oldRows)
}
}
func TestAccountAliasRegistersAndSyncs(t *testing.T) {
server, _, _ := testServer(t)
handler := server.Routes()
publicKey := bytes.Repeat([]byte{0x4a}, mlDSA44PublicKeySize)
userHash := sha256.Sum256(publicKey)
userID := hex.EncodeToString(userHash[:])
signature := hex.EncodeToString(bytes.Repeat([]byte{0x6a}, mlDSA44SignatureSize))
token, _ := loginWithKey(t, handler, "", userID, hex.EncodeToString(publicKey), signature)
aliasBody := []byte(`{"user_id_hash":"` + userID + `","alias":"@waozi"}`)
req := httptest.NewRequest(http.MethodPost, "/api/v1/account/alias", bytes.NewReader(aliasBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Ksync-User", userID)
req.Header.Set("Authorization", "Bearer "+token)
res := httptest.NewRecorder()
handler.ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("alias status = %d body=%s", res.Code, res.Body.String())
}
var aliasRes AliasResponse
if err := json.Unmarshal(res.Body.Bytes(), &aliasRes); err != nil {
t.Fatal(err)
}
if aliasRes.Alias != "waozi" {
t.Fatalf("alias = %q", aliasRes.Alias)
}
{
nonce := issueChallenge(t, handler, "", userID)
loginBody := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-1","public_key":"` + hex.EncodeToString(publicKey) + `"}`)
req := httptest.NewRequest(http.MethodPost, "/api/v1/sync/login", bytes.NewReader(loginBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Ksync-User", userID)
req.Header.Set("X-Ksync-Signature", signature)
res := httptest.NewRecorder()
handler.ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("login alias status = %d body=%s nonce=%s", res.Code, res.Body.String(), nonce)
}
var loginRes LoginResponse
if err := json.Unmarshal(res.Body.Bytes(), &loginRes); err != nil {
t.Fatal(err)
}
if loginRes.AccountAlias != "waozi" {
t.Fatalf("login alias = %q", loginRes.AccountAlias)
}
}
body := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-1","since_server_version":0}`)
syncRes := syncWithBody(t, handler, "", userID, token, body)
var payload SyncResponse
if err := json.Unmarshal(syncRes.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.AccountAlias != "waozi" {
t.Fatalf("sync alias = %q", payload.AccountAlias)
}
aliasBody = []byte(`{"user_id_hash":"` + userID + `","alias":"@new_waozi"}`)
req = httptest.NewRequest(http.MethodPost, "/api/v1/account/alias", bytes.NewReader(aliasBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Ksync-User", userID)
req.Header.Set("Authorization", "Bearer "+token)
res = httptest.NewRecorder()
handler.ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("alias change status = %d body=%s", res.Code, res.Body.String())
}
if err := json.Unmarshal(res.Body.Bytes(), &aliasRes); err != nil {
t.Fatal(err)
}
if aliasRes.Alias != "new_waozi" {
t.Fatalf("changed alias = %q", aliasRes.Alias)
}
syncRes = syncWithBody(t, handler, "", userID, token, body)
if err := json.Unmarshal(syncRes.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.AccountAlias != "new_waozi" {
t.Fatalf("sync changed alias = %q", payload.AccountAlias)
}
otherKey := bytes.Repeat([]byte{0x4b}, mlDSA44PublicKeySize)
otherHash := sha256.Sum256(otherKey)
otherID := hex.EncodeToString(otherHash[:])
otherToken, _ := loginWithKey(t, handler, "", otherID, hex.EncodeToString(otherKey), signature)
aliasBody = []byte(`{"user_id_hash":"` + otherID + `","alias":"waozi"}`)
req = httptest.NewRequest(http.MethodPost, "/api/v1/account/alias", bytes.NewReader(aliasBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Ksync-User", otherID)
req.Header.Set("Authorization", "Bearer "+otherToken)
res = httptest.NewRecorder()
handler.ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("old alias reuse status = %d body=%s", res.Code, res.Body.String())
}
aliasBody = []byte(`{"user_id_hash":"` + otherID + `","alias":"new_waozi"}`)
req = httptest.NewRequest(http.MethodPost, "/api/v1/account/alias", bytes.NewReader(aliasBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Ksync-User", otherID)
req.Header.Set("Authorization", "Bearer "+otherToken)
res = httptest.NewRecorder()
handler.ServeHTTP(res, req)
if res.Code != http.StatusConflict {
t.Fatalf("alias conflict status = %d body=%s", res.Code, res.Body.String())
}
}
func TestAccountProfileIconRegistersAndSyncs(t *testing.T) {
server, _, _ := testServer(t)
handler := server.Routes()
publicKey := bytes.Repeat([]byte{0x5c}, mlDSA44PublicKeySize)
userHash := sha256.Sum256(publicKey)
userID := hex.EncodeToString(userHash[:])
signature := hex.EncodeToString(bytes.Repeat([]byte{0x7c}, mlDSA44SignatureSize))
token, _ := loginWithKey(t, handler, "", userID, hex.EncodeToString(publicKey), signature)
iconBody := []byte(`{"user_id_hash":"` + userID + `","profile_icon":` + strconv.Itoa(ProfileIconLotus) + `}`)
req := httptest.NewRequest(http.MethodPost, "/api/v1/account/profile-icon", bytes.NewReader(iconBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Ksync-User", userID)
req.Header.Set("Authorization", "Bearer "+token)
res := httptest.NewRecorder()
handler.ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("profile icon status = %d body=%s", res.Code, res.Body.String())
}
var iconRes ProfileIconResponse
if err := json.Unmarshal(res.Body.Bytes(), &iconRes); err != nil {
t.Fatal(err)
}
if iconRes.ProfileIcon != ProfileIconLotus {
t.Fatalf("profile icon = %d", iconRes.ProfileIcon)
}
{
nonce := issueChallenge(t, handler, "", userID)
loginBody := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-1","public_key":"` + hex.EncodeToString(publicKey) + `"}`)
req := httptest.NewRequest(http.MethodPost, "/api/v1/sync/login", bytes.NewReader(loginBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Ksync-User", userID)
req.Header.Set("X-Ksync-Signature", signature)
res := httptest.NewRecorder()
handler.ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("login profile icon status = %d body=%s nonce=%s", res.Code, res.Body.String(), nonce)
}
var loginRes LoginResponse
if err := json.Unmarshal(res.Body.Bytes(), &loginRes); err != nil {
t.Fatal(err)
}
if loginRes.ProfileIcon != ProfileIconLotus {
t.Fatalf("login profile icon = %d", loginRes.ProfileIcon)
}
}
body := []byte(`{"user_id_hash":"` + userID + `","client_id":"test-client-1","since_server_version":0}`)
syncRes := syncWithBody(t, handler, "", userID, token, body)
var payload SyncResponse
if err := json.Unmarshal(syncRes.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.ProfileIcon != ProfileIconLotus {
t.Fatalf("sync profile icon = %d", payload.ProfileIcon)
}
req = httptest.NewRequest(http.MethodPost, "/api/v1/account/profile-icon", bytes.NewReader([]byte(`{"user_id_hash":"`+userID+`","profile_icon":99}`)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Ksync-User", userID)
req.Header.Set("Authorization", "Bearer "+token)
res = httptest.NewRecorder()
handler.ServeHTTP(res, req)
if res.Code != http.StatusBadRequest {
t.Fatalf("invalid profile icon status = %d body=%s", res.Code, res.Body.String())
}
}
func TestFriendRequestsByAliasAndPublicID(t *testing.T) {
server, store, _ := testServer(t)
handler := server.Routes()
alice := newTestIdentity(t, handler, 0x21)
bob := newTestIdentity(t, handler, 0x22)
carol := newTestIdentity(t, handler, 0x23)
setAlias(t, handler, alice, "alice")
setAlias(t, handler, bob, "bobby")
res := friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests", alice, []byte(`{"target":"@bobby"}`))
if res.Code != http.StatusCreated {
t.Fatalf("create by alias status = %d body=%s", res.Code, res.Body.String())
}
var created FriendRequestResponse
if err := json.Unmarshal(res.Body.Bytes(), &created); err != nil {
t.Fatal(err)
}
if created.Request.RequesterUserID != alice.UserID || created.Request.TargetUserID != bob.UserID || created.Request.TargetAlias != "bobby" {
t.Fatalf("unexpected created request: %#v", created.Request)
}
res = friendJSONRequest(t, handler, http.MethodGet, "/api/v1/friends/requests", bob, nil)
if res.Code != http.StatusOK {
t.Fatalf("bob requests status = %d body=%s", res.Code, res.Body.String())
}
var pending FriendRequestsResponse
if err := json.Unmarshal(res.Body.Bytes(), &pending); err != nil {
t.Fatal(err)
}
if len(pending.Incoming) != 1 || pending.Incoming[0].RequesterAlias != "alice" || len(pending.Outgoing) != 0 {
t.Fatalf("unexpected bob pending: %#v", pending)
}
res = friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests/"+created.Request.ID+"/accept", alice, []byte(`{}`))
if res.Code != http.StatusForbidden {
t.Fatalf("requester accept status = %d body=%s", res.Code, res.Body.String())
}
res = friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests/"+created.Request.ID+"/accept", bob, []byte(`{}`))
if res.Code != http.StatusOK {
t.Fatalf("target accept status = %d body=%s", res.Code, res.Body.String())
}
res = friendJSONRequest(t, handler, http.MethodGet, "/api/v1/friends", alice, nil)
if res.Code != http.StatusOK {
t.Fatalf("alice friends status = %d body=%s", res.Code, res.Body.String())
}
var friends FriendsResponse
if err := json.Unmarshal(res.Body.Bytes(), &friends); err != nil {
t.Fatal(err)
}
if len(friends.Friends) != 1 || friends.Friends[0].UserIDHash != bob.UserID || friends.Friends[0].Alias != "bobby" {
t.Fatalf("unexpected alice friends: %#v", friends)
}
res = friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests", alice, []byte(`{"target":"`+bob.UserID+`"}`))
if res.Code != http.StatusConflict {
t.Fatalf("already friends status = %d body=%s", res.Code, res.Body.String())
}
res = friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests", carol, []byte(`{"target":"`+alice.UserID+`"}`))
if res.Code != http.StatusCreated {
t.Fatalf("create by public id status = %d body=%s", res.Code, res.Body.String())
}
var outgoing FriendRequestResponse
if err := json.Unmarshal(res.Body.Bytes(), &outgoing); err != nil {
t.Fatal(err)
}
res = friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests/"+outgoing.Request.ID+"/decline", carol, []byte(`{}`))
if res.Code != http.StatusOK {
t.Fatalf("requester cancel outgoing status = %d body=%s", res.Code, res.Body.String())
}
res = friendJSONRequest(t, handler, http.MethodGet, "/api/v1/friends/requests", alice, nil)
if res.Code != http.StatusOK {
t.Fatalf("alice requests after cancel status = %d body=%s", res.Code, res.Body.String())
}
if err := json.Unmarshal(res.Body.Bytes(), &pending); err != nil {
t.Fatal(err)
}
if len(pending.Incoming) != 0 || len(pending.Outgoing) != 0 {
t.Fatalf("canceled outgoing request still visible: %#v", pending)
}
res = friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests", alice, []byte(`{"target":"`+alice.UserID+`"}`))
if res.Code != http.StatusConflict {
t.Fatalf("self friend status = %d body=%s", res.Code, res.Body.String())
}
res = friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests", alice, []byte(`{"target":"@missing_alias"}`))
if res.Code != http.StatusNotFound {
t.Fatalf("missing target status = %d body=%s", res.Code, res.Body.String())
}
assertCount(t, store, "server_friend_requests", 2)
assertCount(t, store, "server_friendships", 1)
}
func TestFriendRequestsRejectMismatchedHeaderUser(t *testing.T) {
server, _, _ := testServer(t)
handler := server.Routes()
alice := newTestIdentity(t, handler, 0x31)
bob := newTestIdentity(t, handler, 0x32)
req := httptest.NewRequest(http.MethodPost, "/api/v1/friends/requests",
bytes.NewReader([]byte(`{"target":"`+bob.UserID+`"}`)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+alice.Token)
req.Header.Set("X-Ksync-User", bob.UserID)
res := httptest.NewRecorder()
handler.ServeHTTP(res, req)
if res.Code != http.StatusUnauthorized {
t.Fatalf("mismatched friend user status = %d body=%s", res.Code, res.Body.String())
}
}
func TestFriendDeclineAndStatsVisibility(t *testing.T) {
server, store, _ := testServer(t)
handler := server.Routes()
alice := newTestIdentity(t, handler, 0x24)
bob := newTestIdentity(t, handler, 0x25)
carol := newTestIdentity(t, handler, 0x26)
req := createFriendRequest(t, handler, alice, bob.UserID)
res := friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests/"+req.ID+"/decline", bob, []byte(`{}`))
if res.Code != http.StatusOK {
t.Fatalf("decline status = %d body=%s", res.Code, res.Body.String())
}
res = friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests/"+req.ID+"/accept", bob, []byte(`{}`))
if res.Code != http.StatusConflict {
t.Fatalf("accept declined status = %d body=%s", res.Code, res.Body.String())
}
req = createFriendRequest(t, handler, alice, bob.UserID)
res = friendJSONRequest(t, handler, http.MethodPost, "/api/v1/friends/requests/"+req.ID+"/accept", bob, []byte(`{}`))
if res.Code != http.StatusOK {
t.Fatalf("accept resent status = %d body=%s", res.Code, res.Body.String())
}
syncWithBody(t, handler, "", alice.UserID, alice.Token, []byte(`{"user_id_hash":"`+alice.UserID+`","client_id":"alice-stats","habits":[{"id":"whm","name":"WHM","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":1,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-26T00:00:00Z"}],"habit_days":[{"habit_id":"whm","local_date":`+time.Now().UTC().Format("20060102")+`,"completed":true,"count":1,"updated_at":"2026-06-28T00:00:00Z"}],"sessions":[{"id":"alice-hold","started_at":"2026-06-28T00:00:00Z","local_date":`+time.Now().UTC().Format("20060102")+`,"topic":"0","activity":0,"source":"test","rounds_hash":"alice","deleted_at":0,"updated_at":"2026-06-28T00:00:00Z","rounds":[{"round_index":0,"breaths":0,"hold_seconds":82},{"round_index":1,"breaths":0,"hold_seconds":83}]}]}`))
syncWithBody(t, handler, "", bob.UserID, bob.Token, []byte(`{"user_id_hash":"`+bob.UserID+`","client_id":"bob-stats","habits":[{"id":"whm","name":"WHM","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":1,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-26T00:00:00Z"}],"habit_days":[{"habit_id":"whm","local_date":`+time.Now().UTC().Format("20060102")+`,"completed":true,"count":1,"updated_at":"2026-06-28T00:00:00Z"}]}`))
syncWithBody(t, handler, "", carol.UserID, carol.Token, []byte(`{"user_id_hash":"`+carol.UserID+`","client_id":"carol-stats","habits":[{"id":"whm","name":"WHM","color_r":1,"color_g":2,"color_b":3,"sync_mode":1,"sync_activity":1,"counter_enabled":0,"sort_order":0,"deleted_at":0,"updated_at":"2026-06-26T00:00:00Z"}],"habit_days":[{"habit_id":"whm","local_date":`+time.Now().UTC().Format("20060102")+`,"completed":true,"count":1,"updated_at":"2026-06-28T00:00:00Z"}]}`))
yesterdayDay := time.Now().UTC().AddDate(0, 0, -1)
yesterdayDate := yesterdayDay.Year()*10000 + int(yesterdayDay.Month())*100 + yesterdayDay.Day()
if _, err := store.db.Exec(`
INSERT INTO server_leaderboard_stats(user_id_hash,app,practice,metric,source_version,value,label,local_date,updated_at)
SELECT ?1,'inbe','whm','avg_hold',server_version,0,'0',0,'stale'