1
0
Fork 0
mirror of https://github.com/portainer/portainer.git synced 2025-07-24 15:59:41 +02:00

fix(linters): add back removed linters and extend them to CE BE-11294

This commit is contained in:
andres-portainer 2024-10-10 12:06:20 -03:00
parent 2bd880ec29
commit 364e4f1b4e
55 changed files with 123 additions and 176 deletions

View file

@ -1,7 +1,6 @@
package backup
import (
"fmt"
"net/http"
"os"
"path/filepath"
@ -37,8 +36,7 @@ func (p *backupPayload) Validate(r *http.Request) error {
// @router /backup [post]
func (h *Handler) backup(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
var payload backupPayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil {
return httperror.BadRequest("Invalid request payload", err)
}
@ -48,7 +46,7 @@ func (h *Handler) backup(w http.ResponseWriter, r *http.Request) *httperror.Hand
}
defer os.RemoveAll(filepath.Dir(archivePath))
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fmt.Sprintf("portainer-backup_%s", filepath.Base(archivePath))))
w.Header().Set("Content-Disposition", "attachment; filename=portainer-backup_"+filepath.Base(archivePath))
http.ServeFile(w, r, archivePath)
return nil

View file

@ -2,7 +2,6 @@ package customtemplates
import (
"errors"
"fmt"
"net/http"
"os"
"regexp"
@ -52,15 +51,13 @@ func (handler *Handler) customTemplateCreate(w http.ResponseWriter, r *http.Requ
}
}
err = handler.DataStore.CustomTemplate().Create(customTemplate)
if err != nil {
if err := handler.DataStore.CustomTemplate().Create(customTemplate); err != nil {
return httperror.InternalServerError("Unable to create custom template", err)
}
resourceControl := authorization.NewPrivateResourceControl(strconv.Itoa(int(customTemplate.ID)), portainer.CustomTemplateResourceControl, tokenData.ID)
err = handler.DataStore.ResourceControl().Create(resourceControl)
if err != nil {
if err := handler.DataStore.ResourceControl().Create(resourceControl); err != nil {
return httperror.InternalServerError("Unable to persist resource control inside the database", err)
}
@ -155,8 +152,7 @@ func isValidNote(note string) bool {
// @router /custom_templates/create/string [post]
func (handler *Handler) createCustomTemplateFromFileContent(r *http.Request) (*portainer.CustomTemplate, error) {
var payload customTemplateFromFileContentPayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil {
return nil, err
}
@ -272,8 +268,7 @@ func (payload *customTemplateFromGitRepositoryPayload) Validate(r *http.Request)
// @router /custom_templates/create/repository [post]
func (handler *Handler) createCustomTemplateFromGitRepository(r *http.Request) (*portainer.CustomTemplate, error) {
var payload customTemplateFromGitRepositoryPayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil {
return nil, err
}
@ -423,12 +418,10 @@ func (payload *customTemplateFromFileUploadPayload) Validate(r *http.Request) er
varsString, _ := request.RetrieveMultiPartFormValue(r, "Variables", true)
if varsString != "" {
err = json.Unmarshal([]byte(varsString), &payload.Variables)
if err != nil {
if err := json.Unmarshal([]byte(varsString), &payload.Variables); err != nil {
return errors.New("Invalid variables. Ensure that the variables are valid JSON")
}
err = validateVariablesDefinitions(payload.Variables)
if err != nil {
if err := validateVariablesDefinitions(payload.Variables); err != nil {
return err
}
}
@ -462,8 +455,7 @@ func (payload *customTemplateFromFileUploadPayload) Validate(r *http.Request) er
// @router /custom_templates/create/file [post]
func (handler *Handler) createCustomTemplateFromFileUpload(r *http.Request) (*portainer.CustomTemplate, error) {
payload := &customTemplateFromFileUploadPayload{}
err := payload.Validate(r)
if err != nil {
if err := payload.Validate(r); err != nil {
return nil, err
}
@ -513,6 +505,5 @@ func deprecatedCustomTemplateCreateUrlParser(w http.ResponseWriter, r *http.Requ
return "", httperror.BadRequest("Invalid query parameter: method", err)
}
url := fmt.Sprintf("/custom_templates/create/%s", method)
return url, nil
return "/custom_templates/create/" + method, nil
}

View file

@ -1,7 +1,6 @@
package customtemplates
import (
"fmt"
"net/http"
"os"
"sync"
@ -80,8 +79,7 @@ func (handler *Handler) customTemplateGitFetch(w http.ResponseWriter, r *http.Re
if customTemplate.GitConfig.ConfigHash != commitHash {
customTemplate.GitConfig.ConfigHash = commitHash
err = handler.DataStore.CustomTemplate().Update(customTemplate.ID, customTemplate)
if err != nil {
if err := handler.DataStore.CustomTemplate().Update(customTemplate.ID, customTemplate); err != nil {
return httperror.InternalServerError("Unable to persist custom template changes inside the database", err)
}
}
@ -100,9 +98,8 @@ func backupCustomTemplate(projectPath string) (string, error) {
return "", err
}
backupPath := fmt.Sprintf("%s-backup", projectPath)
err = os.Rename(projectPath, backupPath)
if err != nil {
backupPath := projectPath + "-backup"
if err := os.Rename(projectPath, backupPath); err != nil {
return "", err
}
@ -110,8 +107,7 @@ func backupCustomTemplate(projectPath string) (string, error) {
}
func rollbackCustomTemplate(backupPath, projectPath string) error {
err := os.RemoveAll(projectPath)
if err != nil {
if err := os.RemoveAll(projectPath); err != nil {
return err
}

View file

@ -2,7 +2,6 @@ package edgejobs
import (
"errors"
"fmt"
"maps"
"net/http"
"strconv"
@ -300,5 +299,5 @@ func deprecatedEdgeJobCreateUrlParser(w http.ResponseWriter, r *http.Request) (s
return "", httperror.BadRequest("Invalid query parameter: method. Valid values are: file or string", err)
}
return fmt.Sprintf("/edge_jobs/create/%s", method), nil
return "/edge_jobs/create/" + method, nil
}

View file

@ -1,7 +1,6 @@
package edgestacks
import (
"fmt"
"net/http"
portainer "github.com/portainer/portainer/api"
@ -78,5 +77,5 @@ func deprecatedEdgeStackCreateUrlParser(w http.ResponseWriter, r *http.Request)
return "", httperror.BadRequest("Invalid query parameter: method. Valid values are: file or string", err)
}
return fmt.Sprintf("/edge_stacks/create/%s", method), nil
return "/edge_stacks/create/" + method, nil
}

View file

@ -133,7 +133,7 @@ func (handler *Handler) storeManifestFromGitRepository(tx dataservices.DataStore
return "", "", "", fmt.Errorf("unable to check for existence of non fitting environments: %w", err)
}
if hasWrongType {
return "", "", "", fmt.Errorf("edge stack with config do not match the environment type")
return "", "", "", errors.New("edge stack with config do not match the environment type")
}
projectPath = handler.FileService.GetEdgeStackProjectPath(stackFolder)

View file

@ -92,7 +92,7 @@ func (handler *Handler) storeFileContent(tx dataservices.DataStoreTx, stackFolde
return "", "", "", fmt.Errorf("unable to check for existence of non fitting environments: %w", err)
}
if hasWrongType {
return "", "", "", fmt.Errorf("edge stack with config do not match the environment type")
return "", "", "", errors.New("edge stack with config do not match the environment type")
}
if deploymentType == portainer.EdgeStackDeploymentCompose {
@ -107,7 +107,6 @@ func (handler *Handler) storeFileContent(tx dataservices.DataStoreTx, stackFolde
}
if deploymentType == portainer.EdgeStackDeploymentKubernetes {
manifestPath = filesystem.ManifestFileDefaultName
projectPath, err := handler.FileService.StoreEdgeStackFileFromBytes(stackFolder, manifestPath, fileContent)

View file

@ -207,7 +207,7 @@ func TestCreateWithInvalidPayload(t *testing.T) {
r := bytes.NewBuffer(jsonPayload)
// Create EdgeStack
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("/edge_stacks/create/%s", tc.Method), r)
req, err := http.NewRequest(http.MethodPost, "/edge_stacks/create/"+tc.Method, r)
if err != nil {
t.Fatal("request error:", err)
}

View file

@ -2,7 +2,6 @@ package endpoints
import (
"errors"
"fmt"
"net/http"
"slices"
"strconv"
@ -33,7 +32,7 @@ type endpointDeleteBatchPartialResponse struct {
func (payload *endpointDeleteBatchPayload) Validate(r *http.Request) error {
if payload == nil || len(payload.Endpoints) == 0 {
return fmt.Errorf("invalid request payload. You must provide a list of environments to delete")
return errors.New("invalid request payload. You must provide a list of environments to delete")
}
return nil

View file

@ -137,7 +137,7 @@ func getDockerHubLimits(httpClient *client.HTTPClient, token string) (*dockerhub
return nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Add("Authorization", "Bearer "+token)
resp, err := httpClient.Do(req)
if err != nil {

View file

@ -202,7 +202,7 @@ func setupEndpointListHandler(t *testing.T, endpoints []portainer.Endpoint) *Han
}
func buildEndpointListRequest(query string) *http.Request {
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/endpoints?%s", query), nil)
req := httptest.NewRequest(http.MethodGet, "/endpoints?"+query, nil)
ctx := security.StoreTokenData(req, &portainer.TokenData{ID: 1, Username: "admin", Role: 1})
req = req.WithContext(ctx)

View file

@ -557,7 +557,7 @@ func filter(endpoints []portainer.Endpoint, predicate func(endpoint portainer.En
}
func getArrayQueryParameter(r *http.Request, parameter string) []string {
list, exists := r.Form[fmt.Sprintf("%s[]", parameter)]
list, exists := r.Form[parameter+"[]"]
if !exists {
list = []string{}
}
@ -576,7 +576,6 @@ func getNumberArrayQueryParameter[T ~int](r *http.Request, parameter string) ([]
number, err := strconv.Atoi(item)
if err != nil {
return nil, errors.Wrapf(err, "Unable to parse parameter %s", parameter)
}
result = append(result, T(number))

View file

@ -1,7 +1,6 @@
package helm
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
@ -46,7 +45,7 @@ func Test_helmDelete(t *testing.T) {
h.helmPackageManager.Install(options)
t.Run("helmDelete succeeds with admin user", func(t *testing.T) {
req := httptest.NewRequest(http.MethodDelete, fmt.Sprintf("/1/kubernetes/helm/%s", options.Name), nil)
req := httptest.NewRequest(http.MethodDelete, "/1/kubernetes/helm/"+options.Name, nil)
ctx := security.StoreTokenData(req, &portainer.TokenData{ID: 1, Username: "admin", Role: 1})
req = req.WithContext(ctx)
testhelpers.AddTestSecurityCookie(req, "Bearer dummytoken")

View file

@ -1,7 +1,6 @@
package helm
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
@ -26,7 +25,7 @@ func Test_helmRepoSearch(t *testing.T) {
for _, repo := range repos {
t.Run(repo, func(t *testing.T) {
repoUrlEncoded := url.QueryEscape(repo)
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/templates/helm?repo=%s", repoUrlEncoded), nil)
req := httptest.NewRequest(http.MethodGet, "/templates/helm?repo="+repoUrlEncoded, nil)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)
@ -41,7 +40,7 @@ func Test_helmRepoSearch(t *testing.T) {
t.Run("fails on invalid URL", func(t *testing.T) {
repo := "abc.com"
repoUrlEncoded := url.QueryEscape(repo)
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/templates/helm?repo=%s", repoUrlEncoded), nil)
req := httptest.NewRequest(http.MethodGet, "/templates/helm?repo="+repoUrlEncoded, nil)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)

View file

@ -2,7 +2,6 @@ package openamt
import (
"errors"
"fmt"
"net/http"
portainer "github.com/portainer/portainer/api"
@ -37,7 +36,7 @@ func (handler *Handler) openAMTActivate(w http.ResponseWriter, r *http.Request)
} else if err != nil {
return httperror.InternalServerError("Unable to find an endpoint with the specified identifier inside the database", err)
} else if !endpointutils.IsAgentEndpoint(endpoint) {
errMsg := fmt.Sprintf("%s is not an agent environment", endpoint.Name)
errMsg := endpoint.Name + " is not an agent environment"
return httperror.BadRequest(errMsg, errors.New(errMsg))
}
@ -46,8 +45,7 @@ func (handler *Handler) openAMTActivate(w http.ResponseWriter, r *http.Request)
return httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
err = handler.activateDevice(endpoint, *settings)
if err != nil {
if err := handler.activateDevice(endpoint, *settings); err != nil {
return httperror.InternalServerError("Unable to activate device", err)
}
@ -63,8 +61,7 @@ func (handler *Handler) openAMTActivate(w http.ResponseWriter, r *http.Request)
}
endpoint.AMTDeviceGUID = hostInfo.UUID
err = handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint)
if err != nil {
if err := handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint); err != nil {
return httperror.InternalServerError("Unable to persist environment changes inside the database", err)
}

View file

@ -172,13 +172,12 @@ func (handler *Handler) buildCluster(r *http.Request, endpoint portainer.Endpoin
}
func buildClusterName(endpointName string) string {
return fmt.Sprintf("portainer-cluster-%s", endpointName)
return "portainer-cluster-" + endpointName
}
func buildContext(serviceAccountName string, endpoint portainer.Endpoint) clientV1.NamedContext {
contextName := fmt.Sprintf("portainer-ctx-%s", endpoint.Name)
return clientV1.NamedContext{
Name: contextName,
Name: "portainer-ctx-" + endpoint.Name,
Context: clientV1.Context{
AuthInfo: serviceAccountName,
Cluster: buildClusterName(endpoint.Name),

View file

@ -185,7 +185,7 @@ func (handler *Handler) createKubernetesNamespace(w http.ResponseWriter, r *http
}
log.Error().Err(err).Str("context", "CreateKubernetesNamespace").Str("namespace", namespaceName).Msg("Unable to create the namespace")
return httperror.InternalServerError(fmt.Sprintf("an error occurred during the CreateKubernetesNamespace operation, unable to create the namespace: %s", namespaceName), err)
return httperror.InternalServerError("an error occurred during the CreateKubernetesNamespace operation, unable to create the namespace: "+namespaceName, err)
}
return response.JSON(w, namespace)
@ -217,15 +217,14 @@ func (handler *Handler) deleteKubernetesNamespace(w http.ResponseWriter, r *http
}
for _, namespaceName := range *namespaceNames {
_, err := cli.DeleteNamespace(namespaceName)
if err != nil {
if _, err := cli.DeleteNamespace(namespaceName); err != nil {
if k8serrors.IsNotFound(err) {
log.Error().Err(err).Str("context", "DeleteKubernetesNamespace").Str("namespace", namespaceName).Msg("Unable to find the namespace")
return httperror.NotFound(fmt.Sprintf("an error occurred during the DeleteKubernetesNamespace operation for the namespace %s, unable to find the namespace. Error: ", namespaceName), err)
return httperror.NotFound("an error occurred during the DeleteKubernetesNamespace operation for the namespace "+namespaceName+", unable to find the namespace. Error: ", err)
}
log.Error().Err(err).Str("context", "DeleteKubernetesNamespace").Str("namespace", namespaceName).Msg("Unable to delete the namespace")
return httperror.InternalServerError(fmt.Sprintf("an error occurred during the DeleteKubernetesNamespace operation for the namespace %s, unable to delete the Kubernetes namespace. Error: ", namespaceName), err)
return httperror.InternalServerError("an error occurred during the DeleteKubernetesNamespace operation for the namespace "+namespaceName+", unable to delete the Kubernetes namespace. Error: ", err)
}
}
@ -262,8 +261,7 @@ func (payload deleteKubernetesNamespacePayload) Validate(r *http.Request) error
// @router /kubernetes/{id}/namespaces/{namespace} [put]
func (handler *Handler) updateKubernetesNamespace(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
payload := models.K8sNamespaceDetails{}
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil {
return httperror.BadRequest("an error occurred during the UpdateKubernetesNamespace operation, invalid request payload. Error: ", err)
}

View file

@ -1,7 +1,7 @@
package websocket
import (
"fmt"
"errors"
"io"
"net/http"
"strings"
@ -69,8 +69,7 @@ func (handler *Handler) websocketPodExec(w http.ResponseWriter, r *http.Request)
return httperror.InternalServerError("Unable to find the environment associated to the stack inside the database", err)
}
err = handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint)
if err != nil {
if err := handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint); err != nil {
return httperror.Forbidden("Permission denied to access environment", err)
}
@ -87,15 +86,13 @@ func (handler *Handler) websocketPodExec(w http.ResponseWriter, r *http.Request)
r.Header.Del("Origin")
if endpoint.Type == portainer.AgentOnKubernetesEnvironment {
err := handler.proxyAgentWebsocketRequest(w, r, params)
if err != nil {
if err := handler.proxyAgentWebsocketRequest(w, r, params); err != nil {
return httperror.InternalServerError("Unable to proxy websocket request to agent", err)
}
return nil
} else if endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment {
err := handler.proxyEdgeAgentWebsocketRequest(w, r, params)
if err != nil {
if err := handler.proxyEdgeAgentWebsocketRequest(w, r, params); err != nil {
return httperror.InternalServerError("Unable to proxy websocket request to Edge agent", err)
}
@ -187,7 +184,7 @@ func (handler *Handler) getToken(request *http.Request, endpoint *portainer.Endp
}
if token == "" {
return "", false, fmt.Errorf("can not get a valid user service account token")
return "", false, errors.New("can not get a valid user service account token")
}
return token, false, nil

View file

@ -2,7 +2,6 @@ package websocket
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
@ -34,7 +33,7 @@ func (handler *Handler) proxyEdgeAgentWebsocketRequest(w http.ResponseWriter, r
func (handler *Handler) proxyAgentWebsocketRequest(w http.ResponseWriter, r *http.Request, params *webSocketRequestParams) error {
endpointURL := params.endpoint.URL
if params.endpoint.Type == portainer.AgentOnKubernetesEnvironment {
endpointURL = fmt.Sprintf("http://%s", params.endpoint.URL)
endpointURL = "http://" + params.endpoint.URL
}
agentURL, err := url.Parse(endpointURL)

View file

@ -22,13 +22,11 @@ type K8sResourceQuota struct {
func (r *K8sNamespaceDetails) Validate(request *http.Request) error {
if r.ResourceQuota != nil && r.ResourceQuota.Enabled {
_, err := resource.ParseQuantity(r.ResourceQuota.Memory)
if err != nil {
if _, err := resource.ParseQuantity(r.ResourceQuota.Memory); err != nil {
return fmt.Errorf("error parsing memory quota value: %w", err)
}
_, err = resource.ParseQuantity(r.ResourceQuota.CPU)
if err != nil {
if _, err := resource.ParseQuantity(r.ResourceQuota.CPU); err != nil {
return fmt.Errorf("error parsing cpu quota value: %w", err)
}
}

View file

@ -2,7 +2,6 @@ package azure
import (
"errors"
"fmt"
"net/http"
portainer "github.com/portainer/portainer/api"
@ -40,7 +39,7 @@ func (transport *Transport) proxyContainerGroupPutRequest(request *http.Request)
Method: http.MethodGet,
URL: request.URL,
Header: http.Header{
"Authorization": []string{fmt.Sprintf("Bearer %s", tokenData.Token)},
"Authorization": []string{"Bearer " + tokenData.Token},
},
}

View file

@ -1,7 +1,7 @@
package azure
import (
"fmt"
"errors"
"net/http"
"github.com/portainer/portainer/api/http/proxy/factory/utils"
@ -41,7 +41,7 @@ func (transport *Transport) proxyContainerGroupsGetRequest(request *http.Request
utils.RewriteResponse(response, responseObject, http.StatusOK)
} else {
return nil, fmt.Errorf("The container groups response has no value property")
return nil, errors.New("The container groups response has no value property")
}
return response, nil

View file

@ -120,7 +120,7 @@ func (transport *baseTransport) prepareRoundTrip(request *http.Request) (string,
return "", err
}
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
request.Header.Set("Authorization", "Bearer "+token)
return token, nil
}

View file

@ -1,7 +1,6 @@
package security
import (
"fmt"
"net/http"
"strings"
"sync"
@ -426,7 +425,7 @@ func (bouncer *RequestBouncer) apiKeyLookup(r *http.Request) (*portainer.TokenDa
}
if _, _, err := bouncer.jwtService.GenerateToken(tokenData); err != nil {
log.Debug().Err(err).Msg("Failed to generate token")
return nil, fmt.Errorf("failed to generate token")
return nil, errors.New("failed to generate token")
}
if now := time.Now().UTC().Unix(); now-apiKey.LastUsed > 60 { // [seconds]