package services import ( "net/http/httptest" "testing" "github.com/gin-gonic/gin" ) func TestIsSiteOrigin(t *testing.T) { cases := []struct { origin, domain string want bool }{ {"https://www.example.com", "example.com", true}, {"https://example.com", "example.com", true}, {"https://radar.example.com", "example.com", false}, {"https://git.example.com", "example.com", false}, {"https://www.example.com.evil.test", "example.com", false}, {"https://evilexample.com", "example.com", false}, {"null", "example.com", false}, {"http://localhost:5173", "localhost", true}, {"http://localhost:5173", "example.com", false}, {"https://anything", "", false}, } for _, c := range cases { if got := IsSiteOrigin(c.origin, c.domain); got != c.want { t.Errorf("IsSiteOrigin(%q, %q) = %v, want %v", c.origin, c.domain, got, c.want) } } } func TestRequireSameOrigin(t *testing.T) { gin.SetMode(gin.TestMode) cases := []struct { name string method string headers map[string]string want int }{ {"GET is never checked", "GET", map[string]string{"Origin": "https://evil.test"}, 200}, {"POST from www", "POST", map[string]string{"Origin": "https://www.example.com"}, 200}, {"POST from a sibling subdomain", "POST", map[string]string{"Origin": "https://radar.example.com"}, 403}, {"POST from another site", "POST", map[string]string{"Origin": "https://evil.test"}, 403}, {"POST with an opaque origin", "POST", map[string]string{"Origin": "null"}, 403}, {"DELETE from another site", "DELETE", map[string]string{"Origin": "https://evil.test"}, 403}, {"no Origin, same-site fetch", "POST", map[string]string{"Sec-Fetch-Site": "same-site"}, 403}, {"no Origin, same-origin fetch", "POST", map[string]string{"Sec-Fetch-Site": "same-origin"}, 200}, {"no browser headers (curl, server to server)", "POST", nil, 200}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { r := gin.New() r.Use(RequireSameOrigin("example.com")) r.Handle(c.method, "/x", func(ctx *gin.Context) { ctx.Status(200) }) req := httptest.NewRequest(c.method, "/x", nil) for k, v := range c.headers { req.Header.Set(k, v) } rec := httptest.NewRecorder() r.ServeHTTP(rec, req) if rec.Code != c.want { t.Fatalf("status %d, want %d", rec.Code, c.want) } }) } }