package middleware import ( "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" ) func TestNoStoreSensitiveResponses(t *testing.T) { gin.SetMode(gin.TestMode) tests := []struct { name string path string fullPath string wantNoCache bool }{ { name: "auth login path", path: "/api/v1/auth/login", fullPath: "/api/v1/auth/login", wantNoCache: true, }, { name: "auth register path", path: "/api/v1/auth/register", fullPath: "/api/v1/auth/register", wantNoCache: true, }, { name: "non-auth path", path: "/api/v1/users", fullPath: "/api/v1/users", wantNoCache: false, }, { name: "empty fullPath uses request path", path: "/api/v1/auth/refresh", fullPath: "", wantNoCache: true, }, { name: "subpath of auth", path: "/api/v1/auth/oauth/callback", fullPath: "/api/v1/auth/oauth/callback", wantNoCache: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { router := gin.New() router.Use(NoStoreSensitiveResponses()) router.GET(tt.path, func(c *gin.Context) { c.String(200, "OK") }) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", tt.path, nil) router.ServeHTTP(w, req) if tt.wantNoCache { assert.Equal(t, "no-store, no-cache, must-revalidate, max-age=0", w.Header().Get("Cache-Control")) assert.Equal(t, "no-cache", w.Header().Get("Pragma")) assert.Equal(t, "0", w.Header().Get("Expires")) assert.Equal(t, "no-store", w.Header().Get("Surrogate-Control")) } else { assert.Empty(t, w.Header().Get("Cache-Control")) assert.Empty(t, w.Header().Get("Pragma")) } }) } } func TestShouldDisableCaching(t *testing.T) { tests := []struct { name string routePath string requestPath string expected bool }{ { name: "auth prefix match", routePath: "/api/v1/auth/login", requestPath: "/api/v1/auth/login", expected: true, }, { name: "no auth prefix", routePath: "/api/v1/users", requestPath: "/api/v1/users", expected: false, }, { name: "empty routePath uses requestPath", routePath: "", requestPath: "/api/v1/auth/logout", expected: true, }, { name: "trimmed spaces", routePath: " /api/v1/auth/login ", requestPath: "/api/v1/auth/login", expected: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := shouldDisableCaching(tt.routePath, tt.requestPath) assert.Equal(t, tt.expected, result) }) } }