test: report failures as got/want and use subtests for tables
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
d20225982a
commit
b6843330a8
8 files changed
+184
-175
No files matched your search
@@ -9,21 +9,9 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func csrfRouter(sess *Session) *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
if sess != nil {
|
||||
c.Set(ctxKey, sess)
|
||||
}
|
||||
}, CSRF())
|
||||
r.Any("/x", func(c *gin.Context) { c.Status(http.StatusNoContent) })
|
||||
return r
|
||||
}
|
||||
|
||||
func TestCSRF(t *testing.T) {
|
||||
sess := &Session{CSRF: "good"}
|
||||
cases := []struct {
|
||||
tests := []struct {
|
||||
name string
|
||||
sess *Session
|
||||
method string
|
||||
@@ -32,32 +20,43 @@ func TestCSRF(t *testing.T) {
|
||||
form string
|
||||
want int
|
||||
}{
|
||||
{"safe method", sess, http.MethodGet, "", "", "", 204},
|
||||
{"missing token", sess, http.MethodPost, "", "", "", 403},
|
||||
{"wrong token", sess, http.MethodPost, "bad", "", "", 403},
|
||||
{"header token", sess, http.MethodPost, "good", "", "", 204},
|
||||
{"form token", sess, http.MethodPost, "", "", "_csrf=good", 204},
|
||||
{"no session", nil, http.MethodPost, "", "", "", 204},
|
||||
{"same origin", nil, http.MethodPost, "", "http://example.com", "", 204},
|
||||
{"foreign origin without session", nil, http.MethodPost, "", "https://evil.test", "", 403},
|
||||
{"foreign origin with token", sess, http.MethodPost, "good", "https://evil.test", "", 403},
|
||||
{"opaque origin", nil, http.MethodPost, "", "null", "", 403},
|
||||
{name: "safe method", sess: sess, method: http.MethodGet, want: http.StatusNoContent},
|
||||
{name: "missing token", sess: sess, method: http.MethodPost, want: http.StatusForbidden},
|
||||
{name: "wrong token", sess: sess, method: http.MethodPost, header: "bad", want: http.StatusForbidden},
|
||||
{name: "header token", sess: sess, method: http.MethodPost, header: "good", want: http.StatusNoContent},
|
||||
{name: "form token", sess: sess, method: http.MethodPost, form: "_csrf=good", want: http.StatusNoContent},
|
||||
{name: "no session", method: http.MethodPost, want: http.StatusNoContent},
|
||||
{name: "same origin", method: http.MethodPost, origin: "http://example.com", want: http.StatusNoContent},
|
||||
{name: "foreign origin without session", method: http.MethodPost, origin: "https://evil.test", want: http.StatusForbidden},
|
||||
{name: "foreign origin with token", sess: sess, method: http.MethodPost, header: "good", origin: "https://evil.test", want: http.StatusForbidden},
|
||||
{name: "opaque origin", method: http.MethodPost, origin: "null", want: http.StatusForbidden},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
req := httptest.NewRequest(tc.method, "/x", strings.NewReader(tc.form))
|
||||
if tc.form != "" {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
if tc.origin != "" {
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
}
|
||||
if tc.header != "" {
|
||||
req.Header.Set(CSRFHeader, tc.header)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
csrfRouter(tc.sess).ServeHTTP(w, req)
|
||||
if w.Code != tc.want {
|
||||
t.Errorf("%s: got %d want %d", tc.name, w.Code, tc.want)
|
||||
}
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
if tt.sess != nil {
|
||||
c.Set(ctxKey, tt.sess)
|
||||
}
|
||||
}, CSRF())
|
||||
r.Any("/x", func(c *gin.Context) { c.Status(http.StatusNoContent) })
|
||||
|
||||
req := httptest.NewRequest(tt.method, "/x", strings.NewReader(tt.form))
|
||||
if tt.form != "" {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
if tt.origin != "" {
|
||||
req.Header.Set("Origin", tt.origin)
|
||||
}
|
||||
if tt.header != "" {
|
||||
req.Header.Set(CSRFHeader, tt.header)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != tt.want {
|
||||
t.Errorf("%s /x = %d, want %d", tt.method, w.Code, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,42 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPasswordHash(t *testing.T) {
|
||||
h, err := HashPassword("correct horse battery")
|
||||
func TestHashPassword(t *testing.T) {
|
||||
const pw = "correct horse battery"
|
||||
h, err := HashPassword(pw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("HashPassword(%q) failed: %v", pw, err)
|
||||
}
|
||||
if ok, rehash, err := VerifyPassword(h, "correct horse battery"); !ok || rehash || err != nil {
|
||||
t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err)
|
||||
ok, rehash, err := VerifyPassword(h, pw)
|
||||
if err != nil || !ok || rehash {
|
||||
t.Errorf("VerifyPassword(h, %q) = %v, %v, %v; want true, false, nil", pw, ok, rehash, err)
|
||||
}
|
||||
if ok, _, _ := VerifyPassword(h, "correct horse batterz"); ok {
|
||||
t.Fatal("wrong password accepted")
|
||||
if ok, _, _ := VerifyPassword(h, pw+"x"); ok {
|
||||
t.Errorf("VerifyPassword(h, %q) = true, want false", pw+"x")
|
||||
}
|
||||
if _, err := HashPassword("short"); err != ErrPasswordTooShort {
|
||||
t.Fatalf("got %v", err)
|
||||
if _, err := HashPassword("short"); !errors.Is(err, ErrPasswordTooShort) {
|
||||
t.Errorf("HashPassword(%q) error = %v, want %v", "short", err, ErrPasswordTooShort)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordRehashOnWeakerParams(t *testing.T) {
|
||||
saved := current
|
||||
current = argonParams{memory: 8 * 1024, time: 1, threads: 1, keyLen: 32}
|
||||
h, _ := HashPassword("correct horse battery")
|
||||
current = saved
|
||||
ok, rehash, err := VerifyPassword(h, "correct horse battery")
|
||||
if !ok || !rehash || err != nil {
|
||||
t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err)
|
||||
func TestVerifyPasswordRequestsRehashForOldParams(t *testing.T) {
|
||||
const pw = "correct horse battery"
|
||||
weak := argonParams{memory: 8 * 1024, time: 1, threads: 1, keyLen: 32}
|
||||
ok, rehash, err := VerifyPassword(hashPassword(pw, weak), pw)
|
||||
if err != nil || !ok || !rehash {
|
||||
t.Errorf("VerifyPassword(weak hash) = %v, %v, %v; want true, true, nil", ok, rehash, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordHashRejectsForeignFormats(t *testing.T) {
|
||||
for _, h := range []string{"", "$2a$10$abc", strings.Replace(dummyHash, "argon2id", "argon2i", 1)} {
|
||||
func TestVerifyPasswordRejectsForeignFormats(t *testing.T) {
|
||||
for _, h := range []string{"", "$2a$10$abc", strings.Replace(dummyHash(), "argon2id", "argon2i", 1)} {
|
||||
if _, _, err := VerifyPassword(h, "x"); err == nil {
|
||||
t.Errorf("accepted %q", h)
|
||||
t.Errorf("VerifyPassword(%q, _) error = nil, want error", h)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func testSessions(t *testing.T) (*Sessions, *time.Time) {
|
||||
func newTestRedis(t *testing.T) *redis.Client {
|
||||
t.Helper()
|
||||
url := os.Getenv("UPTIME_TEST_REDIS_URL")
|
||||
if url == "" {
|
||||
@@ -19,82 +19,92 @@ func testSessions(t *testing.T) (*Sessions, *time.Time) {
|
||||
}
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("redis.ParseURL(%q) failed: %v", url, err)
|
||||
}
|
||||
rdb := redis.NewClient(opts)
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
return rdb
|
||||
}
|
||||
|
||||
func newTestSessions(t *testing.T) (*Sessions, *time.Time) {
|
||||
t.Helper()
|
||||
now := time.Now()
|
||||
s := NewSessions(rdb, time.Hour, 24*time.Hour)
|
||||
s := NewSessions(newTestRedis(t), time.Hour, 24*time.Hour)
|
||||
s.now = func() time.Time { return now }
|
||||
return s, &now
|
||||
}
|
||||
|
||||
func mustCreate(t *testing.T, s *Sessions, user uuid.UUID) *Session {
|
||||
t.Helper()
|
||||
sess, err := s.Create(context.Background(), user, uuid.Nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("Create() failed: %v", err)
|
||||
}
|
||||
return sess
|
||||
}
|
||||
|
||||
func TestSessionRoundTrip(t *testing.T) {
|
||||
s, _ := testSessions(t)
|
||||
s, _ := newTestSessions(t)
|
||||
ctx := context.Background()
|
||||
user, org := uuid.New(), uuid.New()
|
||||
|
||||
created, err := s.Create(ctx, user, org, "de")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("Create() failed: %v", err)
|
||||
}
|
||||
got, err := s.Get(ctx, created.Token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("Get() failed: %v", err)
|
||||
}
|
||||
if got.UserID != user || got.OrgID != org || got.Locale != "de" || got.CSRF != created.CSRF {
|
||||
t.Fatalf("mismatch: %+v vs %+v", got, created)
|
||||
t.Errorf("Get() = %+v, want user %v org %v locale de csrf %q", got, user, org, created.CSRF)
|
||||
}
|
||||
if !got.CheckCSRF(created.CSRF) || got.CheckCSRF("") || got.CheckCSRF("x") {
|
||||
t.Fatal("csrf check wrong")
|
||||
for token, want := range map[string]bool{created.CSRF: true, "": false, "x": false} {
|
||||
if ok := got.CheckCSRF(token); ok != want {
|
||||
t.Errorf("CheckCSRF(%q) = %t, want %t", token, ok, want)
|
||||
}
|
||||
}
|
||||
if err := s.Delete(ctx, got); err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("Delete() failed: %v", err)
|
||||
}
|
||||
if _, err := s.Get(ctx, created.Token); !errors.Is(err, ErrNoSession) {
|
||||
t.Fatalf("deleted session still valid: %v", err)
|
||||
t.Errorf("Get(deleted) error = %v, want %v", err, ErrNoSession)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionAbsoluteLifetime(t *testing.T) {
|
||||
s, now := testSessions(t)
|
||||
ctx := context.Background()
|
||||
sess, err := s.Create(ctx, uuid.New(), uuid.Nil, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, now := newTestSessions(t)
|
||||
sess := mustCreate(t, s, uuid.New())
|
||||
*now = now.Add(25 * time.Hour)
|
||||
if _, err := s.Get(ctx, sess.Token); !errors.Is(err, ErrNoSession) {
|
||||
t.Fatalf("expired session accepted: %v", err)
|
||||
if _, err := s.Get(context.Background(), sess.Token); !errors.Is(err, ErrNoSession) {
|
||||
t.Errorf("Get(after absolute lifetime) error = %v, want %v", err, ErrNoSession)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteAllForUser(t *testing.T) {
|
||||
s, _ := testSessions(t)
|
||||
s, _ := newTestSessions(t)
|
||||
ctx := context.Background()
|
||||
user := uuid.New()
|
||||
a, _ := s.Create(ctx, user, uuid.Nil, "")
|
||||
b, _ := s.Create(ctx, user, uuid.Nil, "")
|
||||
other, _ := s.Create(ctx, uuid.New(), uuid.Nil, "")
|
||||
a, b := mustCreate(t, s, user), mustCreate(t, s, user)
|
||||
other := mustCreate(t, s, uuid.New())
|
||||
|
||||
if err := s.DeleteAllForUser(ctx, user); err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("DeleteAllForUser() failed: %v", err)
|
||||
}
|
||||
for _, tok := range []string{a.Token, b.Token} {
|
||||
if _, err := s.Get(ctx, tok); !errors.Is(err, ErrNoSession) {
|
||||
t.Fatal("session survived DeleteAllForUser")
|
||||
for _, sess := range []*Session{a, b} {
|
||||
if _, err := s.Get(ctx, sess.Token); !errors.Is(err, ErrNoSession) {
|
||||
t.Errorf("Get(session of removed user) error = %v, want %v", err, ErrNoSession)
|
||||
}
|
||||
}
|
||||
if _, err := s.Get(ctx, other.Token); err != nil {
|
||||
t.Fatalf("unrelated session removed: %v", err)
|
||||
t.Errorf("Get(session of other user) error = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenNotStoredInPlain(t *testing.T) {
|
||||
s, _ := testSessions(t)
|
||||
ctx := context.Background()
|
||||
sess, _ := s.Create(ctx, uuid.New(), uuid.Nil, "")
|
||||
if n, _ := s.rdb.Exists(ctx, "session:"+sess.Token).Result(); n != 0 {
|
||||
t.Fatal("raw token used as redis key")
|
||||
func TestTokenIsNotStoredInPlain(t *testing.T) {
|
||||
s, _ := newTestSessions(t)
|
||||
sess := mustCreate(t, s, uuid.New())
|
||||
if n, err := s.rdb.Exists(context.Background(), "session:"+sess.Token).Result(); err != nil || n != 0 {
|
||||
t.Errorf("EXISTS session:<raw token> = %d, %v; want 0, nil", n, err)
|
||||
}
|
||||
}
|
||||
+16
-19
@@ -2,42 +2,39 @@ package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/pquerna/otp/totp"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func TestTOTPRejectsReplay(t *testing.T) {
|
||||
url := os.Getenv("UPTIME_TEST_REDIS_URL")
|
||||
if url == "" {
|
||||
t.Skip("UPTIME_TEST_REDIS_URL not set")
|
||||
}
|
||||
opts, _ := redis.ParseURL(url)
|
||||
rdb := redis.NewClient(opts)
|
||||
defer rdb.Close()
|
||||
|
||||
func TestTOTPVerifierRejectsReplay(t *testing.T) {
|
||||
key, err := NewTOTPKey("a@example.test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("NewTOTPKey() failed: %v", err)
|
||||
}
|
||||
now := time.Now()
|
||||
code, _ := totp.GenerateCode(key.Secret(), now)
|
||||
v := NewTOTPVerifier(rdb)
|
||||
code, err := totp.GenerateCode(key.Secret(), now)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateCode() failed: %v", err)
|
||||
}
|
||||
v := NewTOTPVerifier(newTestRedis(t))
|
||||
v.now = func() time.Time { return now }
|
||||
user := uuid.New()
|
||||
ctx := context.Background()
|
||||
|
||||
if ok, err := v.Verify(ctx, user, key.Secret(), code); !ok || err != nil {
|
||||
t.Fatalf("first use rejected: %v", err)
|
||||
t.Errorf("Verify(fresh code) = %t, %v; want true, nil", ok, err)
|
||||
}
|
||||
if ok, _ := v.Verify(ctx, user, key.Secret(), code); ok {
|
||||
t.Fatal("replayed code accepted")
|
||||
if ok, err := v.Verify(ctx, user, key.Secret(), code); ok || err != nil {
|
||||
t.Errorf("Verify(replayed code) = %t, %v; want false, nil", ok, err)
|
||||
}
|
||||
if ok, _ := v.Verify(ctx, user, key.Secret(), "000000"); ok {
|
||||
t.Fatal("wrong code accepted")
|
||||
wrong := "000000"
|
||||
if wrong == code {
|
||||
wrong = "000001"
|
||||
}
|
||||
if ok, err := v.Verify(ctx, user, key.Secret(), wrong); ok || err != nil {
|
||||
t.Errorf("Verify(wrong code) = %t, %v; want false, nil", ok, err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user