package auth import ( "net/http" "net/http/httptest" "strings" "testing" "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 { name string sess *Session method string header string origin string 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}, } 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) } } }