diff --git a/.flake8 b/.flake8 new file mode 100644 index 00000000..bdc1f5e3 --- /dev/null +++ b/.flake8 @@ -0,0 +1,2 @@ +[flake8] +exclude = examples diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 9d0cb12f..bf95618d 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -18,6 +18,11 @@ jobs: - name: Run tests run: go test ./pkg/... -cover -coverprofile=profile.cov + - name: Run Gosec Security Scanner + uses: securego/gosec@master + with: + args: ./... + - name: Report coverage uses: codacy/codacy-coverage-reporter-action@v1 with: diff --git a/pkg/backends/k8s.go b/pkg/backends/k8s.go index 0879991d..98a9cde6 100644 --- a/pkg/backends/k8s.go +++ b/pkg/backends/k8s.go @@ -66,7 +66,7 @@ func (k *KubeBackend) ListServices() ([]*types.Service, error) { services := []*types.Service{} for _, cm := range configmaps.Items { - service, err := getServiceFromConfigMap(&cm) + service, err := getServiceFromConfigMap(&cm) // #nosec G601 if err != nil { return nil, err } diff --git a/pkg/backends/knative.go b/pkg/backends/knative.go index 566352c4..3d08ba78 100644 --- a/pkg/backends/knative.go +++ b/pkg/backends/knative.go @@ -21,7 +21,6 @@ import ( "fmt" "log" "net/http" - "os" "strconv" "github.com/grycap/oscar/v3/pkg/imagepuller" @@ -33,8 +32,8 @@ import ( knclientset "knative.dev/serving/pkg/client/clientset/versioned" ) -// Custom logger -var knativeLogger = log.New(os.Stdout, "[KNATIVE] ", log.Flags()) +// Custom logger - uncomment if needed +// var knativeLogger = log.New(os.Stdout, "[KNATIVE] ", log.Flags()) // KnativeBackend struct to represent a Knative client type KnativeBackend struct { @@ -84,7 +83,7 @@ func (kn *KnativeBackend) ListServices() ([]*types.Service, error) { services := []*types.Service{} for _, cm := range configmaps.Items { - service, err := getServiceFromConfigMap(&cm) + service, err := getServiceFromConfigMap(&cm) // #nosec G601 if err != nil { return nil, err } @@ -129,7 +128,10 @@ func (kn *KnativeBackend) CreateService(service types.Service) error { //Create an expose service if service.Expose.APIPort != 0 { - types.CreateExpose(service, kn.kubeClientset, kn.config) + err = types.CreateExpose(service, kn.kubeClientset, kn.config) + if err != nil { + return err + } } //Create deaemonset to cache the service image on all the nodes if service.ImagePrefetch { diff --git a/pkg/backends/openfaas.go b/pkg/backends/openfaas.go index 5743e21a..54ede05d 100644 --- a/pkg/backends/openfaas.go +++ b/pkg/backends/openfaas.go @@ -92,7 +92,7 @@ func (of *OpenfaasBackend) ListServices() ([]*types.Service, error) { services := []*types.Service{} for _, cm := range configmaps.Items { - service, err := getServiceFromConfigMap(&cm) + service, err := getServiceFromConfigMap(&cm) // #nosec G601 if err != nil { return nil, err } diff --git a/pkg/handlers/create.go b/pkg/handlers/create.go index e749f223..7458a7d2 100644 --- a/pkg/handlers/create.go +++ b/pkg/handlers/create.go @@ -118,8 +118,14 @@ func MakeCreateHandler(cfg *types.Config, back types.ServerlessBackend) gin.Hand if len(uids) > 0 { for _, uid := range uids { sk, _ := auth.GenerateRandomKey(8) - minIOAdminClient.CreateMinIOUser(uid, sk) - mc.CreateSecretForOIDC(uid, sk) + cmuErr := minIOAdminClient.CreateMinIOUser(uid, sk) + if cmuErr != nil { + log.Printf("Error creating MinIO user for user %s: %v", uid, cmuErr) + } + csErr := mc.CreateSecretForOIDC(uid, sk) + if csErr != nil { + log.Printf("Error creating secret for user %s: %v", uid, csErr) + } } } @@ -171,7 +177,10 @@ func MakeCreateHandler(cfg *types.Config, back types.ServerlessBackend) gin.Hand // Register minio webhook and restart the server if err := registerMinIOWebhook(service.Name, service.Token, service.StorageProviders.MinIO[types.DefaultProvider], cfg); err != nil { - back.DeleteService(service) + derr := back.DeleteService(service) + if derr != nil { + log.Printf("Error deleting service: %v\n", derr) + } c.String(http.StatusInternalServerError, err.Error()) return } @@ -183,7 +192,10 @@ func MakeCreateHandler(cfg *types.Config, back types.ServerlessBackend) gin.Hand } else { c.String(http.StatusInternalServerError, err.Error()) } - back.DeleteService(service) + derr := back.DeleteService(service) + if derr != nil { + log.Printf("Error deleting service: %v\n", derr) + } return } @@ -361,7 +373,10 @@ func createBuckets(service *types.Service, cfg *types.Config, minIOAdminClient * } if !isAdminUser { - minIOAdminClient.CreateAddPolicy(b, service.AllowedUsers[i], false) + err = minIOAdminClient.CreateAddPolicy(b, service.AllowedUsers[i], false) + if err != nil { + return err + } } } } @@ -401,7 +416,10 @@ func createBuckets(service *types.Service, cfg *types.Config, minIOAdminClient * // Check if the provider identifier is defined in StorageProviders if !isStorageProviderDefined(provName, provID, service.StorageProviders) { // TODO fix - disableInputNotifications(s3Client, service.GetMinIOWebhookARN(), "") + dinErr := disableInputNotifications(s3Client, service.GetMinIOWebhookARN(), "") + if dinErr != nil { + log.Printf("Error disabling input notifications: %v\n", dinErr) + } return fmt.Errorf("the StorageProvider \"%s.%s\" is not defined", provName, provID) } @@ -448,7 +466,10 @@ func createBuckets(service *types.Service, cfg *types.Config, minIOAdminClient * Key: aws.String(folderKey), }) if err != nil { - disableInputNotifications(s3Client, service.GetMinIOWebhookARN(), splitPath[0]) + dinErr := disableInputNotifications(s3Client, service.GetMinIOWebhookARN(), splitPath[0]) + if dinErr != nil { + log.Printf("Error disabling input notifications: %v\n", dinErr) + } return fmt.Errorf("error creating folder \"%s\" in bucket \"%s\": %v", folderKey, splitPath[0], err) } } @@ -474,7 +495,10 @@ func createBuckets(service *types.Service, cfg *types.Config, minIOAdminClient * log.Printf("Error creating \"%s\" folder in Onedata. Error: %v\n", path, err) } else { // TODO fix - disableInputNotifications(s3Client, service.GetMinIOWebhookARN(), "") + dinErr := disableInputNotifications(s3Client, service.GetMinIOWebhookARN(), "") + if dinErr != nil { + log.Printf("Error disabling input notifications: %v\n", dinErr) + } return fmt.Errorf("error connecting to Onedata's Oneprovider \"%s\". Error: %v", service.StorageProviders.Onedata[provID].OneproviderHost, err) } } diff --git a/pkg/handlers/delete.go b/pkg/handlers/delete.go index 0dee6006..f9272ba6 100644 --- a/pkg/handlers/delete.go +++ b/pkg/handlers/delete.go @@ -76,8 +76,10 @@ func MakeDeleteHandler(cfg *types.Config, back types.ServerlessBackend) gin.Hand // Split buckets and folders from path bucket := strings.SplitN(path, "/", 2) var users []string - // Needed ? - minIOAdminClient.UpdateUsersInGroup(users, bucket[0], true) + err = minIOAdminClient.UpdateUsersInGroup(users, bucket[0], true) + if err != nil { + log.Printf("error updating MinIO users in group: %v", err) + } } // Remove the service's webhook in MinIO config and restart the server @@ -176,7 +178,10 @@ func deleteBuckets(service *types.Service, cfg *types.Config, minIOAdminClient * // Delete user's buckets if isolated spaces had been created if strings.ToUpper(service.IsolationLevel) == "USER" && len(service.BucketList) > 0 { // Delete all private buckets - deletePrivateBuckets(service, minIOAdminClient, s3Client) + err = deletePrivateBuckets(service, minIOAdminClient, s3Client) + if err != nil { + return fmt.Errorf("error while disable the input notification") + } } } @@ -193,7 +198,10 @@ func deleteBuckets(service *types.Service, cfg *types.Config, minIOAdminClient * // Check if the provider identifier is defined in StorageProviders if !isStorageProviderDefined(provName, provID, service.StorageProviders) { // TODO fix - disableInputNotifications(s3Client, service.GetMinIOWebhookARN(), "") + err := disableInputNotifications(s3Client, service.GetMinIOWebhookARN(), "") + if err != nil { + return fmt.Errorf("error while disable the input notification") + } return fmt.Errorf("the StorageProvider \"%s.%s\" is not defined", provName, provID) } diff --git a/pkg/handlers/job.go b/pkg/handlers/job.go index e1ebb847..977a1da7 100644 --- a/pkg/handlers/job.go +++ b/pkg/handlers/job.go @@ -157,7 +157,7 @@ func MakeJobHandler(cfg *types.Config, kubeClientset kubernetes.Interface, back c.Next() // Initialize event envVar and args var - event := v1.EnvVar{} + var event v1.EnvVar var args []string if cfg.InterLinkAvailable && service.InterLinkNodeName != "" { diff --git a/pkg/handlers/logs.go b/pkg/handlers/logs.go index c26087a7..318d9ea0 100644 --- a/pkg/handlers/logs.go +++ b/pkg/handlers/logs.go @@ -92,10 +92,10 @@ func MakeJobsInfoHandler(back types.ServerlessBackend, kubeClientset kubernetes. for _, contStatus := range pod.Status.ContainerStatuses { if contStatus.Name == types.ContainerName { if contStatus.State.Running != nil { - jobsInfo[jobName].StartTime = &contStatus.State.Running.StartedAt + jobsInfo[jobName].StartTime = &(contStatus.State.Running.StartedAt) } else if contStatus.State.Terminated != nil { - jobsInfo[jobName].StartTime = &contStatus.State.Terminated.StartedAt - jobsInfo[jobName].FinishTime = &contStatus.State.Terminated.FinishedAt + jobsInfo[jobName].StartTime = &(contStatus.State.Terminated.StartedAt) + jobsInfo[jobName].FinishTime = &(contStatus.State.Terminated.FinishedAt) } } } diff --git a/pkg/handlers/update.go b/pkg/handlers/update.go index 44afd541..3a0edef7 100644 --- a/pkg/handlers/update.go +++ b/pkg/handlers/update.go @@ -129,11 +129,16 @@ func MakeUpdateHandler(cfg *types.Config, back types.ServerlessBackend) gin.Hand return } - disableInputNotifications(s3Client, oldService.GetMinIOWebhookARN(), splitPath[0]) - + err = disableInputNotifications(s3Client, oldService.GetMinIOWebhookARN(), splitPath[0]) + if err != nil { + return + } // Register minio webhook and restart the server if err := registerMinIOWebhook(newService.Name, newService.Token, newService.StorageProviders.MinIO[types.DefaultProvider], cfg); err != nil { - back.UpdateService(*oldService) + uerr := back.UpdateService(*oldService) + if uerr != nil { + log.Println(uerr.Error()) + } c.String(http.StatusInternalServerError, err.Error()) return } @@ -152,7 +157,10 @@ func MakeUpdateHandler(cfg *types.Config, back types.ServerlessBackend) gin.Hand c.String(http.StatusInternalServerError, err.Error()) } // If updateBuckets fails restore the oldService - back.UpdateService(*oldService) + uerr := back.UpdateService(*oldService) + if uerr != nil { + log.Println(uerr.Error()) + } return } diff --git a/pkg/imagepuller/daemonset.go b/pkg/imagepuller/daemonset.go index 7d5a6f9f..22cc2167 100644 --- a/pkg/imagepuller/daemonset.go +++ b/pkg/imagepuller/daemonset.go @@ -21,9 +21,10 @@ package imagepuller import ( //"k8s.io/apimachinery/pkg/watch" "context" + "crypto/rand" "fmt" "log" - "math/rand" + "math/big" "os" "sync" "time" @@ -61,7 +62,11 @@ var stopper chan struct{} func CreateDaemonset(cfg *types.Config, service types.Service, kubeClientset kubernetes.Interface) error { DaemonSetLoggerInfo.Println("Creating daemonset for service:", service.Name) //Set needed variables - setWorkingNodes(kubeClientset) + err := setWorkingNodes(kubeClientset) + if err != nil { + DaemonSetLoggerInfo.Println(err) + return fmt.Errorf("failed to set working nodes: %s", err.Error()) + } podGroup = generatePodGroupName() daemonsetName = "image-puller-" + service.Name @@ -69,7 +74,7 @@ func CreateDaemonset(cfg *types.Config, service types.Service, kubeClientset kub daemon := getDaemonset(cfg, service) //Create daemonset - _, err := kubeClientset.AppsV1().DaemonSets(cfg.ServicesNamespace).Create(context.TODO(), daemon, metav1.CreateOptions{}) + _, err = kubeClientset.AppsV1().DaemonSets(cfg.ServicesNamespace).Create(context.TODO(), daemon, metav1.CreateOptions{}) if err != nil { DaemonSetLoggerInfo.Println(err) return fmt.Errorf("failed to create daemonset: %s", err.Error()) @@ -146,15 +151,19 @@ func watchPods(kubeClientset kubernetes.Interface, cfg *types.Config) { } //Add event handler that gets all the pods status - podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ + _, err := podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ UpdateFunc: handleUpdatePodEvent, }) + if err != nil { + DaemonSetLoggerInfo.Println(err) + log.Fatalf("Failed to add event handler: %s", err.Error()) + } <-stopper //Delete daemonset when all pods are in state "Running" DaemonSetLoggerInfo.Println("Deleting daemonset...") - err := kubeClientset.AppsV1().DaemonSets(cfg.ServicesNamespace).Delete(context.TODO(), daemonsetName, metav1.DeleteOptions{}) + err = kubeClientset.AppsV1().DaemonSets(cfg.ServicesNamespace).Delete(context.TODO(), daemonsetName, metav1.DeleteOptions{}) if err != nil { DaemonSetLoggerInfo.Println(err) log.Fatalf("Failed to delete daemonset: %s", err.Error()) @@ -191,7 +200,9 @@ func setWorkingNodes(kubeClientset kubernetes.Interface) error { func generatePodGroupName() string { b := make([]byte, lengthStr) for i := range b { - b[i] = letterBytes[rand.Intn(len(letterBytes))] + max := big.NewInt(int64(len(letterBytes))) + randomNumber, _ := rand.Int(rand.Reader, max) + b[i] = letterBytes[randomNumber.Int64()] } return "pod-group-" + string(b) } diff --git a/pkg/resourcemanager/delegate.go b/pkg/resourcemanager/delegate.go index dfa5a225..f1aa7a41 100644 --- a/pkg/resourcemanager/delegate.go +++ b/pkg/resourcemanager/delegate.go @@ -18,11 +18,12 @@ package resourcemanager import ( "bytes" + "crypto/rand" "crypto/tls" "encoding/json" "fmt" "log" - "math/rand" + "math/big" "net/http" "net/url" "path" @@ -129,6 +130,7 @@ func DelegateJob(service *types.Service, event string, logger *log.Logger) error req.Header.Add("Authorization", "Bearer "+strings.TrimSpace(token)) // Make HTTP client + // #nosec var transport http.RoundTripper = &http.Transport{ // Enable/disable SSL verification TLSClientConfig: &tls.Config{InsecureSkipVerify: !cluster.SSLVerify}, @@ -191,6 +193,7 @@ func DelegateJob(service *types.Service, event string, logger *log.Logger) error } // Make HTTP client + // #nosec var transport http.RoundTripper = &http.Transport{ // Enable/disable SSL verification TLSClientConfig: &tls.Config{InsecureSkipVerify: !replica.SSLVerify}, @@ -267,6 +270,7 @@ func updateServiceToken(replica types.Replica, cluster types.Cluster) (string, e req.SetBasicAuth(cluster.AuthUser, cluster.AuthPassword) // Make HTTP client + // #nosec var transport http.RoundTripper = &http.Transport{ // Enable/disable SSL verification TLSClientConfig: &tls.Config{InsecureSkipVerify: !cluster.SSLVerify}, @@ -342,6 +346,7 @@ func getClusterStatus(service *types.Service) { req.SetBasicAuth(cluster.AuthUser, cluster.AuthPassword) // Make HTTP client + // #nosec var transport http.RoundTripper = &http.Transport{ // Enable/disable SSL verification TLSClientConfig: &tls.Config{InsecureSkipVerify: !cluster.SSLVerify}, @@ -395,14 +400,16 @@ func getClusterStatus(service *types.Service) { if dist >= 0 { fmt.Println("Resources available in ClusterID", replica.ClusterID) if service.Delegation == "random" { - randPriority := rand.Intn(noDelegateCode) + max := big.NewInt(int64(noDelegateCode)) + randomNumber, _ := rand.Int(rand.Reader, max) + randPriority := randomNumber.Uint64() replica.Priority = uint(randPriority) fmt.Println("Priority ", replica.Priority, " with ", service.Delegation, " delegation") } else if service.Delegation == "load-based" { //Map the totalClusterCPU range to a smaller range (input range 0 to 32 cpu to output range 100 to 0 priority) totalClusterCPU := clusterStatus.CPUFreeTotal mappedCPUPriority := mapToRange(totalClusterCPU, 0, 32000, 100, 0) - replica.Priority = uint(mappedCPUPriority) + replica.Priority = uint(mappedCPUPriority) // #nosec G115 fmt.Println("Priority ", replica.Priority, " with ", service.Delegation, " delegation") } else if service.Delegation != "static" { replica.Priority = noDelegateCode diff --git a/pkg/types/expose.go b/pkg/types/expose.go index 09b758b4..4b7403b7 100644 --- a/pkg/types/expose.go +++ b/pkg/types/expose.go @@ -250,7 +250,7 @@ func getPodTemplateSpec(service Service, cfg *Config) v1.PodTemplateSpec { podSpec.Containers[i].Ports = []v1.ContainerPort{ { Name: podPortName, - ContainerPort: int32(service.Expose.APIPort), + ContainerPort: int32(service.Expose.APIPort), // #nosec G115 }, } podSpec.Containers[i].VolumeMounts[0].ReadOnly = false @@ -323,7 +323,10 @@ func updateDeployment(service Service, kubeClientset kubernetes.Interface, cfg * return err } - kubeClientset.AutoscalingV1().HorizontalPodAutoscalers(cfg.ServicesNamespace).Get(context.TODO(), getHPAName(service.Name), metav1.GetOptions{}) + _, err = kubeClientset.AutoscalingV1().HorizontalPodAutoscalers(cfg.ServicesNamespace).Get(context.TODO(), getHPAName(service.Name), metav1.GetOptions{}) + if err != nil { + return err + } hpa := getHortizontalAutoScaleSpec(service, cfg) _, err = kubeClientset.AutoscalingV1().HorizontalPodAutoscalers(cfg.ServicesNamespace).Update(context.TODO(), hpa, metav1.UpdateOptions{}) if err != nil { @@ -352,7 +355,7 @@ func getServiceSpec(service Service, cfg *Config) *v1.Service { Port: servicePortNumber, TargetPort: intstr.IntOrString{ Type: 0, - IntVal: int32(service.Expose.APIPort), + IntVal: int32(service.Expose.APIPort), // #nosec G115 }, } service_type := v1.ServiceType(typeClusterIP) @@ -420,7 +423,10 @@ func createIngress(service Service, kubeClientset kubernetes.Interface, cfg *Con return err } if service.Expose.SetAuth { - createSecret(service, kubeClientset, cfg) + cerr := createSecret(service, kubeClientset, cfg) + if cerr != nil { + return cerr + } } return nil } @@ -441,13 +447,22 @@ func updateIngress(service Service, kubeClientset kubernetes.Interface, cfg *Con secret := existsSecret(serviceName, kubeClientset, cfg) if secret { if service.Expose.SetAuth { - updateSecret(service, kubeClientset, cfg) + uerr := updateSecret(service, kubeClientset, cfg) + if uerr != nil { + return uerr + } } else { - deleteSecret(service.Name, kubeClientset, cfg) + derr := deleteSecret(service.Name, kubeClientset, cfg) + if derr != nil { + return derr + } } } else { if service.Expose.SetAuth { - createSecret(service, kubeClientset, cfg) + cerr := createSecret(service, kubeClientset, cfg) + if cerr != nil { + return cerr + } } } @@ -547,7 +562,10 @@ func deleteIngress(name string, kubeClientset kubernetes.Interface, cfg *Config) if err != nil { return err } - deleteSecret(name, kubeClientset, cfg) + errd := deleteSecret(name, kubeClientset, cfg) + if errd != nil { + return errd + } return nil } diff --git a/pkg/types/expose_test.go b/pkg/types/expose_test.go index 69bab5b3..09e2450a 100644 --- a/pkg/types/expose_test.go +++ b/pkg/types/expose_test.go @@ -286,6 +286,12 @@ func TestDeleteIngress(t *testing.T) { Namespace: "namespace", }, }, + &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "service-ing-auth-expose", + Namespace: "namespace", + }, + }, } kubeClientset := testclient.NewSimpleClientset(K8sObjects...) diff --git a/pkg/types/storage.go b/pkg/types/storage.go index f2671da9..87de81b1 100644 --- a/pkg/types/storage.go +++ b/pkg/types/storage.go @@ -121,6 +121,7 @@ func (minIOProvider MinIOProvider) GetS3Client() *s3.S3 { // Disable tls verification in client transport if Verify == false if !minIOProvider.Verify { + // #nosec tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } diff --git a/pkg/utils/auth/auth.go b/pkg/utils/auth/auth.go index 57795a48..cea4ad6b 100644 --- a/pkg/utils/auth/auth.go +++ b/pkg/utils/auth/auth.go @@ -50,8 +50,8 @@ func CustomAuth(cfg *types.Config, kubeClientset kubernetes.Interface) gin.Handl // Slice to add default user to all users group on MinIO var oscarUser = []string{"console"} - minIOAdminClient.CreateAllUsersGroup() - minIOAdminClient.UpdateUsersInGroup(oscarUser, "all_users_group", false) + minIOAdminClient.CreateAllUsersGroup() // #nosec G104 + minIOAdminClient.UpdateUsersInGroup(oscarUser, "all_users_group", false) // #nosec G104 oidcHandler := getOIDCMiddleware(kubeClientset, minIOAdminClient, cfg.OIDCIssuer, cfg.OIDCSubject, cfg.OIDCGroups, nil) return func(c *gin.Context) { @@ -110,11 +110,11 @@ func GetLoggerMiddleware() gin.HandlerFunc { func GetUIDFromContext(c *gin.Context) (string, error) { uidOrigin, uidExists := c.Get("uidOrigin") if !uidExists { - return "", fmt.Errorf("Missing EGI user uid") + return "", fmt.Errorf("missing EGI user uid") } uid, uidParsed := uidOrigin.(string) if !uidParsed { - return "", fmt.Errorf("Error parsing uid origin: %v", uidParsed) + return "", fmt.Errorf("error parsing uid origin: %v", uidParsed) } return uid, nil } @@ -122,11 +122,11 @@ func GetUIDFromContext(c *gin.Context) (string, error) { func GetMultitenancyConfigFromContext(c *gin.Context) (*MultitenancyConfig, error) { mcUntyped, mcExists := c.Get("multitenancyConfig") if !mcExists { - return nil, fmt.Errorf("Missing multitenancy config") + return nil, fmt.Errorf("missing multitenancy config") } mc, mcParsed := mcUntyped.(*MultitenancyConfig) if !mcParsed { - return nil, fmt.Errorf("Error parsing multitenancy config") + return nil, fmt.Errorf("error parsing multitenancy config") } return mc, nil } diff --git a/pkg/utils/auth/oidc.go b/pkg/utils/auth/oidc.go index 40dbd54d..b7ad6c30 100644 --- a/pkg/utils/auth/oidc.go +++ b/pkg/utils/auth/oidc.go @@ -159,7 +159,10 @@ func (om *oidcManager) GetUserInfo(rawToken string) (*userInfo, error) { var claims struct { EdupersonEntitlement []string `json:"eduperson_entitlement"` } - ui.Claims(&claims) + cerr := ui.Claims(&claims) + if cerr != nil { + return nil, err + } // Create "userInfo" struct and add the groups return &userInfo{ diff --git a/pkg/utils/minio.go b/pkg/utils/minio.go index 0b2bb7fb..fa5a261e 100644 --- a/pkg/utils/minio.go +++ b/pkg/utils/minio.go @@ -21,10 +21,8 @@ import ( "crypto/tls" "encoding/json" "fmt" - "log" "net/http" "net/url" - "os" "time" "github.com/aws/aws-sdk-go/aws" @@ -36,7 +34,8 @@ import ( const ALL_USERS_GROUP = "all_users_group" -var minioLogger = log.New(os.Stdout, "[MINIO] ", log.Flags()) +// Custom logger - uncomment if needed +// var minioLogger = log.New(os.Stdout, "[MINIO] ", log.Flags()) // MinIOAdminClient struct to represent a MinIO Admin client to configure webhook notifications type MinIOAdminClient struct { @@ -82,6 +81,7 @@ func MakeMinIOAdminClient(cfg *types.Config) (*MinIOAdminClient, error) { // Disable tls verification in client transport if verify == false if !cfg.MinIOProvider.Verify { + // #nosec tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } @@ -307,8 +307,10 @@ func (minIOAdminClient *MinIOAdminClient) CreateAddPolicy(bucketName string, pol policy = []byte(p) } else { actualPolicy := &Policy{} - json.Unmarshal(policyInfo.Policy, actualPolicy) - + err := json.Unmarshal(policyInfo.Policy, actualPolicy) + if err != nil { + return fmt.Errorf("error unmarshal, the policy is not in correct format") + } // Add new resource and create policy actualPolicy.Statement = []Statement{ { @@ -350,7 +352,10 @@ func createPolicy(adminClient *madmin.AdminClient, bucketName string, allUsers b } actualPolicy := &Policy{} - json.Unmarshal(policyInfo.Policy, actualPolicy) + jsonErr = json.Unmarshal(policyInfo.Policy, actualPolicy) + if jsonErr != nil { + return jsonErr + } // Add new resource and create policy actualPolicy.Statement[0].Resource = append(actualPolicy.Statement[0].Resource, rs) @@ -399,7 +404,10 @@ func (minIOAdminClient *MinIOAdminClient) RemoveFromPolicy(bucketName string, po return fmt.Errorf("policy '%s' does not exist: %v", policyName, errInfo) } actualPolicy := &Policy{} - json.Unmarshal(policyInfo.Policy, actualPolicy) + err := json.Unmarshal(policyInfo.Policy, actualPolicy) + if err != nil { + return fmt.Errorf("error unmarshal, the policy is not in correct format") + } if len(actualPolicy.Statement[0].Resource) == 1 { if err := minIOAdminClient.adminClient.RemoveCannedPolicy(context.TODO(), policyName); err != nil { return fmt.Errorf("error removing canned policy: %v", err) @@ -419,7 +427,7 @@ func (minIOAdminClient *MinIOAdminClient) RemoveFromPolicy(bucketName string, po return jsonErr } - err := minIOAdminClient.adminClient.AddCannedPolicy(context.TODO(), policyName, []byte(policy)) + err = minIOAdminClient.adminClient.AddCannedPolicy(context.TODO(), policyName, []byte(policy)) if err != nil { return fmt.Errorf("error creating MinIO policy for user %s: %v", policyName, err) } diff --git a/pkg/utils/token.go b/pkg/utils/token.go index a58d914a..57f480be 100644 --- a/pkg/utils/token.go +++ b/pkg/utils/token.go @@ -24,7 +24,7 @@ import ( // GenerateToken generates a random hexadecimal token func GenerateToken() string { b := make([]byte, 32) - rand.Read(b) + rand.Read(b) // #nosec G104 return hex.EncodeToString(b) }