Files
uptimesebi/internal/auth/middleware_test.go
T
Sebastian UnterschützandClaude Opus 5.5 9667e121f1 feat(auth): add session middleware and csrf protection
Unsafe methods require the session's synchronizer token and a matching
Origin, which also covers login requests that have no session yet.

Refs #5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-21 23:49:08 +01:00

64 lines
1.7 KiB
Go

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)
}
}
}