From 06d818cc613512f2591284bef222b807bde9d6f0 Mon Sep 17 00:00:00 2001 From: Kerod-Fresenbet-Gebremedhin2660 Date: Sun, 1 Nov 2026 14:58:54 +0300 Subject: [PATCH] fix: header normalization fixed in server --- db/migrations/000001_Rezina.up.sql | 2 +- internal/web_server/app.go | 44 ++++++++------ internal/web_server/cors_test.go | 98 ++++++++++++++++++++++++++++++ 3 files changed, 125 insertions(+), 19 deletions(-) create mode 100644 internal/web_server/cors_test.go diff --git a/db/migrations/000001_Rezina.up.sql b/db/migrations/000001_Rezina.up.sql index bd140662..e58ef3de 100644 --- a/db/migrations/000001_Rezina.up.sql +++ b/db/migrations/000001_Rezina.up.sql @@ -4881,7 +4881,7 @@ INSERT INTO exam_prep.unit_modules ( id, unit_id, name, description, thumbnail, icon, sort_order, publish_status, access_tier, created_at, updated_at ) -SELECT mm.migrated_id, um.migrated_id, m.name, m.description, m.thumbnail, m.icon, +SELECT mm.migrated_id, um.migrated_id, m.name, m.description, NULL::text, m.icon, m.sort_order, m.publish_status, m.access_tier, m.created_at, m.updated_at FROM modules m JOIN lms_exam_prep_migration_map mm ON mm.entity_kind = 'MODULE' AND mm.legacy_id = m.id diff --git a/internal/web_server/app.go b/internal/web_server/app.go index 5caba391..2a374f38 100644 --- a/internal/web_server/app.go +++ b/internal/web_server/app.go @@ -100,6 +100,31 @@ type App struct { learnerNotifSvc *learnernotifications.Service } +// newFiberApp applies the same HTTP configuration and global middleware in production and tests. +func newFiberApp() *fiber.App { + app := fiber.New(fiber.Config{ + CaseSensitive: true, + // Keep header normalization enabled so lowercase HTTP/2 headers forwarded + // by reverse proxies are recognized by CORS and authentication middleware. + JSONEncoder: sonic.Marshal, + JSONDecoder: sonic.Unmarshal, + BodyLimit: 500 * 1024 * 1024, // 500 MB + }) + + app.Use(cors.New(cors.Config{ + AllowOrigins: "*", + AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS", + // AllowHeaders empty: preflight echoes Access-Control-Request-Headers (e.g. Accept for CSV export fetch). + ExposeHeaders: "Content-Disposition", + // AllowCredentials: true, + })) + app.Use(recover.New()) + + app.Static("/static", "./static") + + return app +} + func NewApp( questionsSvc *questions.Service, faqSvc *faqs.Service, @@ -141,24 +166,7 @@ func NewApp( videoEngagementSvc *videoengagement.Service, learnerNotifSvc *learnernotifications.Service, ) *App { - app := fiber.New(fiber.Config{ - CaseSensitive: true, - DisableHeaderNormalizing: true, - JSONEncoder: sonic.Marshal, - JSONDecoder: sonic.Unmarshal, - BodyLimit: 500 * 1024 * 1024, // 500 MB - }) - - app.Use(cors.New(cors.Config{ - AllowOrigins: "*", - AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS", - // AllowHeaders empty: preflight echoes Access-Control-Request-Headers (e.g. Accept for CSV export fetch). - ExposeHeaders: "Content-Disposition", - // AllowCredentials: true, - })) - app.Use(recover.New()) - - app.Static("/static", "./static") + app := newFiberApp() s := &App{ questionsSvc: questionsSvc, diff --git a/internal/web_server/cors_test.go b/internal/web_server/cors_test.go new file mode 100644 index 00000000..24369c5a --- /dev/null +++ b/internal/web_server/cors_test.go @@ -0,0 +1,98 @@ +package httpserver + +import ( + "Rezina-Backend/internal/domain" + "Rezina-Backend/internal/web_server/handlers" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gofiber/fiber/v2" +) + +func TestCORSPreflightHeaderCasing(t *testing.T) { + for _, origin := range []string{"https://admin.rezina.yaltopia.com", "https://rezina.yaltopia.com"} { + for _, casing := range []struct { + name, origin, method, headers string + }{ + {"canonical", "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"}, + {"lowercase", "origin", "access-control-request-method", "access-control-request-headers"}, + {"mixed", "oRiGiN", "aCcEsS-CoNtRoL-ReQuEsT-MeThOd", "aCcEsS-CoNtRoL-ReQuEsT-HeAdErS"}, + } { + t.Run(origin+"/"+casing.name, func(t *testing.T) { + server := newFiberApp() + a := audienceTestApp(domain.UserStatusActive) + a.initAdminRoutes(server.Group("/api/v1/admin", apiAudience("admin")), &handlers.Handler{}) + request := httptest.NewRequest(http.MethodOptions, "/api/v1/admin/team/login", nil) + // Assign directly: Header.Set canonicalizes keys and would conceal the production bug. + request.Header[casing.origin] = []string{origin} + request.Header[casing.method] = []string{http.MethodPost} + request.Header[casing.headers] = []string{"content-type,authorization,accept"} + response, err := server.Test(request) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusNoContent { + t.Fatalf("status=%d want=204", response.StatusCode) + } + if got := response.Header.Get("Access-Control-Allow-Origin"); got != "*" { + t.Errorf("allow origin=%q want=*", got) + } + if got := response.Header.Get("Access-Control-Allow-Methods"); !strings.Contains(got, "POST") { + t.Errorf("POST missing from allowed methods: %q", got) + } + for _, header := range []string{"content-type", "authorization", "accept"} { + if got := strings.ToLower(response.Header.Get("Access-Control-Allow-Headers")); !strings.Contains(got, header) { + t.Errorf("%s missing from allowed headers: %q", header, got) + } + } + }) + } + } +} + +func TestCORSActualRequestHeaderCasing(t *testing.T) { + for _, casing := range []struct{ name, origin, authorization string }{ + {"canonical", "Origin", "Authorization"}, + {"lowercase", "origin", "authorization"}, + {"mixed", "oRiGiN", "aUtHoRiZaTiOn"}, + } { + for _, authenticated := range []bool{false, true} { + name := casing.name + "/unauthenticated" + if authenticated { + name = casing.name + "/authenticated" + } + t.Run(name, func(t *testing.T) { + server := newFiberApp() + a := audienceTestApp(domain.UserStatusActive) + server.Get("/api/v1/admin/courses", a.adminAuthMiddleware, func(c *fiber.Ctx) error { + c.Set("Content-Disposition", `attachment; filename="courses.csv"`) + return c.SendString("courses") + }) + request := httptest.NewRequest(http.MethodGet, "/api/v1/admin/courses", nil) + request.Header[casing.origin] = []string{"https://admin.rezina.yaltopia.com"} + wantStatus := http.StatusUnauthorized + if authenticated { + request.Header[casing.authorization] = []string{"Bearer " + audienceToken(t, a, domain.RoleAdmin)} + wantStatus = http.StatusOK + } + response, err := server.Test(request) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != wantStatus { + t.Errorf("status=%d want=%d", response.StatusCode, wantStatus) + } + if got := response.Header.Get("Access-Control-Allow-Origin"); got != "*" { + t.Errorf("allow origin=%q want=*", got) + } + if got := response.Header.Get("Access-Control-Expose-Headers"); got != "Content-Disposition" { + t.Errorf("exposed headers=%q want=Content-Disposition", got) + } + }) + } + } +}