From cdcc91a60ff3d6ac0b28a255e111b4cd383af44f Mon Sep 17 00:00:00 2001 From: Kian Parvin Date: Wed, 4 Sep 2024 15:51:44 +0200 Subject: [PATCH] add test that CORS is enabled correctly --- cmd/jimmsrv/service/service_test.go | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/cmd/jimmsrv/service/service_test.go b/cmd/jimmsrv/service/service_test.go index 9bc815d69..3d35384bc 100644 --- a/cmd/jimmsrv/service/service_test.go +++ b/cmd/jimmsrv/service/service_test.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "net/http/httptest" + "net/url" "os" "testing" @@ -483,3 +484,46 @@ func TestCleanupDoesNotPanic_SessionStoreRelatedCleanups(t *testing.T) { svc.Cleanup() } + +func TestCORS(t *testing.T) { + c := qt.New(t) + + _, _, cofgaParams, err := jimmtest.SetupTestOFGAClient(c.Name()) + c.Assert(err, qt.IsNil) + p := jimmtest.NewTestJimmParams(c) + p.OpenFGAParams = cofgaParamsToJIMMOpenFGAParams(*cofgaParams) + allowedOrigin := "http://my-referrer.com" + p.CorsAllowedOrigins = []string{allowedOrigin} + p.InsecureSecretStorage = true + + svc, err := jimmsvc.NewService(context.Background(), p) + c.Assert(err, qt.IsNil) + defer svc.Cleanup() + + srv := httptest.NewServer(svc) + c.Cleanup(srv.Close) + + url, err := url.Parse(srv.URL + "/debug/info") + c.Assert(err, qt.IsNil) + // Invalid origin won't receive CORS headers. + req := http.Request{ + Method: "GET", + URL: url, + Header: http.Header{"Origin": []string{"123"}}, + } + response, err := srv.Client().Do(&req) + c.Assert(err, qt.IsNil) + defer response.Body.Close() + c.Assert(response.StatusCode, qt.Equals, http.StatusOK) + c.Assert(response.Header.Get("Access-Control-Allow-Credentials"), qt.Equals, "") + c.Assert(response.Header.Get("Access-Control-Allow-Origin"), qt.Equals, "") + + // Valid origin should receive CORS headers. + req.Header = http.Header{"Origin": []string{allowedOrigin}} + response, err = srv.Client().Do(&req) + c.Assert(err, qt.IsNil) + defer response.Body.Close() + c.Assert(response.StatusCode, qt.Equals, http.StatusOK) + c.Assert(response.Header.Get("Access-Control-Allow-Credentials"), qt.Equals, "true") + c.Assert(response.Header.Get("Access-Control-Allow-Origin"), qt.Equals, allowedOrigin) +}