-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
455 lines (414 loc) · 16.5 KB
/
Copy pathmain_test.go
File metadata and controls
455 lines (414 loc) · 16.5 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
package main
// Tests for admin endpoints in main.go.
// These tests use an in-memory SQLite database and exercise the admin
// handlers directly via httptest.
//
// Conventions:
// - Each bug fix is driven by a failing test written first (RED),
// then the smallest possible change to flip it to GREEN.
// - Tests are table-driven where it clarifies multiple scenarios.
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"io/fs"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"bookmark/app/utils"
"github.com/go-chi/chi/v5"
_ "modernc.org/sqlite"
)
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (fn roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return fn(req)
}
func testDBName(t *testing.T) string {
t.Helper()
// Temp file (not :memory:) avoids the "out of memory" error some
// modernc.org/sqlite builds emit for shared in-memory caches.
path := filepath.Join(os.TempDir(),
fmt.Sprintf("bookmarks_test_%s_%d.db", t.Name(), time.Now().UnixNano()))
return fmt.Sprintf("file:%s?_foreign_keys=on&_journal_mode=WAL&_busy_timeout=5000", path)
}
// newTestServer wires up a *server backed by a fresh in-memory SQLite.
// It creates the users, nodes, and audit_log tables the admin endpoints
// need without going through the full upgrade system.
func newTestServer(t *testing.T) (*server, *sql.DB) {
t.Helper()
dsn := testDBName(t)
dbPath := strings.TrimPrefix(strings.TrimSuffix(dsn, "?_foreign_keys=on&_journal_mode=WAL&_busy_timeout=5000"), "file:")
db, err := sql.Open("sqlite", dsn)
if err != nil {
t.Fatalf("open in-memory sqlite: %v", err)
}
db.SetMaxOpenConns(1)
if _, err := db.Exec("PRAGMA foreign_keys = ON"); err != nil {
t.Fatalf("enable foreign keys: %v", err)
}
mustExec(t, db, `
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
token TEXT,
nickname TEXT,
avatar TEXT,
email TEXT,
is_active INTEGER NOT NULL DEFAULT 1,
is_admin INTEGER NOT NULL DEFAULT 0,
api_key TEXT,
fnos_user_id INTEGER UNIQUE,
fnos_username TEXT NOT NULL DEFAULT '',
last_login_at DATETIME,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`)
mustExec(t, db, `
CREATE TABLE nodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL DEFAULT 0,
parent_id INTEGER,
type TEXT NOT NULL CHECK (type IN ('folder', 'bookmark')),
title TEXT NOT NULL,
url TEXT,
favicon_url TEXT,
remark TEXT NOT NULL DEFAULT '',
visibility TEXT NOT NULL DEFAULT 'private',
position INTEGER NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`)
mustExec(t, db, `
CREATE TABLE audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
username TEXT NOT NULL DEFAULT '',
action TEXT NOT NULL,
target_type TEXT NOT NULL DEFAULT '',
target_id INTEGER NOT NULL DEFAULT 0,
detail TEXT NOT NULL DEFAULT '',
ip_address TEXT NOT NULL DEFAULT '',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`)
srv := &server{db: db, httpClient: http.DefaultClient}
t.Cleanup(func() {
_ = db.Close()
_ = os.Remove(dbPath)
_ = os.Remove(dbPath + "-wal")
_ = os.Remove(dbPath + "-shm")
})
return srv, db
}
func mustExec(t *testing.T, db *sql.DB, stmt string, args ...any) {
t.Helper()
if _, err := db.Exec(stmt, args...); err != nil {
t.Fatalf("exec %q: %v", stmt, err)
}
}
func TestLoadTree_PreservesSQLSiblingOrder(t *testing.T) {
srv, db := newTestServer(t)
userID := insertTestUser(t, db, "tree-order", false)
insert := func(parentID *int64, nodeType, title string, position int) int64 {
t.Helper()
res, err := db.Exec(`INSERT INTO nodes (user_id, parent_id, type, title, position) VALUES (?, ?, ?, ?, ?)`, userID, parentID, nodeType, title, position)
if err != nil {
t.Fatalf("insert %s: %v", title, err)
}
id, err := res.LastInsertId()
if err != nil {
t.Fatalf("last insert id for %s: %v", title, err)
}
return id
}
second := insert(nil, nodeTypeFolder, "second", 2)
first := insert(nil, nodeTypeFolder, "first", 1)
insert(&first, nodeTypeBookmark, "later child", 2)
insert(&first, nodeTypeBookmark, "first child", 1)
_ = second
tree, err := srv.loadTree(context.Background(), userID)
if err != nil {
t.Fatalf("load tree: %v", err)
}
if len(tree) != 2 || tree[0].Title != "first" || tree[1].Title != "second" {
t.Fatalf("root order = %#v, want [first second]", tree)
}
if len(tree[0].Children) != 2 || tree[0].Children[0].Title != "first child" || tree[0].Children[1].Title != "later child" {
t.Fatalf("child order = %#v, want [first child later child]", tree[0].Children)
}
}
func TestCreateBookmark_DoesNotWaitForRemoteMetadata(t *testing.T) {
srv, db := newTestServer(t)
userID := insertTestUser(t, db, "create-fast", false)
// A nil favicon queue takes the non-blocking default branch. If the
// handler ever returns to synchronous metadata fetching, this client
// makes the regression deterministic instead of relying on the network.
srv.httpClient = &http.Client{Transport: roundTripperFunc(func(*http.Request) (*http.Response, error) {
t.Fatal("create bookmark must not issue a remote metadata request")
return nil, nil
})}
req := jsonRequest(t, http.MethodPost, "/bookmarks", map[string]string{"url": "https://example.com"})
req = req.WithContext(withUserID(req.Context(), userID))
rec := runHandler(srv, srv.handleCreateBookmark, req)
if rec.Code != http.StatusCreated {
t.Fatalf("create bookmark: want 201, got %d (body=%q)", rec.Code, rec.Body.String())
}
var created node
decodeJSON(t, rec, &created)
if created.Title != "https://example.com" {
t.Fatalf("temporary title = %q, want normalized URL", created.Title)
}
}
// insertTestUser inserts a users row and stores a stable token of the
// form "tok-<username>" so callers can authenticate by passing it as
// the Authorization header. nickname defaults to the username so
// handleGetUsers can scan it as a non-null string.
func insertTestUser(t *testing.T, db *sql.DB, username string, isAdmin bool) int64 {
t.Helper()
admin := 0
if isAdmin {
admin = 1
}
token := "tok-" + username
res, err := db.ExecContext(context.Background(),
`INSERT INTO users (username, password, nickname, email, is_admin, is_active, token) VALUES (?, ?, ?, ?, ?, 1, ?)`,
username, "x", username, username+"@example.com", admin, token)
if err != nil {
t.Fatalf("insert user: %v", err)
}
id, err := res.LastInsertId()
if err != nil {
t.Fatalf("LastInsertId: %v", err)
}
return id
}
// userTokenFor returns the canonical token stored for a user created via
// insertTestUser. Tests pass it in the Authorization header so the real
// tokenAuthMiddleware accepts the request.
func userTokenFor(username string) string { return "tok-" + username }
// withUserID returns a context carrying a user id, matching the
// shape main.go uses after the token-auth middleware sets it.
func withUserID(ctx context.Context, userID int64) context.Context {
return context.WithValue(ctx, userContextKey, userID)
}
// jsonRequest builds an *http.Request with a JSON body (or nil for GET/DELETE).
func jsonRequest(t *testing.T, method, path string, body any) *http.Request {
t.Helper()
var reader io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal body: %v", err)
}
reader = bytes.NewReader(b)
}
r := httptest.NewRequest(method, path, reader)
if body != nil {
r.Header.Set("Content-Type", "application/json")
}
return r
}
// newRecorder executes the handler under test and returns the recorder.
func runHandler(srv *server, h http.HandlerFunc, r *http.Request) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
h(rec, r)
return rec
}
func trustedFnOSRequest(t *testing.T, method, path string, body any, userID int64, username string) *http.Request {
t.Helper()
req := jsonRequest(t, method, path, body)
req.Header.Set("X-Trim-Userid", fmt.Sprint(userID))
req.Header.Set("X-Trim-Username", username)
return req.WithContext(context.WithValue(req.Context(), fnOSGatewayContextKey{}, true))
}
func TestFnOSHeadersRequireGatewayConnection(t *testing.T) {
srv, _ := newTestServer(t)
req := jsonRequest(t, http.MethodPost, "/api/auth/fnos/login", nil)
req.Header.Set("X-Trim-Userid", "1001")
req.Header.Set("X-Trim-Username", "forged-user")
rec := runHandler(srv, srv.handleFnOSLogin, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("untrusted fnOS headers: want 401, got %d (%s)", rec.Code, rec.Body.String())
}
}
func TestFnOSTicketBridgesGatewayIdentityToDirectPort(t *testing.T) {
srv, _ := newTestServer(t)
forgedReq := jsonRequest(t, http.MethodPost, "/api/auth/fnos/ticket", nil)
forgedReq.Header.Set("X-Trim-Userid", "1001")
forgedReq.Header.Set("X-Trim-Username", "nas-alice")
forgedRec := runHandler(srv, srv.handleFnOSTicket, forgedReq)
if forgedRec.Code != http.StatusUnauthorized {
t.Fatalf("untrusted ticket issue: want 401, got %d (%s)", forgedRec.Code, forgedRec.Body.String())
}
ticketReq := trustedFnOSRequest(t, http.MethodPost, "/api/auth/fnos/ticket", nil, 1001, "nas-alice")
ticketRec := runHandler(srv, srv.handleFnOSTicket, ticketReq)
if ticketRec.Code != http.StatusOK {
t.Fatalf("issue fnOS ticket: want 200, got %d (%s)", ticketRec.Code, ticketRec.Body.String())
}
var ticketData map[string]string
decodeJSON(t, ticketRec, &ticketData)
ticket := ticketData["ticket"]
if ticket == "" || ticketData["fnos_username"] != "nas-alice" {
t.Fatalf("unexpected ticket response: %#v", ticketData)
}
loginReq := jsonRequest(t, http.MethodPost, "/api/auth/fnos/login", nil)
loginReq.Header.Set("X-FnOS-Ticket", ticket)
loginRec := runHandler(srv, srv.handleFnOSLogin, loginReq)
if loginRec.Code != http.StatusOK {
t.Fatalf("direct-port ticket login: want 200, got %d (%s)", loginRec.Code, loginRec.Body.String())
}
var loginData map[string]any
decodeJSON(t, loginRec, &loginData)
if loginData["binding_required"] != true || loginData["fnos_username"] != "nas-alice" {
t.Fatalf("unexpected unbound ticket login response: %#v", loginData)
}
bindReq := jsonRequest(t, http.MethodPost, "/api/auth/fnos/bind", map[string]string{
"mode": "register", "username": "ticket-user", "password": "client-md5-password",
})
bindReq.Header.Set("X-FnOS-Ticket", ticket)
bindRec := runHandler(srv, srv.handleFnOSBind, bindReq)
if bindRec.Code != http.StatusOK {
t.Fatalf("direct-port ticket bind: want 200, got %d (%s)", bindRec.Code, bindRec.Body.String())
}
reuseReq := jsonRequest(t, http.MethodPost, "/api/auth/fnos/login", nil)
reuseReq.Header.Set("X-FnOS-Ticket", ticket)
reuseRec := runHandler(srv, srv.handleFnOSLogin, reuseReq)
if reuseRec.Code != http.StatusUnauthorized {
t.Fatalf("consumed fnOS ticket: want 401, got %d (%s)", reuseRec.Code, reuseRec.Body.String())
}
}
func TestFnOSLoginUIIsOnlyInjectedForGatewaySocket(t *testing.T) {
staticFiles, err := fs.Sub(staticFS, "static")
if err != nil {
t.Fatalf("open embedded static files: %v", err)
}
prefix := "/app/techfunway-bookmarks"
handler := fnOSGatewayProxy(prefix, fnOSStaticFileServer(staticFiles))
direct := httptest.NewRequest(http.MethodGet, prefix+"/login.html", nil)
directRec := httptest.NewRecorder()
handler.ServeHTTP(directRec, direct)
if strings.Contains(directRec.Body.String(), "__bookmarksFnOSURL=function") {
t.Fatal("direct port request must not receive the fnOS one-click-login bootstrap")
}
trusted := httptest.NewRequest(http.MethodGet, prefix+"/login.html", nil)
trusted = trusted.WithContext(context.WithValue(trusted.Context(), fnOSGatewayContextKey{}, true))
trustedRec := httptest.NewRecorder()
handler.ServeHTTP(trustedRec, trusted)
if !strings.Contains(trustedRec.Body.String(), "__bookmarksFnOSURL=function") {
t.Fatal("gateway socket request must receive the fnOS one-click-login bootstrap")
}
}
func TestEnsureFnOSBindingSchemaMigratesExistingUsers(t *testing.T) {
dsn := testDBName(t)
dbPath := strings.TrimPrefix(strings.TrimSuffix(dsn, "?_foreign_keys=on&_journal_mode=WAL&_busy_timeout=5000"), "file:")
db, err := sql.Open("sqlite", dsn)
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
defer func() {
_ = db.Close()
_ = os.Remove(dbPath)
_ = os.Remove(dbPath + "-wal")
_ = os.Remove(dbPath + "-shm")
}()
mustExec(t, db, `CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT NOT NULL UNIQUE)`)
if err := ensureFnOSBindingSchema(db); err != nil {
t.Fatalf("ensure fnOS binding schema: %v", err)
}
if _, err := db.Exec(`INSERT INTO users (id, username, fnos_user_id, fnos_username) VALUES (1, 'one', 88, 'nas-one')`); err != nil {
t.Fatalf("insert bound user: %v", err)
}
if _, err := db.Exec(`INSERT INTO users (id, username, fnos_user_id) VALUES (2, 'two', 88)`); err == nil {
t.Fatal("duplicate fnOS user ID should be rejected by the unique index")
}
}
func TestFnOSRegisterBindThenOneClickLogin(t *testing.T) {
srv, db := newTestServer(t)
bindReq := trustedFnOSRequest(t, http.MethodPost, "/api/auth/fnos/bind", map[string]string{
"mode": "register", "username": "nas-alice", "password": "client-md5-password",
}, 1001, "alice")
bindRec := runHandler(srv, srv.handleFnOSBind, bindReq)
if bindRec.Code != http.StatusOK {
t.Fatalf("register and bind: want 200, got %d (%s)", bindRec.Code, bindRec.Body.String())
}
var bound authResponse
decodeJSON(t, bindRec, &bound)
if bound.Token == "" || bound.User == nil || bound.User.Username != "nas-alice" || !bound.User.IsAdmin {
t.Fatalf("unexpected bind response: %+v", bound)
}
loginReq := trustedFnOSRequest(t, http.MethodPost, "/api/auth/fnos/login", nil, 1001, "alice-renamed")
loginRec := runHandler(srv, srv.handleFnOSLogin, loginReq)
if loginRec.Code != http.StatusOK {
t.Fatalf("one-click login: want 200, got %d (%s)", loginRec.Code, loginRec.Body.String())
}
var loggedIn authResponse
decodeJSON(t, loginRec, &loggedIn)
if loggedIn.Token != bound.Token || loggedIn.User == nil || loggedIn.User.ID != bound.User.ID {
t.Fatalf("one-click login returned a different account: %+v", loggedIn)
}
var storedName string
if err := db.QueryRow(`SELECT fnos_username FROM users WHERE id = ?`, bound.User.ID).Scan(&storedName); err != nil {
t.Fatalf("read stored fnOS username: %v", err)
}
if storedName != "alice-renamed" {
t.Fatalf("fnOS username was not refreshed: got %q", storedName)
}
}
func TestFnOSCannotBindOneAppAccountToDifferentNASUser(t *testing.T) {
srv, db := newTestServer(t)
passwordMD5 := "client-md5-password"
mustExec(t, db, `INSERT INTO users (username, password, nickname, fnos_user_id) VALUES (?, ?, ?, ?)`, "bound-user", utils.MD5Hash(passwordMD5, "bookmarks"), "bound-user", 2001)
req := trustedFnOSRequest(t, http.MethodPost, "/api/auth/fnos/bind", map[string]string{
"mode": "bind", "username": "bound-user", "password": passwordMD5,
}, 2002, "other-user")
rec := runHandler(srv, srv.handleFnOSBind, req)
if rec.Code != http.StatusConflict {
t.Fatalf("bind already-bound app account: want 409, got %d (%s)", rec.Code, rec.Body.String())
}
}
// newAdminRouter returns a chi router that mounts only the admin endpoints
// with the same middleware stack as main.go. Tests use this to assert
// end-to-end status codes without spinning up a real HTTP listener.
func newAdminRouter(srv *server) http.Handler {
r := chi.NewRouter()
r.Use(srv.tokenAuthMiddlewareChi)
r.Use(srv.adminMiddlewareChi)
r.Get("/admin/stats", srv.handleAdminStats)
r.Get("/admin/users/{userId}/tree", srv.handleAdminGetUserTree)
r.Put("/admin/nodes/{id}", srv.handleAdminUpdateNode)
r.Delete("/admin/nodes/{id}", srv.handleAdminDeleteNode)
r.Get("/admin/audit-log", srv.handleGetAuditLog)
r.Post("/admin/folders", srv.handleAdminCreateFolder)
r.Post("/admin/bookmarks", srv.handleAdminCreateBookmark)
r.Put("/admin/nodes/reorder", srv.handleAdminReorderNodes)
return r
}
// do runs an HTTP request through the router and returns the response.
func do(t *testing.T, h http.Handler, r *http.Request) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
return rec
}
// decodeJSON unmarshals a response body into target and fails the test
// on any decode error.
func decodeJSON(t *testing.T, rec *httptest.ResponseRecorder, target any) {
t.Helper()
if err := json.NewDecoder(rec.Body).Decode(target); err != nil {
t.Fatalf("decode json (status=%d, body=%q): %v", rec.Code, rec.Body.String(), err)
}
}
// contains reports whether sub is contained in s.
func contains(s, sub string) bool {
return strings.Contains(s, sub)
}