Files

63 lines
2.1 KiB
Go

package auth
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestCSRF(t *testing.T) {
sess := &Session{CSRF: "good"}
tests := []struct {
name string
sess *Session
method string
header string
origin string
form string
want int
}{
{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},
}
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)
}
})
}
}