-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathutils.go
291 lines (249 loc) · 8.75 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package utils
import (
"bytes"
"crypto"
"encoding/hex"
"encoding/json"
"fmt"
xscutils "github.com/jfrog/jfrog-client-go/xsc/services/utils"
orderedJson "github.com/virtuald/go-ordered-json"
"os"
"path/filepath"
"strings"
"github.com/jfrog/jfrog-client-go/utils/log"
"golang.org/x/exp/slices"
"time"
"github.com/jfrog/gofrog/datastructures"
"github.com/jfrog/jfrog-cli-core/v2/utils/coreutils"
clientutils "github.com/jfrog/jfrog-client-go/utils"
"github.com/jfrog/jfrog-client-go/utils/errorutils"
)
const (
NodeModulesPattern = "**/*node_modules*/**"
JfMsiEnvVariable = "JF_MSI"
BaseDocumentationURL = "https://docs.jfrog-applications.jfrog.io/jfrog-security-features/"
JasInfoURL = "https://jfrog.com/xray/"
EntitlementsMinVersion = "3.66.5"
GitRepoKeyAnalyticsMinVersion = "3.114.0"
JfrogExternalRunIdEnv = "JFROG_CLI_USAGE_RUN_ID"
JfrogExternalJobIdEnv = "JFROG_CLI_USAGE_JOB_ID"
JfrogExternalGitRepoEnv = "JFROG_CLI_USAGE_GIT_REPO"
)
var (
// Exclude pattern for files.
DefaultJasExcludePatterns = []string{"**/.git/**", "**/*test*/**", "**/*venv*/**", NodeModulesPattern, "**/target/**", "**/dist/**"}
// Exclude pattern for directories.
DefaultScaExcludePatterns = []string{"*.git*", "*node_modules*", "*target*", "*venv*", "*test*", "dist"}
)
const (
ContextualAnalysisScan SubScanType = "contextual_analysis"
ScaScan SubScanType = "sca"
IacScan SubScanType = "iac"
SastScan SubScanType = "sast"
SecretsScan SubScanType = "secrets"
SecretTokenValidationScan SubScanType = "secrets_token_validation"
ViolationTypeSecurity ViolationIssueType = "security"
ViolationTypeLicense ViolationIssueType = "license"
ViolationTypeOperationalRisk ViolationIssueType = "operational_risk"
)
type ViolationIssueType string
func (v ViolationIssueType) String() string {
return string(v)
}
type SubScanType string
func (s SubScanType) String() string {
return string(s)
}
const (
SourceCode CommandType = "source_code"
Binary CommandType = "binary"
DockerImage CommandType = "docker_image"
Build CommandType = "build"
Curation CommandType = "curation"
SBOM CommandType = "SBOM"
)
type CommandType string
func (s CommandType) IsTargetBinary() bool {
return s == Binary || s == DockerImage
}
func GetAllSupportedScans() []SubScanType {
return []SubScanType{ScaScan, ContextualAnalysisScan, IacScan, SastScan, SecretsScan, SecretTokenValidationScan}
}
// IsScanRequested returns true if the scan is requested, otherwise false. If requestedScans is empty, all scans are considered requested.
func IsScanRequested(cmdType CommandType, subScan SubScanType, requestedScans ...SubScanType) bool {
if cmdType.IsTargetBinary() && (subScan == IacScan || subScan == SastScan) {
return false
}
return len(requestedScans) == 0 || slices.Contains(requestedScans, subScan)
}
func IsJASRequested(cmdType CommandType, requestedScans ...SubScanType) bool {
return IsScanRequested(cmdType, ContextualAnalysisScan, requestedScans...) ||
IsScanRequested(cmdType, SecretsScan, requestedScans...) ||
IsScanRequested(cmdType, IacScan, requestedScans...) ||
IsScanRequested(cmdType, SastScan, requestedScans...)
}
func GetScanFindingsLog(scanType SubScanType, vulnerabilitiesCount, violationsCount, threadId int) string {
threadPrefix := ""
if threadId >= 0 {
threadPrefix = clientutils.GetLogMsgPrefix(threadId, false)
}
if vulnerabilitiesCount == 0 && violationsCount == 0 {
return fmt.Sprintf("%sNo %s findings", threadPrefix, scanType.String())
}
msg := fmt.Sprintf("%sFound", threadPrefix)
hasVulnerabilities := vulnerabilitiesCount > 0
if hasVulnerabilities {
msg += fmt.Sprintf(" %d %s vulnerabilities", vulnerabilitiesCount, scanType.String())
}
if violationsCount > 0 {
if hasVulnerabilities {
msg = fmt.Sprintf("%s (%d violations)", msg, violationsCount)
} else {
msg += fmt.Sprintf(" %d %s violations", violationsCount, scanType.String())
}
}
return msg
}
func IsCI() bool {
return strings.ToLower(os.Getenv(coreutils.CI)) == "true"
}
// UniqueIntersection returns a new slice of strings that contains elements from both input slices without duplicates
func UniqueIntersection[T comparable](arr []T, others ...T) []T {
uniqueSet := datastructures.MakeSetFromElements(arr...)
uniqueIntersection := datastructures.MakeSet[T]()
for _, other := range others {
if exist := uniqueSet.Exists(other); exist {
uniqueIntersection.Add(other)
}
}
return uniqueIntersection.ToSlice()
}
// UniqueUnion returns a new slice of strings that contains elements from the input slice and the elements provided without duplicates
func UniqueUnion[T comparable](arr []T, elements ...T) []T {
uniqueSet := datastructures.MakeSetFromElements(arr...)
uniqueSet.AddElements(elements...)
return uniqueSet.ToSlice()
}
func GetAsJsonBytes(output interface{}, escapeValues, indent bool) (results []byte, err error) {
if escapeValues {
if results, err = orderedJson.Marshal(output); errorutils.CheckError(err) != nil {
return
}
} else {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
if err = encoder.Encode(output); err != nil {
return
}
results = buffer.Bytes()
}
if indent {
return doIndent(results)
}
return
}
func doIndent(bytesRes []byte) ([]byte, error) {
var content bytes.Buffer
if err := json.Indent(&content, bytesRes, "", " "); errorutils.CheckError(err) != nil {
return content.Bytes(), err
}
return content.Bytes(), nil
}
func GetAsJsonString(output interface{}, escapeValues, indent bool) (string, error) {
results, err := GetAsJsonBytes(output, escapeValues, indent)
if err != nil {
return "", err
}
return string(results), nil
}
func NewStringPtr(v string) *string {
return &v
}
func NewBoolPtr(v bool) *bool {
return &v
}
func NewIntPtr(v int) *int {
return &v
}
func NewInt64Ptr(v int64) *int64 {
return &v
}
func NewFloat64Ptr(v float64) *float64 {
return &v
}
func NewStrPtr(v string) *string {
return &v
}
func Md5Hash(values ...string) (string, error) {
return toHash(crypto.MD5, values...)
}
func Sha1Hash(values ...string) (string, error) {
return toHash(crypto.SHA1, values...)
}
func toHash(hash crypto.Hash, values ...string) (string, error) {
h := hash.New()
for _, ob := range values {
_, err := fmt.Fprint(h, ob)
if err != nil {
return "", err
}
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// map[string]string to []string (key=value format)
func ToCommandEnvVars(envVarsMap map[string]string) (converted []string) {
converted = make([]string, 0, len(envVarsMap))
for key, value := range envVarsMap {
converted = append(converted, fmt.Sprintf("%s=%s", key, value))
}
return
}
// []string (key=value format) to map[string]string
func ToEnvVarsMap(envVars []string) (converted map[string]string) {
converted = make(map[string]string)
for _, envVar := range envVars {
key, value := splitEnvVar(envVar)
converted[key] = value
}
return
}
// Merge multiple maps into one, the last map will override the previous ones
func MergeMaps(maps ...map[string]string) map[string]string {
merged := make(map[string]string)
for _, m := range maps {
for k, v := range m {
merged[k] = v
}
}
return merged
}
func splitEnvVar(envVar string) (key, value string) {
split := strings.Split(envVar, "=")
if len(split) == 1 {
return split[0], ""
}
return split[0], strings.Join(split[1:], "=")
}
func DumpContentToFile(fileContent []byte, scanResultsOutputDir string, scanType string) (err error) {
// TODO this function should be in utils/results/results.go after the refactor, since it is a common code for Jas and SCA scanners
// TODO AFTER merging the refactor - make sure to create a new directory for every Scan Target and convert results to Sarif before writing them to file
var curTimeHash string
if curTimeHash, err = Md5Hash(time.Now().String()); err != nil {
return fmt.Errorf("failed to write %s scan results to file: %s", scanType, err.Error())
}
resultsFileName := strings.ToLower(scanType) + "_results_" + curTimeHash + ".json"
resultsFileFullPath := filepath.Join(scanResultsOutputDir, resultsFileName)
log.Debug(fmt.Sprintf("Scans output directory was provided, saving %s scan results to file '%s'...", scanType, resultsFileFullPath))
if err = os.WriteFile(resultsFileFullPath, fileContent, 0644); err != nil {
return fmt.Errorf("failed to write %s scan results to file: %s", scanType, err.Error())
}
return
}
// Returns the key for the git reop Url, as expected by the Analyzer Manager and the Analytics event report
func GetGitRepoUrlKey(gitRepoHttpsCloneUrl string) string {
if gitRepoHttpsCloneUrl == "" {
return ""
}
return xscutils.GetGitRepoUrlKey(gitRepoHttpsCloneUrl)
}