Skip to content

Commit 6deea32

Browse files
added-XML-JSON-validation
1 parent 8c46520 commit 6deea32

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

internal/commands/scan.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package commands
33
import (
44
"archive/zip"
55
"encoding/json"
6+
"encoding/xml"
67
"fmt"
78
"io"
89
"io/fs"
@@ -1685,6 +1686,13 @@ func getUploadURLFromSource(cmd *cobra.Command, uploadsWrapper wrappers.UploadsW
16851686
var directoryPath string
16861687
if isSbom {
16871688
sbomFile, _ := cmd.Flags().GetString(commonParams.SourcesFlag)
1689+
isValid, err := isValidJSONOrXML(sbomFile)
1690+
if err != nil {
1691+
return "", "", errors.New(err.Error())
1692+
}
1693+
if !isValid {
1694+
return "", "", errors.New("Provide a correct JSON/XML file")
1695+
}
16881696
zipFilePath, err = util.CompressFile(sbomFile, "sbomFileCompress", directoryCreationPrefix)
16891697
} else {
16901698
zipFilePath, directoryPath, err = definePathForZipFileOrDirectory(cmd)
@@ -3133,3 +3141,32 @@ func createMinimalZipFile() (string, error) {
31333141

31343142
return outputFile.Name(), nil
31353143
}
3144+
3145+
func isValidJSONOrXML(path string) (bool, error) {
3146+
ext := strings.ToLower(filepath.Ext(path))
3147+
if ext != ".json" && ext != ".xml" {
3148+
return false, nil
3149+
}
3150+
3151+
data, err := ioutil.ReadFile(path)
3152+
if err != nil {
3153+
return false, fmt.Errorf("failed to read file: %w", err)
3154+
}
3155+
3156+
switch ext {
3157+
case ".json":
3158+
var js interface{}
3159+
if err := json.Unmarshal(data, &js); err != nil {
3160+
return false, nil // Invalid JSON
3161+
}
3162+
case ".xml":
3163+
var x interface{}
3164+
if err := xml.Unmarshal(data, &x); err != nil {
3165+
return false, nil // Invalid XML
3166+
}
3167+
default:
3168+
return false, nil
3169+
}
3170+
3171+
return true, nil
3172+
}

0 commit comments

Comments
 (0)