Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixing gosec alerts #12

Merged
merged 1 commit into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions pkg/apis/enricher/framework/java/quarkus_detector.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ package enricher
import (
"context"
"errors"
"io/ioutil"
"os"
"path/filepath"

Expand Down Expand Up @@ -135,7 +134,7 @@ func getServerPortsFromQuarkusPropertiesFile(file string) ([]int, error) {
}

func getServerPortsFromQuarkusApplicationYamlFile(file string) ([]int, error) {
yamlFile, err := ioutil.ReadFile(file)
yamlFile, err := os.ReadFile(filepath.Clean(file))
if err != nil {
return []int{}, err
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/apis/enricher/framework/java/spring_detector.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ package enricher
import (
"context"
"errors"
"io/ioutil"
"os"
"path/filepath"

"github.com/devfile/alizer/pkg/apis/model"
Expand Down Expand Up @@ -122,7 +122,7 @@ func getPortFromMap(props map[string]string, key string) int {
}

func getServerPortsFromYamlFile(file string) ([]int, error) {
yamlFile, err := ioutil.ReadFile(file)
yamlFile, err := os.ReadFile(filepath.Clean(file))
if err != nil {
return []int{}, err
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/apis/enricher/go_enricher.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ package enricher
import (
"context"
"errors"
"io/ioutil"

framework "github.com/devfile/alizer/pkg/apis/enricher/framework/go"
"github.com/devfile/alizer/pkg/apis/model"
"github.com/devfile/alizer/pkg/utils"
"golang.org/x/mod/modfile"
"os"
"path/filepath"
)

type GoEnricher struct{}
Expand Down Expand Up @@ -108,7 +108,7 @@ func (g GoEnricher) IsConfigValidForComponentDetection(language string, config s
}

func getGoModFile(filePath string) (*modfile.File, error) {
b, err := ioutil.ReadFile(filePath)
b, err := os.ReadFile(filepath.Clean(filePath))
if err != nil {
return nil, errors.New("unable to read go.mod file")
}
Expand Down
12 changes: 6 additions & 6 deletions pkg/utils/detector.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"io"
"os"
"path/filepath"
"regexp"
Expand Down Expand Up @@ -83,7 +83,7 @@ func IsPathOfWantedFile(path string, wantedFile string) bool {

// IsTagInFile checks if the file contains the tag.
func IsTagInFile(file string, tag string) (bool, error) {
contentInByte, err := ioutil.ReadFile(file)
contentInByte, err := os.ReadFile(filepath.Clean(file))
if err != nil {
return false, err
}
Expand Down Expand Up @@ -143,7 +143,7 @@ func GetPomFileContent(pomFilePath string) (schema.Pom, error) {
if err != nil {
return schema.Pom{}, err
}
byteValue, _ := ioutil.ReadAll(xmlFile)
byteValue, _ := io.ReadAll(xmlFile)

var pom schema.Pom
err = xml.Unmarshal(byteValue, &pom)
Expand Down Expand Up @@ -298,7 +298,7 @@ func isFileInRoot(root string, file string) bool {

// GetFilePathsInRoot returns a slice of all files in the root.
func GetFilePathsInRoot(root string) ([]string, error) {
fileInfos, err := ioutil.ReadDir(root)
fileInfos, err := os.ReadDir(root)
if err != nil {
return nil, err
}
Expand All @@ -310,7 +310,7 @@ func GetFilePathsInRoot(root string) ([]string, error) {
}

func ConvertPropertiesFileAsPathToMap(path string) (map[string]string, error) {
bytes, err := ioutil.ReadFile(path)
bytes, err := os.ReadFile(filepath.Clean(path))
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -426,7 +426,7 @@ func readAnyApplicationFile(root string, propsFiles []model.ApplicationFileInfo,
path = GetAnyApplicationFilePath(root, propsFiles, ctx)
}
if path != "" {
return ioutil.ReadFile(path)
return os.ReadFile(filepath.Clean(path))
}
return nil, errors.New("no file found")
}
Expand Down
4 changes: 2 additions & 2 deletions resources/projects/golang-gin-app/articles/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package articles

import (
_ "fmt"
"github.com/jinzhu/gorm"
"github.com/gothinkster/golang-gin-realworld-example-app/common"
"github.com/gothinkster/golang-gin-realworld-example-app/users"
"github.com/jinzhu/gorm"
"strconv"
)

Expand Down Expand Up @@ -184,7 +184,7 @@ func FindManyArticle(tag, author, limit, offset, favorited string) ([]ArticleMod
count = tx.Model(&articleUserModel).Association("FavoriteModels").Count()
for _, favorite := range favoriteModels {
var model ArticleModel
tx.Model(&favorite).Related(&model, "Favorite")
tx.Model(&favorite).Related(&model, "Favorite") // #nosec G601
models = append(models, model)
}
}
Expand Down
7 changes: 5 additions & 2 deletions resources/projects/golang-gin-app/articles/validators.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package articles

import (
"github.com/gin-gonic/gin"
"github.com/gosimple/slug"
"github.com/gothinkster/golang-gin-realworld-example-app/common"
"github.com/gothinkster/golang-gin-realworld-example-app/users"
"github.com/gin-gonic/gin"
)

type ArticleModelValidator struct {
Expand Down Expand Up @@ -44,7 +44,10 @@ func (s *ArticleModelValidator) Bind(c *gin.Context) error {
s.articleModel.Description = s.Article.Description
s.articleModel.Body = s.Article.Body
s.articleModel.Author = GetArticleUserModel(myUserModel)
s.articleModel.setTags(s.Article.Tags)
err = s.articleModel.setTags(s.Article.Tags)
if err != nil {
return err
}
return nil
}

Expand Down
11 changes: 6 additions & 5 deletions resources/projects/golang-gin-app/common/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import (
"github.com/dgrijalva/jwt-go"
"gopkg.in/go-playground/validator.v8"

"github.com/gin-gonic/gin/binding"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
Expand All @@ -19,14 +19,14 @@ var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345
func RandString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
b[i] = letters[rand.Intn(len(letters))] // #nosec G404
}
return string(b)
}

// Keep this two config private, it should not expose to open source
const NBSecretPassword = "A String Very Very Very Strong!!@##$!@#$"
const NBRandomPassword = "A String Very Very Very Niubilty!!@##$!@#4"
const NBSecretPassword = "A String Very Very Very Strong!!@##$!@#$" // #nosec G101
const NBRandomPassword = "A String Very Very Very Niubilty!!@##$!@#4" // #nosec G101

// A Util function to generate jwt_token which can be used in the request header
func GenToken(id uint) string {
Expand All @@ -42,7 +42,8 @@ func GenToken(id uint) string {
}

// My own Error type that will help return my customized Error info
// {"database": {"hello":"no such table", error: "not_exists"}}
//
// {"database": {"hello":"no such table", error: "not_exists"}}
type CommonError struct {
Errors map[string]interface{} `json:"errors"`
}
Expand Down
36 changes: 23 additions & 13 deletions resources/projects/golang-gin-app/users/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package users

import (
"errors"
"github.com/jinzhu/gorm"
"github.com/gothinkster/golang-gin-realworld-example-app/common"
"github.com/jinzhu/gorm"
"golang.org/x/crypto/bcrypt"
)

Expand All @@ -27,8 +27,9 @@ type UserModel struct {
// DB schema looks like: id, created_at, updated_at, deleted_at, following_id, followed_by_id.
//
// Retrieve them by:
// db.Where(FollowModel{ FollowingID: v.ID, FollowedByID: u.ID, }).First(&follow)
// db.Where(FollowModel{ FollowedByID: u.ID, }).Find(&follows)
//
// db.Where(FollowModel{ FollowingID: v.ID, FollowedByID: u.ID, }).First(&follow)
// db.Where(FollowModel{ FollowedByID: u.ID, }).Find(&follows)
//
// More details about gorm.Model: http://jinzhu.me/gorm/models.html#conventions
type FollowModel struct {
Expand All @@ -50,7 +51,8 @@ func AutoMigrate() {
// What's bcrypt? https://en.wikipedia.org/wiki/Bcrypt
// Golang bcrypt doc: https://godoc.org/golang.org/x/crypto/bcrypt
// You can change the value in bcrypt.DefaultCost to adjust the security index.
// err := userModel.setPassword("password0")
//
// err := userModel.setPassword("password0")
func (u *UserModel) setPassword(password string) error {
if len(password) == 0 {
return errors.New("password should not be empty!")
Expand All @@ -63,15 +65,17 @@ func (u *UserModel) setPassword(password string) error {
}

// Database will only save the hashed string, you should check it by util function.
// if err := serModel.checkPassword("password0"); err != nil { password error }
//
// if err := serModel.checkPassword("password0"); err != nil { password error }
func (u *UserModel) checkPassword(password string) error {
bytePassword := []byte(password)
byteHashedPassword := []byte(u.PasswordHash)
return bcrypt.CompareHashAndPassword(byteHashedPassword, bytePassword)
}

// You could input the conditions and it will return an UserModel in database with error info.
// userModel, err := FindOneUser(&UserModel{Username: "username0"})
//
// userModel, err := FindOneUser(&UserModel{Username: "username0"})
func FindOneUser(condition interface{}) (UserModel, error) {
db := common.GetDB()
var model UserModel
Expand All @@ -80,23 +84,26 @@ func FindOneUser(condition interface{}) (UserModel, error) {
}

// You could input an UserModel which will be saved in database returning with error info
// if err := SaveOne(&userModel); err != nil { ... }
//
// if err := SaveOne(&userModel); err != nil { ... }
func SaveOne(data interface{}) error {
db := common.GetDB()
err := db.Save(data).Error
return err
}

// You could update properties of an UserModel to database returning with error info.
// err := db.Model(userModel).Update(UserModel{Username: "wangzitian0"}).Error
//
// err := db.Model(userModel).Update(UserModel{Username: "wangzitian0"}).Error
func (model *UserModel) Update(data interface{}) error {
db := common.GetDB()
err := db.Model(model).Update(data).Error
return err
}

// You could add a following relationship as userModel1 following userModel2
// err = userModel1.following(userModel2)
//
// err = userModel1.following(userModel2)
func (u UserModel) following(v UserModel) error {
db := common.GetDB()
var follow FollowModel
Expand All @@ -108,7 +115,8 @@ func (u UserModel) following(v UserModel) error {
}

// You could check whether userModel1 following userModel2
// followingBool = myUserModel.isFollowing(self.UserModel)
//
// followingBool = myUserModel.isFollowing(self.UserModel)
func (u UserModel) isFollowing(v UserModel) bool {
db := common.GetDB()
var follow FollowModel
Expand All @@ -120,7 +128,8 @@ func (u UserModel) isFollowing(v UserModel) bool {
}

// You could delete a following relationship as userModel1 following userModel2
// err = userModel1.unFollowing(userModel2)
//
// err = userModel1.unFollowing(userModel2)
func (u UserModel) unFollowing(v UserModel) error {
db := common.GetDB()
err := db.Where(FollowModel{
Expand All @@ -131,7 +140,8 @@ func (u UserModel) unFollowing(v UserModel) error {
}

// You could get a following list of userModel
// followings := userModel.GetFollowings()
//
// followings := userModel.GetFollowings()
func (u UserModel) GetFollowings() []UserModel {
db := common.GetDB()
tx := db.Begin()
Expand All @@ -142,7 +152,7 @@ func (u UserModel) GetFollowings() []UserModel {
}).Find(&follows)
for _, follow := range follows {
var userModel UserModel
tx.Model(&follow).Related(&userModel, "Following")
tx.Model(&follow).Related(&userModel, "Following") // #nosec G601
followings = append(followings, userModel)
}
tx.Commit()
Expand Down
7 changes: 5 additions & 2 deletions resources/projects/golang-gin-app/users/validators.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package users

import (
"github.com/gothinkster/golang-gin-realworld-example-app/common"
"github.com/gin-gonic/gin"
"github.com/gothinkster/golang-gin-realworld-example-app/common"
)

// *ModelValidator containing two parts:
Expand Down Expand Up @@ -33,7 +33,10 @@ func (self *UserModelValidator) Bind(c *gin.Context) error {
self.userModel.Bio = self.User.Bio

if self.User.Password != common.NBRandomPassword {
self.userModel.setPassword(self.User.Password)
err := self.userModel.setPassword(self.User.Password)
if err != nil {
return err
}
}
if self.User.Image != "" {
self.userModel.Image = &self.User.Image
Expand Down
12 changes: 11 additions & 1 deletion resources/projects/golang-runtime/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,22 @@ import (
"fmt"
"net/http"
"os"
"time"
)

func main() {
http.HandleFunc("/", HelloHandler)
fmt.Println("Listening on localhost:8080")
http.ListenAndServe(":8080", nil)

server := &http.Server{
Addr: ":8080",
ReadHeaderTimeout: 3 * time.Second,
}

err := server.ListenAndServe()
if err != nil {
panic(err)
}
}

func HelloHandler(w http.ResponseWriter, r *http.Request) {
Expand Down