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

pull/6693/merge
andres-portainer 1 month ago
parent 2bd880ec29
commit 364e4f1b4e

@ -9,6 +9,9 @@ linters:
- gosimple - gosimple
- govet - govet
- errorlint - errorlint
- copyloopvar
- intrange
- perfsprint
linters-settings: linters-settings:
depguard: depguard:

@ -15,7 +15,7 @@ import (
// abosolutePath should be an absolute path to a directory. // abosolutePath should be an absolute path to a directory.
// Archive name will be <directoryName>.tar.gz and will be placed next to the directory. // Archive name will be <directoryName>.tar.gz and will be placed next to the directory.
func TarGzDir(absolutePath string) (string, error) { func TarGzDir(absolutePath string) (string, error) {
targzPath := filepath.Join(absolutePath, fmt.Sprintf("%s.tar.gz", filepath.Base(absolutePath))) targzPath := filepath.Join(absolutePath, filepath.Base(absolutePath)+".tar.gz")
outFile, err := os.Create(targzPath) outFile, err := os.Create(targzPath)
if err != nil { if err != nil {
return "", err return "", err

@ -1,7 +1,6 @@
package archive package archive
import ( import (
"fmt"
"os" "os"
"os/exec" "os/exec"
"path" "path"
@ -24,7 +23,7 @@ func listFiles(dir string) []string {
return items return items
} }
func Test_shouldCreateArhive(t *testing.T) { func Test_shouldCreateArchive(t *testing.T) {
tmpdir := t.TempDir() tmpdir := t.TempDir()
content := []byte("content") content := []byte("content")
os.WriteFile(path.Join(tmpdir, "outer"), content, 0600) os.WriteFile(path.Join(tmpdir, "outer"), content, 0600)
@ -34,12 +33,11 @@ func Test_shouldCreateArhive(t *testing.T) {
gzPath, err := TarGzDir(tmpdir) gzPath, err := TarGzDir(tmpdir)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, filepath.Join(tmpdir, fmt.Sprintf("%s.tar.gz", filepath.Base(tmpdir))), gzPath) assert.Equal(t, filepath.Join(tmpdir, filepath.Base(tmpdir)+".tar.gz"), gzPath)
extractionDir := t.TempDir() extractionDir := t.TempDir()
cmd := exec.Command("tar", "-xzf", gzPath, "-C", extractionDir) cmd := exec.Command("tar", "-xzf", gzPath, "-C", extractionDir)
err = cmd.Run() if err := cmd.Run(); err != nil {
if err != nil {
t.Fatal("Failed to extract archive: ", err) t.Fatal("Failed to extract archive: ", err)
} }
extractedFiles := listFiles(extractionDir) extractedFiles := listFiles(extractionDir)
@ -56,7 +54,7 @@ func Test_shouldCreateArhive(t *testing.T) {
wasExtracted("dir/.dotfile") wasExtracted("dir/.dotfile")
} }
func Test_shouldCreateArhiveXXXXX(t *testing.T) { func Test_shouldCreateArchive2(t *testing.T) {
tmpdir := t.TempDir() tmpdir := t.TempDir()
content := []byte("content") content := []byte("content")
os.WriteFile(path.Join(tmpdir, "outer"), content, 0600) os.WriteFile(path.Join(tmpdir, "outer"), content, 0600)
@ -66,12 +64,11 @@ func Test_shouldCreateArhiveXXXXX(t *testing.T) {
gzPath, err := TarGzDir(tmpdir) gzPath, err := TarGzDir(tmpdir)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, filepath.Join(tmpdir, fmt.Sprintf("%s.tar.gz", filepath.Base(tmpdir))), gzPath) assert.Equal(t, filepath.Join(tmpdir, filepath.Base(tmpdir)+".tar.gz"), gzPath)
extractionDir := t.TempDir() extractionDir := t.TempDir()
r, _ := os.Open(gzPath) r, _ := os.Open(gzPath)
ExtractTarGz(r, extractionDir) if err := ExtractTarGz(r, extractionDir); err != nil {
if err != nil {
t.Fatal("Failed to extract archive: ", err) t.Fatal("Failed to extract archive: ", err)
} }
extractedFiles := listFiles(extractionDir) extractedFiles := listFiles(extractionDir)

@ -3,7 +3,7 @@ package ecr
import ( import (
"context" "context"
"encoding/base64" "encoding/base64"
"fmt" "errors"
"strings" "strings"
"time" "time"
) )
@ -15,7 +15,7 @@ func (s *Service) GetEncodedAuthorizationToken() (token *string, expiry *time.Ti
} }
if len(getAuthorizationTokenOutput.AuthorizationData) == 0 { if len(getAuthorizationTokenOutput.AuthorizationData) == 0 {
err = fmt.Errorf("AuthorizationData is empty") err = errors.New("AuthorizationData is empty")
return return
} }
@ -50,7 +50,7 @@ func (s *Service) ParseAuthorizationToken(token string) (username string, passwo
splitToken := strings.Split(token, ":") splitToken := strings.Split(token, ":")
if len(splitToken) < 2 { if len(splitToken) < 2 {
err = fmt.Errorf("invalid ECR authorization token") err = errors.New("invalid ECR authorization token")
return return
} }

@ -94,7 +94,7 @@ func encrypt(path string, passphrase string) (string, error) {
} }
defer in.Close() defer in.Close()
outFileName := fmt.Sprintf("%s.encrypted", path) outFileName := path + ".encrypted"
out, err := os.Create(outFileName) out, err := os.Create(outFileName)
if err != nil { if err != nil {
return "", err return "", err

@ -31,8 +31,7 @@ const (
// AesEncrypt reads from input, encrypts with AES-256 and writes to output. passphrase is used to generate an encryption key // AesEncrypt reads from input, encrypts with AES-256 and writes to output. passphrase is used to generate an encryption key
func AesEncrypt(input io.Reader, output io.Writer, passphrase []byte) error { func AesEncrypt(input io.Reader, output io.Writer, passphrase []byte) error {
err := aesEncryptGCM(input, output, passphrase) if err := aesEncryptGCM(input, output, passphrase); err != nil {
if err != nil {
return fmt.Errorf("error encrypting file: %w", err) return fmt.Errorf("error encrypting file: %w", err)
} }
@ -142,7 +141,7 @@ func aesDecryptGCM(input io.Reader, passphrase []byte) (io.Reader, error) {
} }
if string(header) != aesGcmHeader { if string(header) != aesGcmHeader {
return nil, fmt.Errorf("invalid header") return nil, errors.New("invalid header")
} }
// Read salt // Read salt
@ -194,8 +193,7 @@ func aesDecryptGCM(input io.Reader, passphrase []byte) (io.Reader, error) {
return nil, err return nil, err
} }
_, err = buf.Write(plaintext) if _, err := buf.Write(plaintext); err != nil {
if err != nil {
return nil, err return nil, err
} }

@ -21,8 +21,7 @@ type Service struct {
// NewService creates a new instance of a service. // NewService creates a new instance of a service.
func NewService(connection portainer.Connection) (*Service, error) { func NewService(connection portainer.Connection) (*Service, error) {
err := connection.SetServiceName(BucketName) if err := connection.SetServiceName(BucketName); err != nil {
if err != nil {
return nil, err return nil, err
} }
@ -62,7 +61,7 @@ func (service *Service) GetAPIKeysByUserID(userID portainer.UserID) ([]portainer
// Note: there is a 1-to-1 mapping of api-key and digest // Note: there is a 1-to-1 mapping of api-key and digest
func (service *Service) GetAPIKeyByDigest(digest string) (*portainer.APIKey, error) { func (service *Service) GetAPIKeyByDigest(digest string) (*portainer.APIKey, error) {
var k *portainer.APIKey var k *portainer.APIKey
stop := fmt.Errorf("ok") stop := errors.New("ok")
err := service.Connection.GetAll( err := service.Connection.GetAll(
BucketName, BucketName,
&portainer.APIKey{}, &portainer.APIKey{},

@ -48,7 +48,7 @@ func (service *Service) Tx(tx portainer.Transaction) ServiceTx {
// if no ResourceControl was found. // if no ResourceControl was found.
func (service *Service) ResourceControlByResourceIDAndType(resourceID string, resourceType portainer.ResourceControlType) (*portainer.ResourceControl, error) { func (service *Service) ResourceControlByResourceIDAndType(resourceID string, resourceType portainer.ResourceControlType) (*portainer.ResourceControl, error) {
var resourceControl *portainer.ResourceControl var resourceControl *portainer.ResourceControl
stop := fmt.Errorf("ok") stop := errors.New("ok")
err := service.Connection.GetAll( err := service.Connection.GetAll(
BucketName, BucketName,
&portainer.ResourceControl{}, &portainer.ResourceControl{},

@ -19,7 +19,7 @@ type ServiceTx struct {
// if no ResourceControl was found. // if no ResourceControl was found.
func (service ServiceTx) ResourceControlByResourceIDAndType(resourceID string, resourceType portainer.ResourceControlType) (*portainer.ResourceControl, error) { func (service ServiceTx) ResourceControlByResourceIDAndType(resourceID string, resourceType portainer.ResourceControlType) (*portainer.ResourceControl, error) {
var resourceControl *portainer.ResourceControl var resourceControl *portainer.ResourceControl
stop := fmt.Errorf("ok") stop := errors.New("ok")
err := service.Tx.GetAll( err := service.Tx.GetAll(
BucketName, BucketName,
&portainer.ResourceControl{}, &portainer.ResourceControl{},

@ -1,7 +1,6 @@
package datastore package datastore
import ( import (
"fmt"
"testing" "testing"
portainer "github.com/portainer/portainer/api" portainer "github.com/portainer/portainer/api"
@ -33,7 +32,7 @@ func TestStoreCreation(t *testing.T) {
func TestBackup(t *testing.T) { func TestBackup(t *testing.T) {
_, store := MustNewTestStore(t, true, true) _, store := MustNewTestStore(t, true, true)
backupFileName := store.backupFilename() backupFileName := store.backupFilename()
t.Run(fmt.Sprintf("Backup should create %s", backupFileName), func(t *testing.T) { t.Run("Backup should create "+backupFileName, func(t *testing.T) {
v := models.Version{ v := models.Version{
Edition: int(portainer.PortainerCE), Edition: int(portainer.PortainerCE),
SchemaVersion: portainer.APIVersion, SchemaVersion: portainer.APIVersion,

@ -142,23 +142,23 @@ func (i *Image) hubLink() (string, error) {
prefix = "_" prefix = "_"
path = strings.Replace(i.Path, "library/", "", 1) path = strings.Replace(i.Path, "library/", "", 1)
} }
return fmt.Sprintf("https://hub.docker.com/%s/%s", prefix, path), nil return "https://hub.docker.com/" + prefix + "/" + path, nil
case "docker.bintray.io", "jfrog-docker-reg2.bintray.io": case "docker.bintray.io", "jfrog-docker-reg2.bintray.io":
return fmt.Sprintf("https://bintray.com/jfrog/reg2/%s", strings.ReplaceAll(i.Path, "/", "%3A")), nil return "https://bintray.com/jfrog/reg2/" + strings.ReplaceAll(i.Path, "/", "%3A"), nil
case "docker.pkg.github.com": case "docker.pkg.github.com":
return fmt.Sprintf("https://github.com/%s/packages", filepath.ToSlash(filepath.Dir(i.Path))), nil return "https://github.com/" + filepath.ToSlash(filepath.Dir(i.Path)) + "/packages", nil
case "gcr.io": case "gcr.io":
return fmt.Sprintf("https://%s/%s", i.Domain, i.Path), nil return "https://" + i.Domain + "/" + i.Path, nil
case "ghcr.io": case "ghcr.io":
ref := strings.Split(i.Path, "/") ref := strings.Split(i.Path, "/")
ghUser, ghPackage := ref[0], ref[1] ghUser, ghPackage := ref[0], ref[1]
return fmt.Sprintf("https://github.com/users/%s/packages/container/package/%s", ghUser, ghPackage), nil return "https://github.com/users/" + ghUser + "/packages/container/package/" + ghPackage, nil
case "quay.io": case "quay.io":
return fmt.Sprintf("https://quay.io/repository/%s", i.Path), nil return "https://quay.io/repository/" + i.Path, nil
case "registry.access.redhat.com": case "registry.access.redhat.com":
return fmt.Sprintf("https://access.redhat.com/containers/#/registry.access.redhat.com/%s", i.Path), nil return "https://access.redhat.com/containers/#/registry.access.redhat.com/" + i.Path, nil
case "registry.gitlab.com": case "registry.gitlab.com":
return fmt.Sprintf("https://gitlab.com/%s/container_registry", i.Path), nil return "https://gitlab.com/" + i.Path + "/container_registry", nil
default: default:
return "", nil return "", nil
} }

@ -1,7 +1,6 @@
package images package images
import ( import (
"fmt"
"strings" "strings"
"github.com/containers/image/v5/docker" "github.com/containers/image/v5/docker"
@ -10,7 +9,7 @@ import (
func ParseReference(imageStr string) (types.ImageReference, error) { func ParseReference(imageStr string) (types.ImageReference, error) {
if !strings.HasPrefix(imageStr, "//") { if !strings.HasPrefix(imageStr, "//") {
imageStr = fmt.Sprintf("//%s", imageStr) imageStr = "//" + imageStr
} }
return docker.ParseReference(imageStr) return docker.ParseReference(imageStr)
} }

@ -2,7 +2,6 @@ package exec
import ( import (
"context" "context"
"fmt"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@ -60,8 +59,7 @@ func Test_UpAndDown(t *testing.T) {
ctx := context.TODO() ctx := context.TODO()
err = w.Up(ctx, stack, endpoint, portainer.ComposeUpOptions{}) if err := w.Up(ctx, stack, endpoint, portainer.ComposeUpOptions{}); err != nil {
if err != nil {
t.Fatalf("Error calling docker-compose up: %s", err) t.Fatalf("Error calling docker-compose up: %s", err)
} }
@ -69,8 +67,7 @@ func Test_UpAndDown(t *testing.T) {
t.Fatal("container should exist") t.Fatal("container should exist")
} }
err = w.Down(ctx, stack, endpoint) if err := w.Down(ctx, stack, endpoint); err != nil {
if err != nil {
t.Fatalf("Error calling docker-compose down: %s", err) t.Fatalf("Error calling docker-compose down: %s", err)
} }
@ -80,7 +77,7 @@ func Test_UpAndDown(t *testing.T) {
} }
func containerExists(containerName string) bool { func containerExists(containerName string) bool {
cmd := exec.Command("docker", "ps", "-a", "-f", fmt.Sprintf("name=%s", containerName)) cmd := exec.Command("docker", "ps", "-a", "-f", "name="+containerName)
out, err := cmd.Output() out, err := cmd.Output()
if err != nil { if err != nil {

@ -71,7 +71,7 @@ func (deployer *KubernetesDeployer) getToken(userID portainer.UserID, endpoint *
} }
if token == "" { if token == "" {
return "", fmt.Errorf("can not get a valid user service account token") return "", errors.New("can not get a valid user service account token")
} }
return token, nil return token, nil

@ -8,6 +8,7 @@ import (
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
portainer "github.com/portainer/portainer/api" portainer "github.com/portainer/portainer/api"
@ -357,7 +358,7 @@ func (service *Service) RollbackStackFile(stackIdentifier, fileName string) erro
stackStorePath := JoinPaths(ComposeStorePath, stackIdentifier) stackStorePath := JoinPaths(ComposeStorePath, stackIdentifier)
composeFilePath := JoinPaths(stackStorePath, fileName) composeFilePath := JoinPaths(stackStorePath, fileName)
path := service.wrapFileStore(composeFilePath) path := service.wrapFileStore(composeFilePath)
backupPath := fmt.Sprintf("%s.bak", path) backupPath := path + ".bak"
exists, err := service.FileExists(backupPath) exists, err := service.FileExists(backupPath)
if err != nil { if err != nil {
@ -381,12 +382,12 @@ func (service *Service) RollbackStackFile(stackIdentifier, fileName string) erro
func (service *Service) RollbackStackFileByVersion(stackIdentifier string, version int, fileName string) error { func (service *Service) RollbackStackFileByVersion(stackIdentifier string, version int, fileName string) error {
versionStr := "" versionStr := ""
if version != 0 { if version != 0 {
versionStr = fmt.Sprintf("v%d", version) versionStr = "v" + strconv.Itoa(version)
} }
stackStorePath := JoinPaths(ComposeStorePath, stackIdentifier, versionStr) stackStorePath := JoinPaths(ComposeStorePath, stackIdentifier, versionStr)
composeFilePath := JoinPaths(stackStorePath, fileName) composeFilePath := JoinPaths(stackStorePath, fileName)
path := service.wrapFileStore(composeFilePath) path := service.wrapFileStore(composeFilePath)
backupPath := fmt.Sprintf("%s.bak", path) backupPath := path + ".bak"
exists, err := service.FileExists(backupPath) exists, err := service.FileExists(backupPath)
if err != nil { if err != nil {
@ -671,7 +672,7 @@ func (service *Service) createFileInStore(filePath string, r io.Reader) error {
// createBackupFileInStore makes a copy in the file store. // createBackupFileInStore makes a copy in the file store.
func (service *Service) createBackupFileInStore(filePath string) error { func (service *Service) createBackupFileInStore(filePath string) error {
path := service.wrapFileStore(filePath) path := service.wrapFileStore(filePath)
backupPath := fmt.Sprintf("%s.bak", path) backupPath := path + ".bak"
return service.Copy(path, backupPath, true) return service.Copy(path, backupPath, true)
} }
@ -679,7 +680,7 @@ func (service *Service) createBackupFileInStore(filePath string) error {
// removeBackupFileInStore removes the copy in the file store. // removeBackupFileInStore removes the copy in the file store.
func (service *Service) removeBackupFileInStore(filePath string) error { func (service *Service) removeBackupFileInStore(filePath string) error {
path := service.wrapFileStore(filePath) path := service.wrapFileStore(filePath)
backupPath := fmt.Sprintf("%s.bak", path) backupPath := path + ".bak"
exists, err := service.FileExists(backupPath) exists, err := service.FileExists(backupPath)
if err != nil { if err != nil {
@ -799,7 +800,7 @@ func (service *Service) StoreEdgeJobTaskLogFileFromBytes(edgeJobID, taskID strin
return err return err
} }
filePath := JoinPaths(edgeJobStorePath, fmt.Sprintf("logs_%s", taskID)) filePath := JoinPaths(edgeJobStorePath, "logs_"+taskID)
r := bytes.NewReader(data) r := bytes.NewReader(data)
return service.createFileInStore(filePath, r) return service.createFileInStore(filePath, r)
} }
@ -990,7 +991,7 @@ func MoveDirectory(originalPath, newPath string, overwriteTargetPath bool) error
if alreadyExists { if alreadyExists {
if !overwriteTargetPath { if !overwriteTargetPath {
return fmt.Errorf("Target path already exists") return errors.New("Target path already exists")
} }
if err = os.RemoveAll(newPath); err != nil { if err = os.RemoveAll(newPath); err != nil {

@ -51,7 +51,7 @@ func FilterDirForEntryFile(dirEntries []DirEntry, entryFile string) []DirEntry {
// FilterDirForCompatibility returns the content of the entry file if agent version is less than 2.19.0 // FilterDirForCompatibility returns the content of the entry file if agent version is less than 2.19.0
func FilterDirForCompatibility(dirEntries []DirEntry, entryFilePath, agentVersion string) (string, error) { func FilterDirForCompatibility(dirEntries []DirEntry, entryFilePath, agentVersion string) (string, error) {
if semver.Compare(fmt.Sprintf("v%s", agentVersion), "v2.19.0") == -1 { if semver.Compare("v"+agentVersion, "v2.19.0") == -1 {
for _, dirEntry := range dirEntries { for _, dirEntry := range dirEntries {
if dirEntry.IsFile { if dirEntry.IsFile {
if dirEntry.Name == entryFilePath { if dirEntry.Name == entryFilePath {

@ -116,7 +116,7 @@ func shouldIncludeFile(dirEntry DirEntry, deviceName, configPath string) bool {
filterEqual := filepath.Join(configPath, deviceName) filterEqual := filepath.Join(configPath, deviceName)
// example: A/B/C/<deviceName>/ // example: A/B/C/<deviceName>/
filterPrefix := fmt.Sprintf("%s.", filterEqual) filterPrefix := filterEqual + "."
// include file entries: A/B/C/<deviceName> or A/B/C/<deviceName>.* // include file entries: A/B/C/<deviceName> or A/B/C/<deviceName>.*
return dirEntry.Name == filterEqual || strings.HasPrefix(dirEntry.Name, filterPrefix) return dirEntry.Name == filterEqual || strings.HasPrefix(dirEntry.Name, filterPrefix)

@ -1,12 +1,11 @@
package git package git
import ( import (
"fmt"
"github.com/pkg/errors"
portainer "github.com/portainer/portainer/api" portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/filesystem" "github.com/portainer/portainer/api/filesystem"
gittypes "github.com/portainer/portainer/api/git/types" gittypes "github.com/portainer/portainer/api/git/types"
"github.com/pkg/errors"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
@ -25,32 +24,28 @@ type CloneOptions struct {
} }
func CloneWithBackup(gitService portainer.GitService, fileService portainer.FileService, options CloneOptions) (clean func(), err error) { func CloneWithBackup(gitService portainer.GitService, fileService portainer.FileService, options CloneOptions) (clean func(), err error) {
backupProjectPath := fmt.Sprintf("%s-old", options.ProjectPath) backupProjectPath := options.ProjectPath + "-old"
cleanUp := false cleanUp := false
cleanFn := func() { cleanFn := func() {
if !cleanUp { if !cleanUp {
return return
} }
err = fileService.RemoveDirectory(backupProjectPath) if err := fileService.RemoveDirectory(backupProjectPath); err != nil {
if err != nil {
log.Warn().Err(err).Msg("unable to remove git repository directory") log.Warn().Err(err).Msg("unable to remove git repository directory")
} }
} }
err = filesystem.MoveDirectory(options.ProjectPath, backupProjectPath, true) if err := filesystem.MoveDirectory(options.ProjectPath, backupProjectPath, true); err != nil {
if err != nil {
return cleanFn, errors.WithMessage(err, "Unable to move git repository directory") return cleanFn, errors.WithMessage(err, "Unable to move git repository directory")
} }
cleanUp = true cleanUp = true
err = gitService.CloneRepository(options.ProjectPath, options.URL, options.ReferenceName, options.Username, options.Password, options.TLSSkipVerify) if err := gitService.CloneRepository(options.ProjectPath, options.URL, options.ReferenceName, options.Username, options.Password, options.TLSSkipVerify); err != nil {
if err != nil {
cleanUp = false cleanUp = false
restoreError := filesystem.MoveDirectory(backupProjectPath, options.ProjectPath, false) if err := filesystem.MoveDirectory(backupProjectPath, options.ProjectPath, false); err != nil {
if restoreError != nil { log.Warn().Err(err).Msg("failed restoring backup folder")
log.Warn().Err(restoreError).Msg("failed restoring backup folder")
} }
if errors.Is(err, gittypes.ErrAuthenticationFailure) { if errors.Is(err, gittypes.ErrAuthenticationFailure) {

@ -123,7 +123,7 @@ func (service *Service) getCIRACertificate(configuration portainer.OpenAMTConfig
if err != nil { if err != nil {
return "", err return "", err
} }
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", configuration.MPSToken)) req.Header.Set("Authorization", "Bearer "+configuration.MPSToken)
response, err := service.httpsClient.Do(req) response, err := service.httpsClient.Do(req)
if err != nil { if err != nil {

@ -97,7 +97,7 @@ func (service *Service) executeSaveRequest(method string, url string, token stri
return nil, err return nil, err
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) req.Header.Set("Authorization", "Bearer "+token)
response, err := service.httpsClient.Do(req) response, err := service.httpsClient.Do(req)
if err != nil { if err != nil {
@ -128,7 +128,7 @@ func (service *Service) executeGetRequest(url string, token string) ([]byte, err
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) req.Header.Set("Authorization", "Bearer "+token)
response, err := service.httpsClient.Do(req) response, err := service.httpsClient.Do(req)
if err != nil { if err != nil {

@ -1,7 +1,6 @@
package backup package backup
import ( import (
"fmt"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@ -37,8 +36,7 @@ func (p *backupPayload) Validate(r *http.Request) error {
// @router /backup [post] // @router /backup [post]
func (h *Handler) backup(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { func (h *Handler) backup(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
var payload backupPayload var payload backupPayload
err := request.DecodeAndValidateJSONPayload(r, &payload) if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil {
if err != nil {
return httperror.BadRequest("Invalid request payload", err) 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)) 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) http.ServeFile(w, r, archivePath)
return nil return nil

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

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

@ -2,7 +2,6 @@ package edgejobs
import ( import (
"errors" "errors"
"fmt"
"maps" "maps"
"net/http" "net/http"
"strconv" "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 "", 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
} }

@ -1,7 +1,6 @@
package edgestacks package edgestacks
import ( import (
"fmt"
"net/http" "net/http"
portainer "github.com/portainer/portainer/api" 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 "", 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
} }

@ -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) return "", "", "", fmt.Errorf("unable to check for existence of non fitting environments: %w", err)
} }
if hasWrongType { 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) projectPath = handler.FileService.GetEdgeStackProjectPath(stackFolder)

@ -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) return "", "", "", fmt.Errorf("unable to check for existence of non fitting environments: %w", err)
} }
if hasWrongType { 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 { if deploymentType == portainer.EdgeStackDeploymentCompose {
@ -107,7 +107,6 @@ func (handler *Handler) storeFileContent(tx dataservices.DataStoreTx, stackFolde
} }
if deploymentType == portainer.EdgeStackDeploymentKubernetes { if deploymentType == portainer.EdgeStackDeploymentKubernetes {
manifestPath = filesystem.ManifestFileDefaultName manifestPath = filesystem.ManifestFileDefaultName
projectPath, err := handler.FileService.StoreEdgeStackFileFromBytes(stackFolder, manifestPath, fileContent) projectPath, err := handler.FileService.StoreEdgeStackFileFromBytes(stackFolder, manifestPath, fileContent)

@ -207,7 +207,7 @@ func TestCreateWithInvalidPayload(t *testing.T) {
r := bytes.NewBuffer(jsonPayload) r := bytes.NewBuffer(jsonPayload)
// Create EdgeStack // 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 { if err != nil {
t.Fatal("request error:", err) t.Fatal("request error:", err)
} }

@ -2,7 +2,6 @@ package endpoints
import ( import (
"errors" "errors"
"fmt"
"net/http" "net/http"
"slices" "slices"
"strconv" "strconv"
@ -33,7 +32,7 @@ type endpointDeleteBatchPartialResponse struct {
func (payload *endpointDeleteBatchPayload) Validate(r *http.Request) error { func (payload *endpointDeleteBatchPayload) Validate(r *http.Request) error {
if payload == nil || len(payload.Endpoints) == 0 { 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 return nil

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

@ -202,7 +202,7 @@ func setupEndpointListHandler(t *testing.T, endpoints []portainer.Endpoint) *Han
} }
func buildEndpointListRequest(query string) *http.Request { 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}) ctx := security.StoreTokenData(req, &portainer.TokenData{ID: 1, Username: "admin", Role: 1})
req = req.WithContext(ctx) req = req.WithContext(ctx)

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

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

@ -1,7 +1,6 @@
package helm package helm
import ( import (
"fmt"
"io" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -26,7 +25,7 @@ func Test_helmRepoSearch(t *testing.T) {
for _, repo := range repos { for _, repo := range repos {
t.Run(repo, func(t *testing.T) { t.Run(repo, func(t *testing.T) {
repoUrlEncoded := url.QueryEscape(repo) 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() rr := httptest.NewRecorder()
h.ServeHTTP(rr, req) h.ServeHTTP(rr, req)
@ -41,7 +40,7 @@ func Test_helmRepoSearch(t *testing.T) {
t.Run("fails on invalid URL", func(t *testing.T) { t.Run("fails on invalid URL", func(t *testing.T) {
repo := "abc.com" repo := "abc.com"
repoUrlEncoded := url.QueryEscape(repo) 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() rr := httptest.NewRecorder()
h.ServeHTTP(rr, req) h.ServeHTTP(rr, req)

@ -2,7 +2,6 @@ package openamt
import ( import (
"errors" "errors"
"fmt"
"net/http" "net/http"
portainer "github.com/portainer/portainer/api" portainer "github.com/portainer/portainer/api"
@ -37,7 +36,7 @@ func (handler *Handler) openAMTActivate(w http.ResponseWriter, r *http.Request)
} else if err != nil { } else if err != nil {
return httperror.InternalServerError("Unable to find an endpoint with the specified identifier inside the database", err) return httperror.InternalServerError("Unable to find an endpoint with the specified identifier inside the database", err)
} else if !endpointutils.IsAgentEndpoint(endpoint) { } 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)) 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) return httperror.InternalServerError("Unable to retrieve settings from the database", err)
} }
err = handler.activateDevice(endpoint, *settings) if err := handler.activateDevice(endpoint, *settings); err != nil {
if err != nil {
return httperror.InternalServerError("Unable to activate device", err) 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 endpoint.AMTDeviceGUID = hostInfo.UUID
err = handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint) if err := handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint); err != nil {
if err != nil {
return httperror.InternalServerError("Unable to persist environment changes inside the database", err) return httperror.InternalServerError("Unable to persist environment changes inside the database", err)
} }

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

@ -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") 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) return response.JSON(w, namespace)
@ -217,15 +217,14 @@ func (handler *Handler) deleteKubernetesNamespace(w http.ResponseWriter, r *http
} }
for _, namespaceName := range *namespaceNames { for _, namespaceName := range *namespaceNames {
_, err := cli.DeleteNamespace(namespaceName) if _, err := cli.DeleteNamespace(namespaceName); err != nil {
if err != nil {
if k8serrors.IsNotFound(err) { if k8serrors.IsNotFound(err) {
log.Error().Err(err).Str("context", "DeleteKubernetesNamespace").Str("namespace", namespaceName).Msg("Unable to find the namespace") 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") 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] // @router /kubernetes/{id}/namespaces/{namespace} [put]
func (handler *Handler) updateKubernetesNamespace(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { func (handler *Handler) updateKubernetesNamespace(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
payload := models.K8sNamespaceDetails{} payload := models.K8sNamespaceDetails{}
err := request.DecodeAndValidateJSONPayload(r, &payload) if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil {
if err != nil {
return httperror.BadRequest("an error occurred during the UpdateKubernetesNamespace operation, invalid request payload. Error: ", err) return httperror.BadRequest("an error occurred during the UpdateKubernetesNamespace operation, invalid request payload. Error: ", err)
} }

@ -1,7 +1,7 @@
package websocket package websocket
import ( import (
"fmt" "errors"
"io" "io"
"net/http" "net/http"
"strings" "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) return httperror.InternalServerError("Unable to find the environment associated to the stack inside the database", err)
} }
err = handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint) if err := handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint); err != nil {
if err != nil {
return httperror.Forbidden("Permission denied to access environment", err) 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") r.Header.Del("Origin")
if endpoint.Type == portainer.AgentOnKubernetesEnvironment { if endpoint.Type == portainer.AgentOnKubernetesEnvironment {
err := handler.proxyAgentWebsocketRequest(w, r, params) if err := handler.proxyAgentWebsocketRequest(w, r, params); err != nil {
if err != nil {
return httperror.InternalServerError("Unable to proxy websocket request to agent", err) return httperror.InternalServerError("Unable to proxy websocket request to agent", err)
} }
return nil return nil
} else if endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment { } else if endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment {
err := handler.proxyEdgeAgentWebsocketRequest(w, r, params) if err := handler.proxyEdgeAgentWebsocketRequest(w, r, params); err != nil {
if err != nil {
return httperror.InternalServerError("Unable to proxy websocket request to Edge agent", err) 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 == "" { 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 return token, false, nil

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

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

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

@ -1,7 +1,7 @@
package azure package azure
import ( import (
"fmt" "errors"
"net/http" "net/http"
"github.com/portainer/portainer/api/http/proxy/factory/utils" "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) utils.RewriteResponse(response, responseObject, http.StatusOK)
} else { } 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 return response, nil

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

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

@ -1,7 +1,7 @@
package endpointutils package endpointutils
import ( import (
"fmt" "errors"
"strings" "strings"
"time" "time"
@ -171,7 +171,7 @@ func storageDetect(endpoint *portainer.Endpoint, endpointService dataservices.En
} else if len(storage) == 0 { } else if len(storage) == 0 {
log.Info().Err(err).Msg("zero storage classes found: they may be still building, retrying in 30 seconds") log.Info().Err(err).Msg("zero storage classes found: they may be still building, retrying in 30 seconds")
return fmt.Errorf("zero storage classes found: they may be still building, retrying in 30 seconds") return errors.New("zero storage classes found: they may be still building, retrying in 30 seconds")
} }
endpoint.Kubernetes.Configuration.StorageClasses = storage endpoint.Kubernetes.Configuration.StorageClasses = storage

@ -1,7 +1,7 @@
package access package access
import ( import (
"fmt" "errors"
portainer "github.com/portainer/portainer/api" portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/dataservices" "github.com/portainer/portainer/api/dataservices"
@ -52,7 +52,7 @@ func GetAccessibleRegistry(
} }
if !hasPermission { if !hasPermission {
err = fmt.Errorf("user does not has permission to get the registry") err = errors.New("user does not has permission to get the registry")
return nil, err return nil, err
} }

@ -2,7 +2,6 @@ package cli
import ( import (
"context" "context"
"fmt"
models "github.com/portainer/portainer/api/http/models/kubernetes" models "github.com/portainer/portainer/api/http/models/kubernetes"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@ -28,7 +27,7 @@ func (kcl *KubeClient) GetApplications(namespace, nodeName string, withDependenc
func (kcl *KubeClient) fetchApplications(namespace, nodeName string, withDependencies bool) ([]models.K8sApplication, error) { func (kcl *KubeClient) fetchApplications(namespace, nodeName string, withDependencies bool) ([]models.K8sApplication, error) {
podListOptions := metav1.ListOptions{} podListOptions := metav1.ListOptions{}
if nodeName != "" { if nodeName != "" {
podListOptions.FieldSelector = fmt.Sprintf("spec.nodeName=%s", nodeName) podListOptions.FieldSelector = "spec.nodeName=" + nodeName
} }
if !withDependencies { if !withDependencies {
// TODO: make sure not to fetch services in fetchAllApplicationsListResources from this call // TODO: make sure not to fetch services in fetchAllApplicationsListResources from this call
@ -59,7 +58,7 @@ func (kcl *KubeClient) fetchApplicationsForNonAdmin(namespace, nodeName string,
podListOptions := metav1.ListOptions{} podListOptions := metav1.ListOptions{}
if nodeName != "" { if nodeName != "" {
podListOptions.FieldSelector = fmt.Sprintf("spec.nodeName=%s", nodeName) podListOptions.FieldSelector = "spec.nodeName=" + nodeName
} }
if !withDependencies { if !withDependencies {
@ -125,7 +124,7 @@ func (kcl *KubeClient) GetApplicationsResource(namespace, node string) (models.K
resource := models.K8sApplicationResource{} resource := models.K8sApplicationResource{}
podListOptions := metav1.ListOptions{} podListOptions := metav1.ListOptions{}
if node != "" { if node != "" {
podListOptions.FieldSelector = fmt.Sprintf("spec.nodeName=%s", node) podListOptions.FieldSelector = "spec.nodeName=" + node
} }
pods, err := kcl.cli.CoreV1().Pods(namespace).List(context.Background(), podListOptions) pods, err := kcl.cli.CoreV1().Pods(namespace).List(context.Background(), podListOptions)

@ -273,7 +273,7 @@ func (factory *ClientFactory) buildEdgeConfig(endpoint *portainer.Endpoint) (*re
func (factory *ClientFactory) CreateRemoteMetricsClient(endpoint *portainer.Endpoint) (*metricsv.Clientset, error) { func (factory *ClientFactory) CreateRemoteMetricsClient(endpoint *portainer.Endpoint) (*metricsv.Clientset, error) {
config, err := factory.CreateConfig(endpoint) config, err := factory.CreateConfig(endpoint)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create metrics KubeConfig") return nil, errors.New("failed to create metrics KubeConfig")
} }
return metricsv.NewForConfig(config) return metricsv.NewForConfig(config)
} }

@ -2,7 +2,7 @@ package cli
import ( import (
"context" "context"
"fmt" "errors"
models "github.com/portainer/portainer/api/http/models/kubernetes" models "github.com/portainer/portainer/api/http/models/kubernetes"
rbacv1 "k8s.io/api/rbac/v1" rbacv1 "k8s.io/api/rbac/v1"
@ -16,7 +16,7 @@ func (kcl *KubeClient) GetClusterRoles() ([]models.K8sClusterRole, error) {
return kcl.fetchClusterRoles() return kcl.fetchClusterRoles()
} }
return []models.K8sClusterRole{}, fmt.Errorf("non-admin users are not allowed to access cluster roles") return []models.K8sClusterRole{}, errors.New("non-admin users are not allowed to access cluster roles")
} }
// fetchClusterRoles returns a list of all Roles in the specified namespace. // fetchClusterRoles returns a list of all Roles in the specified namespace.

@ -2,7 +2,7 @@ package cli
import ( import (
"context" "context"
"fmt" "errors"
models "github.com/portainer/portainer/api/http/models/kubernetes" models "github.com/portainer/portainer/api/http/models/kubernetes"
rbacv1 "k8s.io/api/rbac/v1" rbacv1 "k8s.io/api/rbac/v1"
@ -16,7 +16,7 @@ func (kcl *KubeClient) GetClusterRoleBindings() ([]models.K8sClusterRoleBinding,
return kcl.fetchClusterRoleBindings() return kcl.fetchClusterRoleBindings()
} }
return []models.K8sClusterRoleBinding{}, fmt.Errorf("non-admin users are not allowed to access cluster role bindings") return []models.K8sClusterRoleBinding{}, errors.New("non-admin users are not allowed to access cluster role bindings")
} }
// fetchClusterRoleBindings returns a list of all cluster roles in the cluster. // fetchClusterRoleBindings returns a list of all cluster roles in the cluster.

@ -3,7 +3,6 @@ package scheduler
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"sync/atomic" "sync/atomic"
"testing" "testing"
"time" "time"
@ -59,7 +58,7 @@ func Test_JobShouldStop_UponPermError(t *testing.T) {
s.StartJobEvery(jobInterval, func() error { s.StartJobEvery(jobInterval, func() error {
acc++ acc++
close(ch) close(ch)
return NewPermanentError(fmt.Errorf("failed")) return NewPermanentError(errors.New("failed"))
}) })
<-time.After(3 * jobInterval) <-time.After(3 * jobInterval)
@ -76,7 +75,7 @@ func Test_JobShouldNotStop_UponError(t *testing.T) {
s.StartJobEvery(jobInterval, func() error { s.StartJobEvery(jobInterval, func() error {
if acc.Add(1) == 2 { if acc.Add(1) == 2 {
close(ch) close(ch)
return NewPermanentError(fmt.Errorf("failed")) return NewPermanentError(errors.New("failed"))
} }
return errors.New("non-permanent error") return errors.New("non-permanent error")

@ -4,7 +4,6 @@ package binary
// The functionality does not rely on the implementation of `HelmPackageManager` // The functionality does not rely on the implementation of `HelmPackageManager`
import ( import (
"fmt"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
@ -72,7 +71,7 @@ func (hbpm *helmBinaryPackageManager) SearchRepo(searchRepoOpts options.SearchRe
url, err := url.ParseRequestURI(searchRepoOpts.Repo) url, err := url.ParseRequestURI(searchRepoOpts.Repo)
if err != nil { if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("invalid helm chart URL: %s", searchRepoOpts.Repo)) return nil, errors.Wrap(err, "invalid helm chart URL: "+searchRepoOpts.Repo)
} }
url.Path = path.Join(url.Path, "index.yaml") url.Path = path.Join(url.Path, "index.yaml")

@ -2,7 +2,6 @@ package compose_test
import ( import (
"context" "context"
"fmt"
"log" "log"
"os" "os"
"os/exec" "os/exec"
@ -94,7 +93,7 @@ func createFile(dir, fileName, content string) (string, error) {
} }
func containerExists(containerName string) bool { func containerExists(containerName string) bool {
cmd := exec.Command("docker", "ps", "-a", "-f", fmt.Sprintf("name=%s", containerName)) cmd := exec.Command("docker", "ps", "-a", "-f", "name="+containerName)
out, err := cmd.Output() out, err := cmd.Output()
if err != nil { if err != nil {

@ -2,7 +2,6 @@ package composeplugin
import ( import (
"context" "context"
"fmt"
"log" "log"
"os" "os"
"os/exec" "os/exec"
@ -134,7 +133,7 @@ func createFile(dir, fileName, content string) (string, error) {
} }
func containerExists(containerName string) bool { func containerExists(containerName string) bool {
cmd := exec.Command("docker", "ps", "-a", "-f", fmt.Sprintf("name=%s", containerName)) cmd := exec.Command("docker", "ps", "-a", "-f", "name="+containerName)
out, err := cmd.Output() out, err := cmd.Output()
if err != nil { if err != nil {

@ -124,7 +124,7 @@ func (wrapper *PluginWrapper) WaitForStatus(ctx context.Context, name string, st
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
waitResult.ErrorMsg = fmt.Sprintf("failed to wait for status: %s", ctx.Err().Error()) waitResult.ErrorMsg = "failed to wait for status: " + ctx.Err().Error()
waitResultCh <- waitResult waitResultCh <- waitResult
default: default:
} }

Loading…
Cancel
Save