github.com/SAP/jenkins-library@v1.362.0/cmd/contrastExecuteScan_generated.go (about) 1 // Code generated by piper's step-generator. DO NOT EDIT. 2 3 package cmd 4 5 import ( 6 "fmt" 7 "os" 8 "reflect" 9 "strings" 10 "time" 11 12 "github.com/SAP/jenkins-library/pkg/config" 13 "github.com/SAP/jenkins-library/pkg/gcs" 14 "github.com/SAP/jenkins-library/pkg/log" 15 "github.com/SAP/jenkins-library/pkg/splunk" 16 "github.com/SAP/jenkins-library/pkg/telemetry" 17 "github.com/SAP/jenkins-library/pkg/validation" 18 "github.com/bmatcuk/doublestar" 19 "github.com/spf13/cobra" 20 ) 21 22 type contrastExecuteScanOptions struct { 23 UserAPIKey string `json:"userApiKey,omitempty"` 24 ServiceKey string `json:"serviceKey,omitempty"` 25 Username string `json:"username,omitempty"` 26 Server string `json:"server,omitempty"` 27 OrganizationID string `json:"organizationId,omitempty"` 28 ApplicationID string `json:"applicationId,omitempty"` 29 VulnerabilityThresholdTotal int `json:"vulnerabilityThresholdTotal,omitempty"` 30 CheckForCompliance bool `json:"checkForCompliance,omitempty"` 31 } 32 33 type contrastExecuteScanReports struct { 34 } 35 36 func (p *contrastExecuteScanReports) persist(stepConfig contrastExecuteScanOptions, gcpJsonKeyFilePath string, gcsBucketId string, gcsFolderPath string, gcsSubFolder string) { 37 if gcsBucketId == "" { 38 log.Entry().Info("persisting reports to GCS is disabled, because gcsBucketId is empty") 39 return 40 } 41 log.Entry().Info("Uploading reports to Google Cloud Storage...") 42 content := []gcs.ReportOutputParam{ 43 {FilePattern: "**/toolrun_contrast_*.json", ParamRef: "", StepResultType: "contrast"}, 44 {FilePattern: "**/piper_contrast_report.json", ParamRef: "", StepResultType: "contrast"}, 45 } 46 envVars := []gcs.EnvVar{ 47 {Name: "GOOGLE_APPLICATION_CREDENTIALS", Value: gcpJsonKeyFilePath, Modified: false}, 48 } 49 gcsClient, err := gcs.NewClient(gcs.WithEnvVars(envVars)) 50 if err != nil { 51 log.Entry().Errorf("creation of GCS client failed: %v", err) 52 return 53 } 54 defer gcsClient.Close() 55 structVal := reflect.ValueOf(&stepConfig).Elem() 56 inputParameters := map[string]string{} 57 for i := 0; i < structVal.NumField(); i++ { 58 field := structVal.Type().Field(i) 59 if field.Type.String() == "string" { 60 paramName := strings.Split(field.Tag.Get("json"), ",") 61 paramValue, _ := structVal.Field(i).Interface().(string) 62 inputParameters[paramName[0]] = paramValue 63 } 64 } 65 if err := gcs.PersistReportsToGCS(gcsClient, content, inputParameters, gcsFolderPath, gcsBucketId, gcsSubFolder, doublestar.Glob, os.Stat); err != nil { 66 log.Entry().Errorf("failed to persist reports: %v", err) 67 } 68 } 69 70 // ContrastExecuteScanCommand This step evaluates if the audit requirements for Contrast Assess have been fulfilled. 71 func ContrastExecuteScanCommand() *cobra.Command { 72 const STEP_NAME = "contrastExecuteScan" 73 74 metadata := contrastExecuteScanMetadata() 75 var stepConfig contrastExecuteScanOptions 76 var startTime time.Time 77 var reports contrastExecuteScanReports 78 var logCollector *log.CollectorHook 79 var splunkClient *splunk.Splunk 80 telemetryClient := &telemetry.Telemetry{} 81 82 var createContrastExecuteScanCmd = &cobra.Command{ 83 Use: STEP_NAME, 84 Short: "This step evaluates if the audit requirements for Contrast Assess have been fulfilled.", 85 Long: `This step evaluates if the audit requirements for Contrast Assess have been fulfilled after the execution of security tests by Contrast Assess. For further information on the tool, please consult the [documentation](https://github.wdf.sap.corp/pages/Security-Testing/doc/contrast/introduction/).`, 86 PreRunE: func(cmd *cobra.Command, _ []string) error { 87 startTime = time.Now() 88 log.SetStepName(STEP_NAME) 89 log.SetVerbose(GeneralConfig.Verbose) 90 91 GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens) 92 93 path, _ := os.Getwd() 94 fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path} 95 log.RegisterHook(fatalHook) 96 97 err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile) 98 if err != nil { 99 log.SetErrorCategory(log.ErrorConfiguration) 100 return err 101 } 102 log.RegisterSecret(stepConfig.UserAPIKey) 103 log.RegisterSecret(stepConfig.ServiceKey) 104 log.RegisterSecret(stepConfig.Username) 105 106 if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 { 107 sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID) 108 log.RegisterHook(&sentryHook) 109 } 110 111 if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 { 112 splunkClient = &splunk.Splunk{} 113 logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID} 114 log.RegisterHook(logCollector) 115 } 116 117 if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil { 118 log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook") 119 } 120 121 validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages()) 122 if err != nil { 123 return err 124 } 125 if err = validation.ValidateStruct(stepConfig); err != nil { 126 log.SetErrorCategory(log.ErrorConfiguration) 127 return err 128 } 129 130 return nil 131 }, 132 Run: func(_ *cobra.Command, _ []string) { 133 stepTelemetryData := telemetry.CustomData{} 134 stepTelemetryData.ErrorCode = "1" 135 handler := func() { 136 reports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder) 137 config.RemoveVaultSecretFiles() 138 stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds()) 139 stepTelemetryData.ErrorCategory = log.GetErrorCategory().String() 140 stepTelemetryData.PiperCommitHash = GitCommit 141 telemetryClient.SetData(&stepTelemetryData) 142 telemetryClient.Send() 143 if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { 144 splunkClient.Initialize(GeneralConfig.CorrelationID, 145 GeneralConfig.HookConfig.SplunkConfig.Dsn, 146 GeneralConfig.HookConfig.SplunkConfig.Token, 147 GeneralConfig.HookConfig.SplunkConfig.Index, 148 GeneralConfig.HookConfig.SplunkConfig.SendLogs) 149 splunkClient.Send(telemetryClient.GetData(), logCollector) 150 } 151 if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 { 152 splunkClient.Initialize(GeneralConfig.CorrelationID, 153 GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint, 154 GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken, 155 GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex, 156 GeneralConfig.HookConfig.SplunkConfig.SendLogs) 157 splunkClient.Send(telemetryClient.GetData(), logCollector) 158 } 159 } 160 log.DeferExitHandler(handler) 161 defer handler() 162 telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token) 163 contrastExecuteScan(stepConfig, &stepTelemetryData) 164 stepTelemetryData.ErrorCode = "0" 165 log.Entry().Info("SUCCESS") 166 }, 167 } 168 169 addContrastExecuteScanFlags(createContrastExecuteScanCmd, &stepConfig) 170 return createContrastExecuteScanCmd 171 } 172 173 func addContrastExecuteScanFlags(cmd *cobra.Command, stepConfig *contrastExecuteScanOptions) { 174 cmd.Flags().StringVar(&stepConfig.UserAPIKey, "userApiKey", os.Getenv("PIPER_userApiKey"), "User API key for authorization access to Contrast Assess.") 175 cmd.Flags().StringVar(&stepConfig.ServiceKey, "serviceKey", os.Getenv("PIPER_serviceKey"), "User Service Key for authorization access to Contrast Assess.") 176 cmd.Flags().StringVar(&stepConfig.Username, "username", os.Getenv("PIPER_username"), "Email to use for authorization access to Contrast Assess.") 177 cmd.Flags().StringVar(&stepConfig.Server, "server", os.Getenv("PIPER_server"), "The URL of the Contrast Assess Team server.") 178 cmd.Flags().StringVar(&stepConfig.OrganizationID, "organizationId", os.Getenv("PIPER_organizationId"), "Organization UUID. It's the first UUID in most navigation URLs.") 179 cmd.Flags().StringVar(&stepConfig.ApplicationID, "applicationId", os.Getenv("PIPER_applicationId"), "Application UUID. It's the Last UUID of application View URL") 180 cmd.Flags().IntVar(&stepConfig.VulnerabilityThresholdTotal, "vulnerabilityThresholdTotal", 0, "Threshold for maximum number of allowed vulnerabilities.") 181 cmd.Flags().BoolVar(&stepConfig.CheckForCompliance, "checkForCompliance", false, "If set to true, the piper step checks for compliance based on vulnerability thresholds. Example - If total vulnerabilities are 10 and vulnerabilityThresholdTotal is set as 0, then the steps throws an compliance error.") 182 183 cmd.MarkFlagRequired("userApiKey") 184 cmd.MarkFlagRequired("serviceKey") 185 cmd.MarkFlagRequired("username") 186 cmd.MarkFlagRequired("server") 187 cmd.MarkFlagRequired("organizationId") 188 cmd.MarkFlagRequired("applicationId") 189 } 190 191 // retrieve step metadata 192 func contrastExecuteScanMetadata() config.StepData { 193 var theMetaData = config.StepData{ 194 Metadata: config.StepMetadata{ 195 Name: "contrastExecuteScan", 196 Aliases: []config.Alias{}, 197 Description: "This step evaluates if the audit requirements for Contrast Assess have been fulfilled.", 198 }, 199 Spec: config.StepSpec{ 200 Inputs: config.StepInputs{ 201 Secrets: []config.StepSecrets{ 202 {Name: "userCredentialsId", Description: "Jenkins 'Username with password' credentials ID containing username (email) and service key to communicate with the Contrast server.", Type: "jenkins"}, 203 {Name: "apiKeyCredentialsId", Description: "Jenkins 'Secret text' credentials ID containing user API key to communicate with the Contrast server.", Type: "jenkins"}, 204 }, 205 Resources: []config.StepResources{ 206 {Name: "buildDescriptor", Type: "stash"}, 207 {Name: "tests", Type: "stash"}, 208 }, 209 Parameters: []config.StepParameters{ 210 { 211 Name: "userApiKey", 212 ResourceRef: []config.ResourceReference{ 213 { 214 Name: "apiKeyCredentialsId", 215 Type: "secret", 216 }, 217 218 { 219 Name: "contrastVaultSecretName", 220 Type: "vaultSecret", 221 Default: "contrast", 222 }, 223 }, 224 Scope: []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"}, 225 Type: "string", 226 Mandatory: true, 227 Aliases: []config.Alias{}, 228 Default: os.Getenv("PIPER_userApiKey"), 229 }, 230 { 231 Name: "serviceKey", 232 ResourceRef: []config.ResourceReference{ 233 { 234 Name: "userCredentialsId", 235 Param: "serviceKey", 236 Type: "secret", 237 }, 238 239 { 240 Name: "contrastVaultSecretName", 241 Type: "vaultSecret", 242 Default: "contrast", 243 }, 244 }, 245 Scope: []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"}, 246 Type: "string", 247 Mandatory: true, 248 Aliases: []config.Alias{{Name: "service_key"}}, 249 Default: os.Getenv("PIPER_serviceKey"), 250 }, 251 { 252 Name: "username", 253 ResourceRef: []config.ResourceReference{ 254 { 255 Name: "userCredentialsId", 256 Param: "username", 257 Type: "secret", 258 }, 259 260 { 261 Name: "contrastVaultSecretName", 262 Type: "vaultSecret", 263 Default: "contrast", 264 }, 265 }, 266 Scope: []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"}, 267 Type: "string", 268 Mandatory: true, 269 Aliases: []config.Alias{}, 270 Default: os.Getenv("PIPER_username"), 271 }, 272 { 273 Name: "server", 274 ResourceRef: []config.ResourceReference{}, 275 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 276 Type: "string", 277 Mandatory: true, 278 Aliases: []config.Alias{}, 279 Default: os.Getenv("PIPER_server"), 280 }, 281 { 282 Name: "organizationId", 283 ResourceRef: []config.ResourceReference{}, 284 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 285 Type: "string", 286 Mandatory: true, 287 Aliases: []config.Alias{}, 288 Default: os.Getenv("PIPER_organizationId"), 289 }, 290 { 291 Name: "applicationId", 292 ResourceRef: []config.ResourceReference{}, 293 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 294 Type: "string", 295 Mandatory: true, 296 Aliases: []config.Alias{}, 297 Default: os.Getenv("PIPER_applicationId"), 298 }, 299 { 300 Name: "vulnerabilityThresholdTotal", 301 ResourceRef: []config.ResourceReference{}, 302 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 303 Type: "int", 304 Mandatory: false, 305 Aliases: []config.Alias{}, 306 Default: 0, 307 }, 308 { 309 Name: "checkForCompliance", 310 ResourceRef: []config.ResourceReference{}, 311 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 312 Type: "bool", 313 Mandatory: false, 314 Aliases: []config.Alias{}, 315 Default: false, 316 }, 317 }, 318 }, 319 Containers: []config.Container{ 320 {}, 321 }, 322 Outputs: config.StepOutputs{ 323 Resources: []config.StepResources{ 324 { 325 Name: "reports", 326 Type: "reports", 327 Parameters: []map[string]interface{}{ 328 {"filePattern": "**/toolrun_contrast_*.json", "type": "contrast"}, 329 {"filePattern": "**/piper_contrast_report.json", "type": "contrast"}, 330 }, 331 }, 332 }, 333 }, 334 }, 335 } 336 return theMetaData 337 }