Skip to content

Commit

Permalink
Merge branch 'main' into other/ci_new_cert
Browse files Browse the repository at this point in the history
  • Loading branch information
AlvoBen authored Nov 14, 2024
2 parents 8d9ffde + be94344 commit 5756b51
Show file tree
Hide file tree
Showing 9 changed files with 85 additions and 83 deletions.
2 changes: 1 addition & 1 deletion gonMac.hcl
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ source = ["./dist/cx-mac-universal_darwin_all/cx"]
bundle_id = "com.checkmarx.cli"

apple_id {
username = "tiago.baptista@checkmarx.com"
username = "ben.alvo@checkmarx.com"
provider = "Z68SAQG5BR"
}

Expand Down
17 changes: 8 additions & 9 deletions internal/commands/groups.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,24 @@ package commands
import (
"encoding/json"

featureFlagsConstants "github.com/checkmarx/ast-cli/internal/constants/feature-flags"
commonParams "github.com/checkmarx/ast-cli/internal/params"
"github.com/checkmarx/ast-cli/internal/services"
"github.com/checkmarx/ast-cli/internal/wrappers"
"github.com/spf13/cobra"
)

func updateGroupValues(input *[]byte, cmd *cobra.Command, groupsWrapper wrappers.GroupsWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) ([]*wrappers.Group, error) {
func updateGroupValues(input *[]byte, cmd *cobra.Command, groupsWrapper wrappers.GroupsWrapper) ([]*wrappers.Group, error) {
groupListStr, _ := cmd.Flags().GetString(commonParams.GroupList)
groups, err := services.CreateGroupsMap(groupListStr, groupsWrapper)
if err != nil {
return groups, err
}
flagResponse, _ := wrappers.GetSpecificFeatureFlag(featureFlagsWrapper, featureFlagsConstants.AccessManagementEnabled)
if !flagResponse.Status {
var info map[string]interface{}
_ = json.Unmarshal(*input, &info)
info["groups"] = services.GetGroupIds(groups)
*input, _ = json.Marshal(info)
}

// we're not checking here status of the feature flag, because of refactoring in AM
var info map[string]interface{}
_ = json.Unmarshal(*input, &info)
info["groups"] = services.GetGroupIds(groups)
*input, _ = json.Marshal(info)

return groups, nil
}
2 changes: 1 addition & 1 deletion internal/commands/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ func runCreateProjectCommand(
if err != nil {
return err
}
groups, err := updateGroupValues(&input, cmd, groupsWrapper, featureFlagsWrapper)
groups, err := updateGroupValues(&input, cmd, groupsWrapper)
if err != nil {
return err
}
Expand Down
57 changes: 51 additions & 6 deletions internal/commands/scan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ import (
"strings"
"testing"

"github.com/checkmarx/ast-cli/internal/commands/util"
errorConstants "github.com/checkmarx/ast-cli/internal/constants/errors"
exitCodes "github.com/checkmarx/ast-cli/internal/constants/exit-codes"
"github.com/checkmarx/ast-cli/internal/logger"
commonParams "github.com/checkmarx/ast-cli/internal/params"
"github.com/checkmarx/ast-cli/internal/wrappers"
"github.com/checkmarx/ast-cli/internal/wrappers/mock"
Expand Down Expand Up @@ -52,6 +54,8 @@ const (
InvalidEngineMessage = "Please verify if engine is installed"
SCSScoreCardError = "SCS scan failed to start: Scorecard scan is missing required flags, please include in the ast-cli arguments: " +
"--scs-repo-url your_repo_url --scs-repo-token your_repo_token"
outputFileName = "test_output.log"
noUpdatesForExistingProject = "No applicationId or tags to update. Skipping project update."
)

func TestScanHelp(t *testing.T) {
Expand Down Expand Up @@ -382,14 +386,31 @@ func TestCreateScanBranches(t *testing.T) {
execCmdNilAssertion(t, "scan", "create", "--project-name", "MOCK", "-s", dummyRepo, "-b", "branch_defined")
}

func TestCreateScanWithProjectGroup(t *testing.T) {
func TestCreateScan_WhenProjectNotExistsAndInvalidGroup_ShouldFail(t *testing.T) {
err := execCmdNotNilAssertion(
t,
"scan", "create", "--project-name", "invalidGroup", "-s", ".", "--branch", "main", "--project-groups", "invalidGroup",
"scan", "create", "--project-name", "newProject", "-s", ".", "--branch", "main", "--project-groups", "invalidGroup",
)
assert.Assert(t, err.Error() == "Failed updating a project: Failed finding groups: [invalidGroup]", "\n the received error is:", err.Error())
}

func TestCreateScan_WhenProjectNotExists_ShouldCreateProjectAndAssignGroup(t *testing.T) {
file := createOutputFile(t, outputFileName)
defer deleteOutputFile(file)
defer logger.SetOutput(os.Stdout)

baseArgs := []string{"scan", "create", "--project-name", "newProject", "-s", ".", "--branch", "main", "--project-groups", "existsGroup1", "--debug"}
execCmdNilAssertion(
t,
baseArgs...,
)
stdoutString, err := util.ReadFileAsString(file.Name())
if err != nil {
t.Fatalf("Failed to read log file: %v", err)
}
assert.Equal(t, strings.Contains(stdoutString, "Updating project groups"), true, "Expected output: %s", "Updating project groups")
}

func TestScanWorkflowMissingID(t *testing.T) {
err := execCmdNotNilAssertion(t, "scan", "workflow")
assert.Error(t, err, "Please provide a scan ID", err.Error())
Expand Down Expand Up @@ -590,11 +611,18 @@ func TestCreateScanProjectTags(t *testing.T) {
"--project-tags", "test", "--debug")
}

func TestCreateScanProjecGroupsError(t *testing.T) {
func TestCreateScan_WhenProjectExists_ShouldIgnoreGroups(t *testing.T) {
file := createOutputFile(t, outputFileName)
defer deleteOutputFile(file)
defer logger.SetOutput(os.Stdout)
baseArgs := []string{scanCommand, "create", "--project-name", "MOCK", "-s", dummyRepo, "-b", "dummy_branch",
"--debug", "--project-groups", "err"}
err := execCmdNotNilAssertion(t, baseArgs...)
assert.Error(t, err, "Failed updating a project: Failed finding groups: [err]", err.Error())
"--debug", "--project-groups", "anyProjectGroup"}
execCmdNilAssertion(t, baseArgs...)
stdoutString, err := util.ReadFileAsString(file.Name())
if err != nil {
t.Fatalf("Failed to read log file: %v", err)
}
assert.Equal(t, strings.Contains(stdoutString, noUpdatesForExistingProject), true, "Expected output: %s", noUpdatesForExistingProject)
}
func TestScanCreateLastSastScanTimeWithInvalidValue(t *testing.T) {
baseArgs := []string{"scan", "create", "--project-name", "MOCK", "-s", dummyRepo, "-b", "dummy_branch", "--sca-exploitable-path", "true", "--sca-last-sast-scan-time", "notaniteger"}
Expand Down Expand Up @@ -1275,3 +1303,20 @@ func TestFilterMatched(t *testing.T) {
})
}
}

func createOutputFile(t *testing.T, fileName string) *os.File {
file, err := os.Create(fileName)
if err != nil {
t.Fatalf("Failed to create log file: %v", err)
}
logger.SetOutput(file)
return file
}

func deleteOutputFile(file *os.File) {
file.Close()
err := os.Remove(file.Name())
if err != nil {
logger.Printf("Failed to remove log file: %v", err)
}
}
17 changes: 5 additions & 12 deletions internal/services/groups.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@ import (
"github.com/pkg/errors"
)

func GetGroupMap(groupsWrapper wrappers.GroupsWrapper, projectGroups string, projModelResp *wrappers.ProjectResponseModel,
featureFlagsWrapper wrappers.FeatureFlagsWrapper) ([]*wrappers.Group, []string, error) {
func GetGroupMap(groupsWrapper wrappers.GroupsWrapper, projectGroups string, projModelResp *wrappers.ProjectResponseModel) ([]*wrappers.Group, []string, error) {
groupsMap, groupErr := CreateGroupsMap(projectGroups, groupsWrapper)
if groupErr != nil {
return nil, nil, errors.Errorf("%s: %v", failedUpdatingProj, groupErr)
}
groups := getGroupsForRequest(groupsMap, featureFlagsWrapper)
// we're not checking here status of the feature flag, because of refactoring in AM
groups := GetGroupIds(groupsMap)
if projModelResp != nil {
groups = append(getGroupsForRequest(groupsMap, featureFlagsWrapper), projModelResp.Groups...)
// we're not checking here status of the feature flag, because of refactoring in AM
groups = append(GetGroupIds(groupsMap), projModelResp.Groups...)
return groupsMap, groups, nil
}
return groupsMap, groups, nil
Expand Down Expand Up @@ -47,14 +48,6 @@ func CreateGroupsMap(groupsStr string, groupsWrapper wrappers.GroupsWrapper) ([]
return groupsMap, nil
}

func getGroupsForRequest(groups []*wrappers.Group, featureFlagsWrapper wrappers.FeatureFlagsWrapper) []string {
flagResponse, _ := wrappers.GetSpecificFeatureFlag(featureFlagsWrapper, featureFlagsConstants.AccessManagementEnabled)
if !flagResponse.Status {
return GetGroupIds(groups)
}
return nil
}

func AssignGroupsToProjectNewAccessManagement(projectID string, projectName string, groups []*wrappers.Group,
accessManagement wrappers.AccessManagementWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) error {
flagResponse, _ := wrappers.GetSpecificFeatureFlag(featureFlagsWrapper, featureFlagsConstants.AccessManagementEnabled)
Expand Down
27 changes: 0 additions & 27 deletions internal/services/groups_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,33 +173,6 @@ func Test_findGroupByName(t *testing.T) {
}
}

func Test_getGroupsForRequest(t *testing.T) {
setup() // Clear the map before starting this test
type args struct {
groups []*wrappers.Group
}
tests := []struct {
name string
args args
want []string
}{
{
name: "When access management is disabled, return group IDs of the groups",
args: args{groups: []*wrappers.Group{{ID: "group-id-1", Name: "group-name-1"}, {ID: "group-id-2", Name: "group-name-2"}}},
want: []string{"group-id-1", "group-id-2"},
},
}
for _, tt := range tests {
ttt := tt
t.Run(tt.name, func(t *testing.T) {
mock.Flag = wrappers.FeatureFlagResponseModel{Name: featureFlagsConstants.AccessManagementEnabled, Status: false}
if got := getGroupsForRequest(ttt.args.groups, &mock.FeatureFlagsMockWrapper{}); !reflect.DeepEqual(got, ttt.want) {
t.Errorf("getGroupsForRequest() = %v, want %v", got, ttt.want)
}
})
}
}

func Test_getGroupsToAssign(t *testing.T) {
type args struct {
receivedGroups []*wrappers.Group
Expand Down
26 changes: 3 additions & 23 deletions internal/services/projects.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ func FindProject(

for i := 0; i < len(resp.Projects); i++ {
if resp.Projects[i].Name == projectName {
projectGroups, _ := cmd.Flags().GetString(commonParams.ProjectGroupList)
projectTags, _ := cmd.Flags().GetString(commonParams.ProjectTagList)
projectPrivatePackage, _ := cmd.Flags().GetString(commonParams.ProjecPrivatePackageFlag)
return updateProject(
Expand All @@ -50,7 +49,6 @@ func FindProject(
applicationWrapper,
projectName,
applicationID,
projectGroups,
projectTags,
projectPrivatePackage,
featureFlagsWrapper)
Expand Down Expand Up @@ -112,7 +110,7 @@ func createProject(
if projectGroups != "" {
var groups []string
var groupErr error
groupsMap, groups, groupErr = GetGroupMap(groupsWrapper, projectGroups, nil, featureFlagsWrapper)
groupsMap, groups, groupErr = GetGroupMap(groupsWrapper, projectGroups, nil)
if groupErr != nil {
return "", groupErr
}
Expand Down Expand Up @@ -185,7 +183,6 @@ func updateProject(
applicationsWrapper wrappers.ApplicationsWrapper,
projectName string,
applicationID []string,
projectGroups string,
projectTags string,
projectPrivatePackage string,
featureFlagsWrapper wrappers.FeatureFlagsWrapper,
Expand All @@ -205,8 +202,8 @@ func updateProject(
projModel.RepoURL = resp.Projects[i].RepoURL
}
}
if projectGroups == "" && projectTags == "" && projectPrivatePackage == "" && len(applicationID) == 0 {
logger.PrintIfVerbose("No groups, applicationId or tags to update. Skipping project update.")
if projectTags == "" && projectPrivatePackage == "" && len(applicationID) == 0 {
logger.PrintIfVerbose("No applicationId or tags to update. Skipping project update.")
return projectID, nil
}
if projectPrivatePackage != "" {
Expand Down Expand Up @@ -245,26 +242,9 @@ func updateProject(
}
}

if projectGroups != "" {
err = UpsertProjectGroupsByUpdateFlow(groupsWrapper, &projModel, projectsWrapper, accessManagementWrapper, projModelResp, projectGroups, projectID, projectName, featureFlagsWrapper)
if err != nil {
return projectID, err
}
}
return projectID, nil
}

func UpsertProjectGroupsByUpdateFlow(groupsWrapper wrappers.GroupsWrapper, projModel *wrappers.Project, projectsWrapper wrappers.ProjectsWrapper,
accessManagementWrapper wrappers.AccessManagementWrapper, projModelResp *wrappers.ProjectResponseModel,
projectGroups string, projectID string, projectName string, featureFlagsWrapper wrappers.FeatureFlagsWrapper) error {
groupsMap, groups, groupErr := GetGroupMap(groupsWrapper, projectGroups, projModelResp, featureFlagsWrapper)
if groupErr != nil {
return groupErr
}
projModel.Groups = groups
return UpsertProjectGroups(projModel, projectsWrapper, accessManagementWrapper, projectID, projectName, featureFlagsWrapper, groupsMap)
}

func UpsertProjectGroups(projModel *wrappers.Project, projectsWrapper wrappers.ProjectsWrapper,
accessManagementWrapper wrappers.AccessManagementWrapper, projectID string, projectName string,
featureFlagsWrapper wrappers.FeatureFlagsWrapper, groupsMap []*wrappers.Group) error {
Expand Down
1 change: 0 additions & 1 deletion internal/services/projects_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,6 @@ func Test_updateProject(t *testing.T) {
ttt.args.applicationsWrapper,
ttt.args.projectName,
ttt.args.applicationID,
ttt.args.projectGroups,
ttt.args.projectTags,
ttt.args.projectPrivatePackage,
ttt.args.featureFlagsWrapper)
Expand Down
19 changes: 16 additions & 3 deletions test/integration/scan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"log"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
Expand Down Expand Up @@ -1550,8 +1551,10 @@ func TestScanGeneratingPdfReportWithPdfOptions(t *testing.T) {
//
//}

func TestScanCreateUsingWrongProjectGroups(t *testing.T) {
_, projectName := getRootProject(t)
func TestScanCreate_WhenProjectExists_ShouldNotUpdateGroups(t *testing.T) {
projectID, projectName := getRootProject(t)
project := showProject(t, projectID)
groupsBeforeScanCreate := project.Groups

args := []string{
scanCommand, "create",
Expand All @@ -1561,10 +1564,20 @@ func TestScanCreateUsingWrongProjectGroups(t *testing.T) {
flag(params.PresetName), "Checkmarx Default",
flag(params.BranchFlag), "dummy_branch",
flag(params.ProjectGroupList), "wrong_group",
"--async",
}

err, _ := executeCommand(t, args...)
assertError(t, err, "Failed finding groups")
if err != nil {
assertError(t, err, "running a scan should pass")
}

project = showProject(t, projectID)
groupsAfterScanCreate := project.Groups
if !reflect.DeepEqual(groupsBeforeScanCreate, groupsAfterScanCreate) {
t.Errorf("When project exists, groups before and after scan creation should be equal. Got %v, want %v", groupsAfterScanCreate, groupsBeforeScanCreate)
}

}
func TestScanCreateExploitablePath(t *testing.T) {
_, projectName := getRootProject(t)
Expand Down

0 comments on commit 5756b51

Please sign in to comment.