-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathserver_test.go
More file actions
2408 lines (2129 loc) · 77.2 KB
/
server_test.go
File metadata and controls
2408 lines (2129 loc) · 77.2 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 httpapi
import (
"bufio"
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"scrumboy/internal/db"
"scrumboy/internal/migrate"
"scrumboy/internal/store"
)
func newTestHTTPServer(t *testing.T, mode string) (*httptest.Server, *sql.DB, func()) {
t.Helper()
dir := t.TempDir()
sqlDB, err := db.Open(filepath.Join(dir, "app.db"), db.Options{
BusyTimeout: 5000,
JournalMode: "WAL",
Synchronous: "FULL",
})
if err != nil {
t.Fatalf("open db: %v", err)
}
if err := migrate.Apply(context.Background(), sqlDB); err != nil {
_ = sqlDB.Close()
t.Fatalf("migrate: %v", err)
}
st := store.New(sqlDB, nil)
if mode == "" {
mode = "full"
}
srv := NewServer(st, Options{MaxRequestBody: 1 << 20, ScrumboyMode: mode})
ts := httptest.NewServer(srv)
return ts, sqlDB, func() {
ts.Close()
_ = sqlDB.Close()
}
}
func doJSON(t *testing.T, client *http.Client, method, url string, body any, out any) (*http.Response, []byte) {
t.Helper()
var buf bytes.Buffer
if body != nil {
if err := json.NewEncoder(&buf).Encode(body); err != nil {
t.Fatalf("encode json: %v", err)
}
}
req, err := http.NewRequest(method, url, &buf)
if err != nil {
t.Fatalf("new request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Scrumboy", "1")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("do request: %v", err)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if out != nil && len(b) > 0 {
if err := json.Unmarshal(b, out); err != nil {
t.Fatalf("unmarshal: %v, body=%s", err, string(b))
}
}
return resp, b
}
func newCookieClient(t *testing.T) *http.Client {
t.Helper()
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatalf("cookie jar: %v", err)
}
return &http.Client{Jar: jar}
}
func bootstrapUserClient(t *testing.T, client *http.Client, baseURL, name, email, password string) map[string]any {
t.Helper()
var user map[string]any
resp, body := doJSON(t, client, http.MethodPost, baseURL+"/api/auth/bootstrap", map[string]any{
"name": name,
"email": email,
"password": password,
}, &user)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("bootstrap status=%d body=%s", resp.StatusCode, string(body))
}
return user
}
func loginUserClient(t *testing.T, client *http.Client, baseURL, email, password string) {
t.Helper()
resp, body := doJSON(t, client, http.MethodPost, baseURL+"/api/auth/login", map[string]any{
"email": email,
"password": password,
}, nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("login status=%d body=%s", resp.StatusCode, string(body))
}
}
func TestAPI_CreateMoveAndFetchBoard(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
client := ts.Client()
var p struct {
ID int64 `json:"id"`
}
resp, _ := doJSON(t, client, http.MethodPost, ts.URL+"/api/projects", map[string]any{"name": "p"}, &p)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create project status=%d", resp.StatusCode)
}
var slug string
if err := sqlDB.QueryRow(`SELECT slug FROM projects WHERE id = ?`, p.ID).Scan(&slug); err != nil {
t.Fatalf("read slug: %v", err)
}
if slug == "" {
t.Fatalf("expected non-empty slug")
}
var todo struct {
ID int64 `json:"id"`
Status string `json:"status"`
}
resp, _ = doJSON(t, client, http.MethodPost, ts.URL+"/api/board/"+slug+"/todos", map[string]any{
"title": "t",
"body": "",
"tags": []string{"bug"},
"status": "BACKLOG",
}, &todo)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create todo status=%d", resp.StatusCode)
}
if todo.Status != "BACKLOG" {
t.Fatalf("expected BACKLOG, got %q", todo.Status)
}
resp, _ = doJSON(t, client, http.MethodPost, ts.URL+"/api/todos/"+strconv.FormatInt(todo.ID, 10)+"/move", map[string]any{
"toStatus": "IN_PROGRESS",
"afterId": nil,
"beforeId": nil,
}, &todo)
if resp.StatusCode != http.StatusOK {
t.Fatalf("move todo status=%d", resp.StatusCode)
}
if todo.Status != "IN_PROGRESS" {
t.Fatalf("expected IN_PROGRESS, got %q", todo.Status)
}
var board struct {
Columns map[string][]struct {
ID int64 `json:"id"`
} `json:"columns"`
}
resp, _ = doJSON(t, client, http.MethodGet, ts.URL+"/api/board/"+slug, nil, &board)
if resp.StatusCode != http.StatusOK {
t.Fatalf("get board status=%d", resp.StatusCode)
}
if len(board.Columns["IN_PROGRESS"]) != 1 || board.Columns["IN_PROGRESS"][0].ID != todo.ID {
t.Fatalf("unexpected board: %+v", board.Columns)
}
// Back-compat: numeric-ID route still works.
resp, _ = doJSON(t, client, http.MethodGet, ts.URL+"/api/projects/"+strconv.FormatInt(p.ID, 10)+"/board", nil, &board)
if resp.StatusCode != http.StatusOK {
t.Fatalf("get board by id status=%d", resp.StatusCode)
}
if len(board.Columns["IN_PROGRESS"]) != 1 || board.Columns["IN_PROGRESS"][0].ID != todo.ID {
t.Fatalf("unexpected board by id: %+v", board.Columns)
}
}
func TestRenameLane_RequiresMaintainer(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
ownerClient := newCookieClient(t)
owner := bootstrapUserClient(t, ownerClient, ts.URL, "Owner", "owner@example.com", "password123")
ownerID := int64(owner["id"].(float64))
st := store.New(sqlDB, nil)
ctxOwner := store.WithUserID(context.Background(), ownerID)
project, err := st.CreateProject(ctxOwner, "rename-lane-auth")
if err != nil {
t.Fatalf("CreateProject: %v", err)
}
contributor, err := st.CreateUser(context.Background(), "contrib@example.com", "password123", "Contributor")
if err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := st.AddProjectMember(ctxOwner, ownerID, project.ID, contributor.ID, store.RoleContributor); err != nil {
t.Fatalf("AddProjectMember: %v", err)
}
contributorClient := newCookieClient(t)
loginUserClient(t, contributorClient, ts.URL, "contrib@example.com", "password123")
resp, body := doJSON(t, contributorClient, http.MethodPatch, ts.URL+"/api/board/"+project.Slug+"/workflow/"+store.DefaultColumnDoing, map[string]any{
"name": "Working",
"color": "#10B981",
}, nil)
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("expected 403, got %d body=%s", resp.StatusCode, string(body))
}
}
func TestRenameLane_NonexistentKeyReturns404(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
ownerClient := newCookieClient(t)
owner := bootstrapUserClient(t, ownerClient, ts.URL, "Owner", "owner@example.com", "password123")
ownerID := int64(owner["id"].(float64))
st := store.New(sqlDB, nil)
project, err := st.CreateProject(store.WithUserID(context.Background(), ownerID), "rename-lane-404")
if err != nil {
t.Fatalf("CreateProject: %v", err)
}
resp, body := doJSON(t, ownerClient, http.MethodPatch, ts.URL+"/api/board/"+project.Slug+"/workflow/not_a_lane", map[string]any{
"name": "Working",
"color": "#10B981",
}, nil)
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("expected 404, got %d body=%s", resp.StatusCode, string(body))
}
}
func TestRenameLane_EmptyNameRejected(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
ownerClient := newCookieClient(t)
owner := bootstrapUserClient(t, ownerClient, ts.URL, "Owner", "owner@example.com", "password123")
ownerID := int64(owner["id"].(float64))
st := store.New(sqlDB, nil)
project, err := st.CreateProject(store.WithUserID(context.Background(), ownerID), "rename-lane-400")
if err != nil {
t.Fatalf("CreateProject: %v", err)
}
tests := []struct {
name string
body map[string]any
}{
{
name: "WhitespaceOnly",
body: map[string]any{"name": " ", "color": "#10B981"},
},
{
name: "EmptyColor",
body: map[string]any{"name": "Working", "color": ""},
},
{
name: "MissingColor",
body: map[string]any{"name": "Working"},
},
{
name: "InvalidColor",
body: map[string]any{"name": "Working", "color": "#gggggg"},
},
{
name: "RejectsKey",
body: map[string]any{"name": "Working", "color": "#10B981", "key": "other"},
},
{
name: "RejectsIsDone",
body: map[string]any{"name": "Working", "color": "#10B981", "isDone": true},
},
{
name: "RejectsPosition",
body: map[string]any{"name": "Working", "color": "#10B981", "position": 1},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
resp, body := doJSON(t, ownerClient, http.MethodPatch, ts.URL+"/api/board/"+project.Slug+"/workflow/"+store.DefaultColumnDoing, tc.body, nil)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("expected 400, got %d body=%s", resp.StatusCode, string(body))
}
})
}
}
func TestRenameLane_BoardAPIReflectsNewName(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
ownerClient := newCookieClient(t)
owner := bootstrapUserClient(t, ownerClient, ts.URL, "Owner", "owner@example.com", "password123")
ownerID := int64(owner["id"].(float64))
st := store.New(sqlDB, nil)
project, err := st.CreateProject(store.WithUserID(context.Background(), ownerID), "rename-lane-board")
if err != nil {
t.Fatalf("CreateProject: %v", err)
}
resp, body := doJSON(t, ownerClient, http.MethodPatch, ts.URL+"/api/board/"+project.Slug+"/workflow/"+store.DefaultColumnDoing, map[string]any{
"name": "Working",
"color": "#aabbcc",
}, nil)
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("rename lane status=%d body=%s", resp.StatusCode, string(body))
}
var board struct {
ColumnOrder []struct {
Key string `json:"key"`
Name string `json:"name"`
Color string `json:"color"`
} `json:"columnOrder"`
}
resp, body = doJSON(t, ownerClient, http.MethodGet, ts.URL+"/api/board/"+project.Slug, nil, &board)
if resp.StatusCode != http.StatusOK {
t.Fatalf("get board status=%d body=%s", resp.StatusCode, string(body))
}
for _, lane := range board.ColumnOrder {
if lane.Key == store.DefaultColumnDoing {
if lane.Name != "Working" {
t.Fatalf("expected lane name %q, got %q", "Working", lane.Name)
}
if lane.Color != "#aabbcc" {
t.Fatalf("expected lane color %q, got %q", "#aabbcc", lane.Color)
}
return
}
}
t.Fatalf("expected lane %q in board response", store.DefaultColumnDoing)
}
func TestAddLane_RequiresMaintainer(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
ownerClient := newCookieClient(t)
owner := bootstrapUserClient(t, ownerClient, ts.URL, "Owner", "owner@example.com", "password123")
ownerID := int64(owner["id"].(float64))
st := store.New(sqlDB, nil)
ctxOwner := store.WithUserID(context.Background(), ownerID)
project, err := st.CreateProject(ctxOwner, "add-lane-auth")
if err != nil {
t.Fatalf("CreateProject: %v", err)
}
contributor, err := st.CreateUser(context.Background(), "addlane-contrib@example.com", "password123", "Contributor")
if err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := st.AddProjectMember(ctxOwner, ownerID, project.ID, contributor.ID, store.RoleContributor); err != nil {
t.Fatalf("AddProjectMember: %v", err)
}
contributorClient := newCookieClient(t)
loginUserClient(t, contributorClient, ts.URL, "addlane-contrib@example.com", "password123")
resp, body := doJSON(t, contributorClient, http.MethodPost, ts.URL+"/api/board/"+project.Slug+"/workflow", map[string]any{
"name": "Review",
}, nil)
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("expected 403, got %d body=%s", resp.StatusCode, string(body))
}
}
func TestAddLane_InvalidNameRejected(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
ownerClient := newCookieClient(t)
owner := bootstrapUserClient(t, ownerClient, ts.URL, "Owner", "owner@example.com", "password123")
ownerID := int64(owner["id"].(float64))
st := store.New(sqlDB, nil)
project, err := st.CreateProject(store.WithUserID(context.Background(), ownerID), "add-lane-400")
if err != nil {
t.Fatalf("CreateProject: %v", err)
}
tests := []struct {
name string
body map[string]any
}{
{name: "WhitespaceOnly", body: map[string]any{"name": " "}},
{name: "RejectsKey", body: map[string]any{"name": "Review", "key": "review"}},
{name: "RejectsIsDone", body: map[string]any{"name": "Review", "isDone": true}},
{name: "RejectsPosition", body: map[string]any{"name": "Review", "position": 1}},
{name: "RejectsColor", body: map[string]any{"name": "Review", "color": "#123456"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
resp, body := doJSON(t, ownerClient, http.MethodPost, ts.URL+"/api/board/"+project.Slug+"/workflow", tc.body, nil)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("expected 400, got %d body=%s", resp.StatusCode, string(body))
}
})
}
}
func TestAddLane_BoardShowsNewLane(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
ownerClient := newCookieClient(t)
owner := bootstrapUserClient(t, ownerClient, ts.URL, "Owner", "owner@example.com", "password123")
ownerID := int64(owner["id"].(float64))
st := store.New(sqlDB, nil)
project, err := st.CreateProject(store.WithUserID(context.Background(), ownerID), "add-lane-board")
if err != nil {
t.Fatalf("CreateProject: %v", err)
}
var created struct {
Key string `json:"key"`
Name string `json:"name"`
IsDone bool `json:"isDone"`
Position int `json:"position"`
}
resp, body := doJSON(t, ownerClient, http.MethodPost, ts.URL+"/api/board/"+project.Slug+"/workflow", map[string]any{
"name": "Review",
}, &created)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("add lane status=%d body=%s", resp.StatusCode, string(body))
}
if created.Key != "review" {
t.Fatalf("expected created key %q, got %+v", "review", created)
}
if created.IsDone {
t.Fatalf("expected created lane to be non-done, got %+v", created)
}
var board struct {
ColumnOrder []struct {
Key string `json:"key"`
Name string `json:"name"`
IsDone bool `json:"isDone"`
} `json:"columnOrder"`
}
resp, body = doJSON(t, ownerClient, http.MethodGet, ts.URL+"/api/board/"+project.Slug, nil, &board)
if resp.StatusCode != http.StatusOK {
t.Fatalf("get board status=%d body=%s", resp.StatusCode, string(body))
}
reviewIdx := -1
doneIdx := -1
doneCount := 0
for i, lane := range board.ColumnOrder {
if lane.Key == created.Key {
reviewIdx = i
if lane.Name != "Review" {
t.Fatalf("expected created lane name %q, got %q", "Review", lane.Name)
}
}
if lane.IsDone {
doneIdx = i
doneCount++
}
}
if reviewIdx < 0 {
t.Fatalf("expected created lane %q in board response", created.Key)
}
if doneCount != 1 {
t.Fatalf("expected exactly one done lane, got %d", doneCount)
}
if doneIdx < 0 || reviewIdx != doneIdx-1 {
t.Fatalf("expected created lane immediately before done, reviewIdx=%d doneIdx=%d board=%+v", reviewIdx, doneIdx, board.ColumnOrder)
}
}
func TestAddLane_ResponseAndBoardReflectTrimmedName(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
ownerClient := newCookieClient(t)
owner := bootstrapUserClient(t, ownerClient, ts.URL, "Owner", "owner@example.com", "password123")
ownerID := int64(owner["id"].(float64))
st := store.New(sqlDB, nil)
project, err := st.CreateProject(store.WithUserID(context.Background(), ownerID), "add-lane-trim")
if err != nil {
t.Fatalf("CreateProject: %v", err)
}
var created struct {
Key string `json:"key"`
Name string `json:"name"`
}
resp, body := doJSON(t, ownerClient, http.MethodPost, ts.URL+"/api/board/"+project.Slug+"/workflow", map[string]any{
"name": " QA Gate ",
}, &created)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("add lane status=%d body=%s", resp.StatusCode, string(body))
}
if created.Key != "qa_gate" {
t.Fatalf("expected key %q, got %+v", "qa_gate", created)
}
if created.Name != "QA Gate" {
t.Fatalf("expected trimmed name %q, got %q", "QA Gate", created.Name)
}
var board struct {
ColumnOrder []struct {
Key string `json:"key"`
Name string `json:"name"`
} `json:"columnOrder"`
}
resp, body = doJSON(t, ownerClient, http.MethodGet, ts.URL+"/api/board/"+project.Slug, nil, &board)
if resp.StatusCode != http.StatusOK {
t.Fatalf("get board status=%d body=%s", resp.StatusCode, string(body))
}
for _, lane := range board.ColumnOrder {
if lane.Key == created.Key {
if lane.Name != "QA Gate" {
t.Fatalf("board lane name: want %q, got %q", "QA Gate", lane.Name)
}
return
}
}
t.Fatalf("lane %q missing from board", created.Key)
}
func TestDeleteLane_RequiresMaintainer(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
ownerClient := newCookieClient(t)
owner := bootstrapUserClient(t, ownerClient, ts.URL, "Owner", "owner@example.com", "password123")
ownerID := int64(owner["id"].(float64))
st := store.New(sqlDB, nil)
ctxOwner := store.WithUserID(context.Background(), ownerID)
project, err := st.CreateProject(ctxOwner, "delete-lane-auth")
if err != nil {
t.Fatalf("CreateProject: %v", err)
}
added, err := st.AddWorkflowColumn(ctxOwner, project.ID, "Review")
if err != nil {
t.Fatalf("AddWorkflowColumn: %v", err)
}
contributor, err := st.CreateUser(context.Background(), "deletelane-contrib@example.com", "password123", "Contributor")
if err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := st.AddProjectMember(ctxOwner, ownerID, project.ID, contributor.ID, store.RoleContributor); err != nil {
t.Fatalf("AddProjectMember: %v", err)
}
contributorClient := newCookieClient(t)
loginUserClient(t, contributorClient, ts.URL, "deletelane-contrib@example.com", "password123")
resp, body := doJSON(t, contributorClient, http.MethodDelete, ts.URL+"/api/board/"+project.Slug+"/workflow/"+added.Key, nil, nil)
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("expected 403, got %d body=%s", resp.StatusCode, string(body))
}
}
func TestDeleteLane_BoardNoLongerShowsLane(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
ownerClient := newCookieClient(t)
owner := bootstrapUserClient(t, ownerClient, ts.URL, "Owner", "owner@example.com", "password123")
ownerID := int64(owner["id"].(float64))
st := store.New(sqlDB, nil)
project, err := st.CreateProject(store.WithUserID(context.Background(), ownerID), "delete-lane-board")
if err != nil {
t.Fatalf("CreateProject: %v", err)
}
added, err := st.AddWorkflowColumn(store.WithUserID(context.Background(), ownerID), project.ID, "Review")
if err != nil {
t.Fatalf("AddWorkflowColumn: %v", err)
}
resp, body := doJSON(t, ownerClient, http.MethodDelete, ts.URL+"/api/board/"+project.Slug+"/workflow/"+added.Key, nil, nil)
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("delete lane status=%d body=%s", resp.StatusCode, string(body))
}
var board struct {
ColumnOrder []struct {
Key string `json:"key"`
IsDone bool `json:"isDone"`
} `json:"columnOrder"`
}
resp, body = doJSON(t, ownerClient, http.MethodGet, ts.URL+"/api/board/"+project.Slug, nil, &board)
if resp.StatusCode != http.StatusOK {
t.Fatalf("get board status=%d body=%s", resp.StatusCode, string(body))
}
doneCount := 0
for _, lane := range board.ColumnOrder {
if lane.Key == added.Key {
t.Fatalf("expected lane %q to be removed from board", added.Key)
}
if lane.IsDone {
doneCount++
}
}
if doneCount != 1 {
t.Fatalf("expected exactly one done lane, got %d", doneCount)
}
}
func TestFullMode_MultiProjectBehavior(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
client := ts.Client()
// Create multiple projects
var p1, p2 struct {
ID int64 `json:"id"`
}
resp, _ := doJSON(t, client, http.MethodPost, ts.URL+"/api/projects", map[string]any{"name": "p1"}, &p1)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create project 1 status=%d", resp.StatusCode)
}
resp, _ = doJSON(t, client, http.MethodPost, ts.URL+"/api/projects", map[string]any{"name": "p2"}, &p2)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create project 2 status=%d", resp.StatusCode)
}
// Verify projects have expires_at = NULL (full mode)
var expiresAt sql.NullInt64
if err := sqlDB.QueryRow(`SELECT expires_at FROM projects WHERE id = ?`, p1.ID).Scan(&expiresAt); err != nil {
t.Fatalf("read expires_at: %v", err)
}
if expiresAt.Valid {
t.Fatalf("expected expires_at to be NULL for full mode project, got %d", expiresAt.Int64)
}
// Verify / serves SPA (doesn't auto-create)
resp, _ = http.Get(ts.URL + "/")
if resp.StatusCode != http.StatusOK {
t.Fatalf("GET / status=%d", resp.StatusCode)
}
if resp.Header.Get("Content-Type") != "text/html; charset=utf-8" {
t.Fatalf("expected HTML, got %s", resp.Header.Get("Content-Type"))
}
}
func TestAPI_ProjectsIncludeExpiresAt(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
client := ts.Client()
// Create durable project via API
var p struct {
ID int64 `json:"id"`
}
resp, _ := doJSON(t, client, http.MethodPost, ts.URL+"/api/projects", map[string]any{"name": "durable"}, &p)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create project status=%d", resp.StatusCode)
}
// Create a temporary board directly via store (no public HTTP endpoint in full mode)
st := store.New(sqlDB, nil)
tmp, err := st.CreateAnonymousBoard(context.Background())
if err != nil {
t.Fatalf("create anonymous board: %v", err)
}
var out []struct {
ID int64 `json:"id"`
ExpiresAt *time.Time `json:"expiresAt"`
}
resp, body := doJSON(t, client, http.MethodGet, ts.URL+"/api/projects", nil, &out)
if resp.StatusCode != http.StatusOK {
t.Fatalf("list projects status=%d body=%s", resp.StatusCode, string(body))
}
var durableExpiresAt, tmpExpiresAt *time.Time
for _, item := range out {
if item.ID == p.ID {
durableExpiresAt = item.ExpiresAt
}
if item.ID == tmp.ID {
tmpExpiresAt = item.ExpiresAt
}
}
if durableExpiresAt != nil {
t.Fatalf("expected durable project expiresAt=null, got %v", durableExpiresAt)
}
if tmpExpiresAt == nil {
t.Fatalf("expected temporary board expiresAt to be non-null")
}
}
func TestAnonymousMode_DoesNotAllowProjectEnumeration(t *testing.T) {
ts, _, cleanup := newTestHTTPServer(t, "anonymous")
defer cleanup()
// In anonymous mode, /api/projects must not enumerate projects.
resp, err := http.Get(ts.URL + "/api/projects")
if err != nil {
t.Fatalf("GET /api/projects: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
b, _ := io.ReadAll(resp.Body)
t.Fatalf("expected 404, got %d body=%s", resp.StatusCode, string(b))
}
}
func TestAnonymousMode_RootServesLandingAndIsIdempotent(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, "anonymous")
defer cleanup()
var before int
if err := sqlDB.QueryRow(`SELECT COUNT(*) FROM projects`).Scan(&before); err != nil {
t.Fatalf("count before: %v", err)
}
resp, err := http.Get(ts.URL + "/")
if err != nil {
t.Fatalf("GET /: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
if resp.Header.Get("Content-Type") != "text/html; charset=utf-8" {
t.Fatalf("expected HTML, got %s", resp.Header.Get("Content-Type"))
}
b, _ := io.ReadAll(resp.Body)
if !strings.Contains(string(b), `href="/anon"`) {
t.Fatalf("expected landing page to include /anon CTA")
}
var after int
if err := sqlDB.QueryRow(`SELECT COUNT(*) FROM projects`).Scan(&after); err != nil {
t.Fatalf("count after: %v", err)
}
if after != before {
t.Fatalf("expected GET / to be idempotent, count %d -> %d", before, after)
}
}
func TestAnonAndTempRoutes_CreateAndRedirect(t *testing.T) {
modes := []string{"full", "anonymous"}
for _, mode := range modes {
mode := mode
t.Run(mode, func(t *testing.T) {
ts, sqlDB, cleanup := newTestHTTPServer(t, mode)
defer cleanup()
// Client that doesn't follow redirects
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
// GET /temp -> /anon
resp, err := client.Get(ts.URL + "/temp")
if err != nil {
t.Fatalf("GET /temp: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusFound {
t.Fatalf("expected 302 for /temp, got %d", resp.StatusCode)
}
if loc := resp.Header.Get("Location"); loc != "/anon" {
t.Fatalf("expected Location=/anon, got %q", loc)
}
// GET /anon creates and redirects to /{slug}
resp, err = client.Get(ts.URL + "/anon")
if err != nil {
t.Fatalf("GET /anon: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusFound {
t.Fatalf("expected 302 for /anon, got %d", resp.StatusCode)
}
location := resp.Header.Get("Location")
slug := strings.TrimPrefix(location, "/")
if slug == "" || slug == location || strings.Contains(slug, "/") {
t.Fatalf("expected /{slug} Location, got %q", location)
}
// Non-GET should be rejected (no side effects)
req, _ := http.NewRequest(http.MethodPost, ts.URL+"/anon", nil)
resp, err = client.Do(req)
if err != nil {
t.Fatalf("POST /anon: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusMethodNotAllowed {
t.Fatalf("expected 405 for POST /anon, got %d", resp.StatusCode)
}
// Sanity: created project is expiring
var expiresAt sql.NullInt64
if err := sqlDB.QueryRow(`SELECT expires_at FROM projects WHERE slug = ?`, slug).Scan(&expiresAt); err != nil {
t.Fatalf("read expires_at: %v", err)
}
if !expiresAt.Valid {
t.Fatalf("expected expires_at to be set for /anon-created board")
}
})
}
}
func TestAuth_BootstrapLoginMeLogout_FullMode(t *testing.T) {
ts, _, cleanup := newTestHTTPServer(t, "full")
defer cleanup()
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatalf("cookie jar: %v", err)
}
client := &http.Client{Jar: jar}
// /api/auth/status before bootstrap: bootstrapAvailable=true, user=null
resp, err := client.Get(ts.URL + "/api/auth/status")
if err != nil {
t.Fatalf("GET /api/auth/status: %v", err)
}
var st map[string]any
_ = json.NewDecoder(resp.Body).Decode(&st)
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200 for /api/auth/status, got %d", resp.StatusCode)
}
if cc := resp.Header.Get("Cache-Control"); cc != "no-store" {
t.Fatalf("expected Cache-Control no-store for /api/auth/status, got %q", cc)
}
if st["bootstrapAvailable"] != true {
t.Fatalf("expected bootstrapAvailable true, got %#v", st["bootstrapAvailable"])
}
if st["user"] != nil {
t.Fatalf("expected user null, got %#v", st["user"])
}
// /api/me before login -> 401
resp, err = client.Get(ts.URL + "/api/me")
if err != nil {
t.Fatalf("GET /api/me: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", resp.StatusCode)
}
// Bootstrap first user (also sets cookie)
var u map[string]any
resp, _ = doJSON(t, client, http.MethodPost, ts.URL+"/api/auth/bootstrap", map[string]any{
"name": "Alice",
"email": "admin@example.com",
"password": "password123",
}, &u)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("expected 201 for bootstrap, got %d", resp.StatusCode)
}
if u["email"] != "admin@example.com" {
t.Fatalf("expected email admin@example.com, got %#v", u["email"])
}
if u["name"] != "Alice" {
t.Fatalf("expected name Alice, got %#v", u["name"])
}
// /api/auth/status after bootstrap: bootstrapAvailable=false, user present (id+email only)
resp, err = client.Get(ts.URL + "/api/auth/status")
if err != nil {
t.Fatalf("GET /api/auth/status: %v", err)
}
st = map[string]any{}
_ = json.NewDecoder(resp.Body).Decode(&st)
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200 for /api/auth/status, got %d", resp.StatusCode)
}
if st["bootstrapAvailable"] != false {
t.Fatalf("expected bootstrapAvailable false, got %#v", st["bootstrapAvailable"])
}
userObj, ok := st["user"].(map[string]any)
if !ok {
t.Fatalf("expected user object, got %#v", st["user"])
}
if userObj["email"] != "admin@example.com" {
t.Fatalf("expected user.email admin@example.com, got %#v", userObj["email"])
}
if userObj["name"] != "Alice" {
t.Fatalf("expected user.name Alice, got %#v", userObj["name"])
}
if _, ok := userObj["createdAt"]; ok {
t.Fatalf("status.user must not include createdAt")
}
// /api/me after bootstrap -> 200
resp, err = client.Get(ts.URL + "/api/me")
if err != nil {
t.Fatalf("GET /api/me: %v", err)
}
var me map[string]any
_ = json.NewDecoder(resp.Body).Decode(&me)
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
if me["email"] != "admin@example.com" {
t.Fatalf("expected me.email admin@example.com, got %#v", me["email"])
}
// Logout clears cookie and returns 200 + HTML meta refresh (tunnel-friendly; 302+Set-Cookie
// can be mishandled by some proxies e.g. Cloudflare Tunnel)
req, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/auth/logout", strings.NewReader(""))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("X-Scrumboy", "1") // not required for form POST but test uses doJSON-style
resp, err = client.Do(req)
if err != nil {
t.Fatalf("logout request: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200 for logout, got %d", resp.StatusCode)
}
if cc := resp.Header.Get("Cache-Control"); cc != "no-store" {
t.Fatalf("expected Cache-Control no-store for logout, got %q", cc)
}
// Verify Set-Cookie clears the session (cookie jar will have been updated)
// /api/auth/status after logout: bootstrapAvailable=false, user=null
resp, err = client.Get(ts.URL + "/api/auth/status")
if err != nil {
t.Fatalf("GET /api/auth/status: %v", err)
}
st = map[string]any{}
_ = json.NewDecoder(resp.Body).Decode(&st)
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200 for /api/auth/status, got %d", resp.StatusCode)
}
if st["bootstrapAvailable"] != false {
t.Fatalf("expected bootstrapAvailable false after logout, got %#v", st["bootstrapAvailable"])
}
if st["user"] != nil {
t.Fatalf("expected user null after logout, got %#v", st["user"])
}
resp, err = client.Get(ts.URL + "/api/me")
if err != nil {
t.Fatalf("GET /api/me: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("expected 401 after logout, got %d", resp.StatusCode)
}
}
func TestAuth_EndpointsNotFound_AnonymousMode(t *testing.T) {
ts, _, cleanup := newTestHTTPServer(t, "anonymous")
defer cleanup()
client := &http.Client{}
// /api/me should just 401 (no redirect, no crash)
resp, err := client.Get(ts.URL + "/api/me")
if err != nil {
t.Fatalf("GET /api/me: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {