package main import ( "net/http" "net/http/httptest" "strings" "testing" "time" ) func TestPasswordUnicodeAndNoTruncation(t *testing.T) { password := strings.Repeat("🔑", 128) if !validPassword(password) || validPassword(password+"x") || validPassword("too-short") || validPassword(strings.Repeat(" ", 12)) { t.Fatal("password code point boundaries") } hash := hashPassword(password) if !verifyPassword(hash, password) || verifyPassword(hash, password[:len(password)-4]+"x") || verifyPassword("corrupt", password) { t.Fatal("password verification/truncation") } } func TestCursorScopeAndValidation(t *testing.T) { a := &app{} now := time.Now().UTC() p := cursor{"messages:chat-a", now, "11111111-1111-4111-8111-111111111111"} cases := []struct { query string valid bool }{ {"limit=1&cursor=" + encodeCursor(p), true}, {"limit=100&cursor=" + encodeCursor(p), true}, {"limit=0", false}, {"limit=101", false}, {"limit=1.2", false}, {"cursor=garbage", false}, {"cursor=" + encodeCursor(cursor{"messages:chat-b", now, p.ID}), false}, {"cursor=" + encodeCursor(cursor{p.Resource, now, "bad-id"}), false}, {"cursor=" + encodeCursor(cursor{p.Resource, time.Time{}, p.ID}), false}, } for _, c := range cases { r := httptest.NewRequest("GET", "/messages?"+c.query, nil) w := httptest.NewRecorder() _, _, ok := a.position(w, r, p.Resource) if ok != c.valid { t.Errorf("cursor query %s: valid=%v", c.query, ok) } } } func TestStrictJSONAndBodyLimit(t *testing.T) { a := &app{limits: limits{maxBodyBytes: 128}} for _, data := range []string{`{"text":12}`, `{"text":"ok","sender_id":"spoof"}`, `{"text":"ok"} {}`, `{`, "{\"text\":\"\xff\"}"} { w := httptest.NewRecorder() var input createMessage if a.decode(w, httptest.NewRequest("POST", "/", strings.NewReader(data)), &input) || w.Code != 400 { t.Errorf("accepted invalid JSON %q", data) } } w := httptest.NewRecorder() var input createMessage if a.decode(w, httptest.NewRequest("POST", "/", strings.NewReader(strings.Repeat("x", 129))), &input) || w.Code != 413 { t.Fatal("body limit") } } func TestBearerDoesNotTrustUserHeader(t *testing.T) { r := httptest.NewRequest("GET", "/", nil) r.Header.Set("X-User-Id", newID()) if bearer(r) != "" { t.Fatal("trusted X-User-Id") } r.Header.Set("Authorization", "Basic dXNlcjpwYXNz") if bearer(r) != "" { t.Fatal("accepted Basic") } r.Header.Set("Authorization", "Bearer "+strings.Repeat("A", 43)) if bearer(r) == "" { t.Fatal("rejected valid 256 bit token encoding") } r.Header.Set("Authorization", "Bearer "+strings.Repeat("!", 43)) if bearer(r) != "" { t.Fatal("accepted malformed token") } } func TestLogoutMissingTokenChallenge(t *testing.T) { a := &app{} w := httptest.NewRecorder() a.logout(w, httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)) if w.Code != 401 || w.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` { t.Fatal("logout challenge") } }