diff --git a/api/http/handler/endpoints/endpoint_create_global_key.go b/api/http/handler/endpoints/endpoint_create_global_key.go index c37590960..d6ce39a01 100644 --- a/api/http/handler/endpoints/endpoint_create_global_key.go +++ b/api/http/handler/endpoints/endpoint_create_global_key.go @@ -1,6 +1,7 @@ package endpoints import ( + "errors" "net/http" httperror "github.com/portainer/libhttp/error" @@ -21,6 +22,9 @@ type endpointCreateGlobalKeyResponse struct { // @router /endpoints/global-key [post] func (handler *Handler) endpointCreateGlobalKey(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { edgeID := r.Header.Get(portainer.PortainerAgentEdgeIDHeader) + if edgeID == "" { + return httperror.BadRequest("Invalid Edge ID", errors.New("the Edge ID cannot be empty")) + } // Search for existing endpoints for the given edgeID diff --git a/api/http/handler/endpoints/endpoint_create_global_key_test.go b/api/http/handler/endpoints/endpoint_create_global_key_test.go new file mode 100644 index 000000000..0be6bf2ff --- /dev/null +++ b/api/http/handler/endpoints/endpoint_create_global_key_test.go @@ -0,0 +1,30 @@ +package endpoints + +import ( + "net/http" + "net/http/httptest" + "testing" + + portainer "github.com/portainer/portainer/api" + helper "github.com/portainer/portainer/api/internal/testhelpers" +) + +func TestEmptyGlobalKey(t *testing.T) { + handler := NewHandler( + helper.NewTestRequestBouncer(), + ) + + req, err := http.NewRequest(http.MethodPost, "https://portainer.io:9443/endpoints/global-key", nil) + if err != nil { + t.Fatal("request error:", err) + } + req.Header.Set(portainer.PortainerAgentEdgeIDHeader, "") + + rec := httptest.NewRecorder() + + handler.ServeHTTP(rec, req) + + if rec.Code != http.StatusBadRequest { + t.Fatal("expected a 400 response, found:", rec.Code) + } +}