-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration_api_test.go
More file actions
357 lines (316 loc) · 12.2 KB
/
integration_api_test.go
File metadata and controls
357 lines (316 loc) · 12.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
package bms_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"github.com/pafthang/arc"
"github.com/pafthang/bms/internal/app"
"github.com/pafthang/bms/internal/config"
dbpkg "github.com/pafthang/bms/internal/db"
"github.com/pafthang/bms/internal/domain/models"
"github.com/pafthang/dbx"
"github.com/pafthang/orm"
)
type tokenPair struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
type authRegisterResp struct {
Data struct {
User struct {
ID int64 `json:"id"`
Email string `json:"email"`
} `json:"user"`
Tokens tokenPair `json:"tokens"`
} `json:"data"`
}
type workspaceCreateResp struct {
Data struct {
Workspace struct {
ID int64 `json:"id"`
} `json:"workspace"`
} `json:"data"`
}
type workspaceMembersResp struct {
Data []struct {
UserID int64 `json:"user_id"`
Role string `json:"role"`
} `json:"data"`
}
type workspacesListResp struct {
Data []struct {
ID int64 `json:"id"`
} `json:"data"`
}
type apiErrorResp struct {
Code string `json:"code"`
}
type bookmarkCreateResp struct {
Data struct {
ID int64 `json:"id"`
TagIDs []int64 `json:"tag_ids"`
} `json:"data"`
}
type testEnv struct {
t *testing.T
db *dbx.DB
engine *arc.Engine
}
func setupTestEnv(t *testing.T) *testEnv {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "bms-test.sqlite")
cfg := config.Config{
HTTPAddr: ":0",
ShutdownTimeout: 3 * time.Second,
AllowedOrigins: []string{"http://localhost:3000"},
DBDSN: fmt.Sprintf("file:%s?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)", dbPath),
JWTSecret: "test-secret",
AccessTTL: time.Hour,
RefreshTTL: 24 * time.Hour,
}
database, err := dbpkg.Open(cfg)
if err != nil {
t.Fatalf("open db: %v", err)
}
t.Cleanup(func() { _ = database.Close() })
if err := dbpkg.MigrateUp(context.Background(), database, filepath.Join("migrations")); err != nil {
t.Fatalf("migrate up: %v", err)
}
engine := app.BuildEngine(cfg, database, app.BuildOptions{IncludeSystemRoutes: true, IncludeHealthRoutes: true})
return &testEnv{t: t, db: database, engine: engine}
}
func (e *testEnv) doJSON(method, path string, token string, body any, out any) (int, []byte) {
e.t.Helper()
var reqBody []byte
if body != nil {
var err error
reqBody, err = json.Marshal(body)
if err != nil {
e.t.Fatalf("marshal request: %v", err)
}
} else {
reqBody = []byte("{}")
}
req := httptest.NewRequest(method, path, bytes.NewReader(reqBody))
req.Header.Set("Content-Type", "application/json")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
w := httptest.NewRecorder()
e.engine.ServeHTTP(w, req)
if out != nil {
if err := json.Unmarshal(w.Body.Bytes(), out); err != nil {
e.t.Fatalf("unmarshal response (%s %s): %v; body=%s", method, path, err, w.Body.String())
}
}
return w.Code, w.Body.Bytes()
}
func (e *testEnv) register(email string) (int64, tokenPair) {
e.t.Helper()
var resp authRegisterResp
status, body := e.doJSON(http.MethodPost, "/api/v1/auth/register", "", map[string]any{
"email": email,
"password": "password123",
}, &resp)
if status != http.StatusCreated {
e.t.Fatalf("register status=%d body=%s", status, string(body))
}
return resp.Data.User.ID, resp.Data.Tokens
}
func (e *testEnv) login(email string) tokenPair {
e.t.Helper()
var resp authRegisterResp
status, body := e.doJSON(http.MethodPost, "/api/v1/auth/login", "", map[string]any{
"email": email,
"password": "password123",
}, &resp)
if status != http.StatusOK {
e.t.Fatalf("login status=%d body=%s", status, string(body))
}
return resp.Data.Tokens
}
func TestAcceptanceCoreFlows(t *testing.T) {
env := setupTestEnv(t)
ownerID, ownerTokens := env.register("owner@example.com")
viewerID, viewerTokens := env.register("viewer@example.com")
var meResp map[string]any
status, body := env.doJSON(http.MethodGet, "/api/v1/auth/me", ownerTokens.AccessToken, nil, &meResp)
if status != http.StatusOK {
t.Fatalf("auth/me status=%d body=%s", status, string(body))
}
var wsCreate workspaceCreateResp
status, body = env.doJSON(http.MethodPost, "/api/v1/workspaces", ownerTokens.AccessToken, map[string]any{
"name": "Main Workspace",
"description": "demo",
}, &wsCreate)
if status != http.StatusCreated {
t.Fatalf("create workspace status=%d body=%s", status, string(body))
}
workspaceID := wsCreate.Data.Workspace.ID
var members workspaceMembersResp
status, body = env.doJSON(http.MethodGet, fmt.Sprintf("/api/v1/workspaces/%d/users", workspaceID), ownerTokens.AccessToken, nil, &members)
if status != http.StatusOK {
t.Fatalf("list members status=%d body=%s", status, string(body))
}
if len(members.Data) == 0 || members.Data[0].UserID != ownerID || members.Data[0].Role != "admin" {
t.Fatalf("creator must be admin: %+v", members.Data)
}
status, body = env.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/workspaces/%d/users", workspaceID), ownerTokens.AccessToken, map[string]any{
"user_id": viewerID,
"role": "viewer",
}, nil)
if status != http.StatusCreated {
t.Fatalf("add viewer status=%d body=%s", status, string(body))
}
var workspaceList workspacesListResp
status, body = env.doJSON(http.MethodGet, "/api/v1/workspaces", viewerTokens.AccessToken, nil, &workspaceList)
if status != http.StatusOK || len(workspaceList.Data) == 0 {
t.Fatalf("viewer should see workspace: status=%d body=%s", status, string(body))
}
var errResp apiErrorResp
status, body = env.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/workspaces/%d/bookmarks", workspaceID), viewerTokens.AccessToken, map[string]any{
"title": "Denied",
"url": "https://example.com",
}, &errResp)
if status != http.StatusForbidden || errResp.Code != "workspace_forbidden" {
t.Fatalf("viewer create bookmark should be forbidden: status=%d code=%s body=%s", status, errResp.Code, string(body))
}
status, body = env.doJSON(http.MethodPatch, fmt.Sprintf("/api/v1/workspaces/%d/users/%d", workspaceID, viewerID), ownerTokens.AccessToken, map[string]any{
"role": "editor",
}, nil)
if status != http.StatusOK {
t.Fatalf("promote to editor status=%d body=%s", status, string(body))
}
status, body = env.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/workspaces/%d/bookmarks", workspaceID), viewerTokens.AccessToken, map[string]any{
"title": "Allowed",
"url": "https://example.com",
}, nil)
if status != http.StatusCreated {
t.Fatalf("editor create bookmark should pass: status=%d body=%s", status, string(body))
}
superID, _ := env.register("super@example.com")
superUser, err := orm.ByPK[models.User](context.Background(), env.db, superID)
if err != nil {
t.Fatalf("load super user: %v", err)
}
superUser.IsSuperadmin = true
if err := orm.Update(context.Background(), env.db, superUser); err != nil {
t.Fatalf("promote superadmin: %v", err)
}
superTokens := env.login("super@example.com")
status, body = env.doJSON(http.MethodGet, "/api/v1/auth/me", superTokens.AccessToken, nil, &meResp)
if status != http.StatusOK || meResp["data"].(map[string]any)["is_superadmin"] != true {
t.Fatalf("superadmin token should carry super flag: status=%d body=%s", status, string(body))
}
status, body = env.doJSON(http.MethodGet, "/api/v1/workspaces?all=true", superTokens.AccessToken, nil, &workspaceList)
if status != http.StatusOK || len(workspaceList.Data) == 0 {
t.Fatalf("superadmin should see all workspaces: status=%d body=%s", status, string(body))
}
status, body = env.doJSON(http.MethodGet, fmt.Sprintf("/api/v1/workspaces/%d/users", workspaceID), superTokens.AccessToken, nil, &members)
if status != http.StatusOK || len(members.Data) < 2 {
t.Fatalf("superadmin should list members: status=%d body=%s", status, string(body))
}
}
func TestMembershipConflict(t *testing.T) {
env := setupTestEnv(t)
_, ownerTokens := env.register("owner2@example.com")
memberID, _ := env.register("member2@example.com")
var wsCreate workspaceCreateResp
status, body := env.doJSON(http.MethodPost, "/api/v1/workspaces", ownerTokens.AccessToken, map[string]any{
"name": "Conflict Workspace",
}, &wsCreate)
if status != http.StatusCreated {
t.Fatalf("create workspace status=%d body=%s", status, string(body))
}
workspaceID := wsCreate.Data.Workspace.ID
status, body = env.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/workspaces/%d/users", workspaceID), ownerTokens.AccessToken, map[string]any{
"user_id": memberID,
"role": "viewer",
}, nil)
if status != http.StatusCreated {
t.Fatalf("first add member status=%d body=%s", status, string(body))
}
var errResp apiErrorResp
status, body = env.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/workspaces/%d/users", workspaceID), ownerTokens.AccessToken, map[string]any{
"user_id": memberID,
"role": "viewer",
}, &errResp)
if status != http.StatusConflict || errResp.Code != "workspace_membership_conflict" {
t.Fatalf("duplicate member should conflict: status=%d code=%s body=%s", status, errResp.Code, string(body))
}
}
func TestLastAdminGuard(t *testing.T) {
env := setupTestEnv(t)
ownerID, ownerTokens := env.register("owner3@example.com")
var wsCreate workspaceCreateResp
status, body := env.doJSON(http.MethodPost, "/api/v1/workspaces", ownerTokens.AccessToken, map[string]any{
"name": "Last Admin Workspace",
}, &wsCreate)
if status != http.StatusCreated {
t.Fatalf("create workspace status=%d body=%s", status, string(body))
}
workspaceID := wsCreate.Data.Workspace.ID
var errResp apiErrorResp
status, body = env.doJSON(http.MethodPatch, fmt.Sprintf("/api/v1/workspaces/%d/users/%d", workspaceID, ownerID), ownerTokens.AccessToken, map[string]any{
"role": "viewer",
}, &errResp)
if status != http.StatusConflict || errResp.Code != "workspace_last_admin_violation" {
t.Fatalf("demote last admin should conflict: status=%d code=%s body=%s", status, errResp.Code, string(body))
}
status, body = env.doJSON(http.MethodDelete, fmt.Sprintf("/api/v1/workspaces/%d/users/%d", workspaceID, ownerID), ownerTokens.AccessToken, nil, &errResp)
if status != http.StatusConflict || errResp.Code != "workspace_last_admin_violation" {
t.Fatalf("delete last admin should conflict: status=%d code=%s body=%s", status, errResp.Code, string(body))
}
}
func TestSoftDeletedTagIsIgnoredInBookmarkView(t *testing.T) {
env := setupTestEnv(t)
_, ownerTokens := env.register("owner4@example.com")
var wsCreate workspaceCreateResp
status, body := env.doJSON(http.MethodPost, "/api/v1/workspaces", ownerTokens.AccessToken, map[string]any{
"name": "Tags Workspace",
}, &wsCreate)
if status != http.StatusCreated {
t.Fatalf("create workspace status=%d body=%s", status, string(body))
}
workspaceID := wsCreate.Data.Workspace.ID
var tagResp struct {
Data struct {
ID int64 `json:"id"`
} `json:"data"`
}
status, body = env.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/workspaces/%d/tags", workspaceID), ownerTokens.AccessToken, map[string]any{
"name": "important",
"color": "#abc",
}, &tagResp)
if status != http.StatusCreated {
t.Fatalf("create tag status=%d body=%s", status, string(body))
}
var bookmarkResp bookmarkCreateResp
status, body = env.doJSON(http.MethodPost, fmt.Sprintf("/api/v1/workspaces/%d/bookmarks", workspaceID), ownerTokens.AccessToken, map[string]any{
"title": "Item",
"url": "https://example.com",
"tag_ids": []int64{tagResp.Data.ID},
}, &bookmarkResp)
if status != http.StatusCreated || len(bookmarkResp.Data.TagIDs) != 1 {
t.Fatalf("create bookmark with tag status=%d body=%s", status, string(body))
}
bookmarkID := bookmarkResp.Data.ID
status, body = env.doJSON(http.MethodDelete, fmt.Sprintf("/api/v1/workspaces/%d/tags/%d", workspaceID, tagResp.Data.ID), ownerTokens.AccessToken, nil, nil)
if status != http.StatusNoContent {
t.Fatalf("delete tag status=%d body=%s", status, string(body))
}
var bookmarkGet bookmarkCreateResp
status, body = env.doJSON(http.MethodGet, fmt.Sprintf("/api/v1/workspaces/%d/bookmarks/%d", workspaceID, bookmarkID), ownerTokens.AccessToken, nil, &bookmarkGet)
if status != http.StatusOK {
t.Fatalf("get bookmark status=%d body=%s", status, string(body))
}
if len(bookmarkGet.Data.TagIDs) != 0 {
t.Fatalf("soft deleted tag should be ignored in bookmark view, got=%v body=%s", bookmarkGet.Data.TagIDs, string(body))
}
}