package httpapi import ( "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" ) func TestLoopbackAdminOnlyAllowsLoopbackAddresses(t *testing.T) { for _, remoteAddress := range []string{ "127.0.0.1:12345", "[::1]:12345", } { t.Run(remoteAddress, func(t *testing.T) { router := gin.New() router.Use(requestIDMiddleware(), loopbackAdminOnly()) router.GET("/tasks", func(ctx *gin.Context) { ctx.Status(http.StatusNoContent) }) request := httptest.NewRequest(http.MethodGet, "/tasks", nil) request.RemoteAddr = remoteAddress response := httptest.NewRecorder() router.ServeHTTP(response, request) if response.Code != http.StatusNoContent { t.Fatalf("status = %d", response.Code) } }) } } func TestLoopbackAdminOnlyRejectsRemoteOrMalformedAddresses(t *testing.T) { for _, remoteAddress := range []string{ "192.0.2.1:12345", "not-an-address", } { t.Run(remoteAddress, func(t *testing.T) { router := gin.New() router.Use(requestIDMiddleware(), loopbackAdminOnly()) router.GET("/tasks", func(ctx *gin.Context) { ctx.Status(http.StatusNoContent) }) request := httptest.NewRequest(http.MethodGet, "/tasks", nil) request.RemoteAddr = remoteAddress response := httptest.NewRecorder() router.ServeHTTP(response, request) if response.Code != http.StatusForbidden { t.Fatalf("status = %d", response.Code) } assertErrorCode(t, response, "ADMIN_SESSION_REQUIRED") if response.Header().Get("Cache-Control") != "no-store" { t.Fatalf( "Cache-Control = %q", response.Header().Get("Cache-Control"), ) } }) } }