Skip to content
Open
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
5 changes: 4 additions & 1 deletion commands/curation/curationaudit.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ type CurationAuditCommand struct {
extractPoliciesRegex *regexp.Regexp
workingDirs []string
OriginPath string
invocationDir string
parallelRequests int
dockerImageName string
huggingFaceModel string
Expand Down Expand Up @@ -471,6 +472,7 @@ func (ca *CurationAuditCommand) Run() (err error) {
if err != nil {
return errorutils.CheckError(err)
}
ca.invocationDir = rootDir
if len(ca.workingDirs) > 0 {
defer func() {
if e := errorutils.CheckError(os.Chdir(rootDir)); err == nil {
Expand Down Expand Up @@ -1140,7 +1142,8 @@ func (ca *CurationAuditCommand) getBuildInfoParamsByTech(tech techutils.Technolo
HFWorkingDirectory: ca.OriginPath,
HFProjectName: ca.hfProjectNameHint,
// NuGet params
SolutionFilePath: ca.SolutionFilePath(),
SolutionFilePath: ca.SolutionFilePath(),
SolutionPathBaseDir: ca.invocationDir,
// Uv params
ScriptPath: ca.scriptPath,
}, err
Expand Down
36 changes: 36 additions & 0 deletions commands/curation/curationaudit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2279,6 +2279,29 @@ func TestRunGeneratesAuditIdForHttpDetails(t *testing.T) {
assert.Equal(t, ca.auditId, clientDetails.Headers[utils.CurationAuditIdHeader])
}

// Run records the directory it was started from, even though it changes into each working directory.
func TestRunSetsInvocationDirWithMultipleWorkingDirs(t *testing.T) {
invocationDir := t.TempDir()
firstDir, secondDir := filepath.Join(invocationDir, "first"), filepath.Join(invocationDir, "second")
require.NoError(t, os.Mkdir(firstDir, 0o750))
require.NoError(t, os.Mkdir(secondDir, 0o750))
t.Chdir(invocationDir)
startDir, err := os.Getwd()
require.NoError(t, err)

ca := NewCurationAuditCommand().SetWorkingDirs([]string{firstDir, secondDir})
ca.SetSolutionFilePath(filepath.Join("..", "Parent.sln"))
require.NoError(t, ca.Run())

assert.Equal(t, startDir, ca.invocationDir)
params, err := ca.getBuildInfoParamsByTech(techutils.Nuget)
require.NoError(t, err)
assert.Equal(t, startDir, params.SolutionPathBaseDir)
currentDir, err := os.Getwd()
require.NoError(t, err)
assert.Equal(t, startDir, currentDir, "the working directory is restored after the run")
}

func TestCreateHttpClientDetails_AuditIdHeaderOmittedWhenEmpty(t *testing.T) {
rtAuth, err := (&config.ServerDetails{ArtifactoryUrl: "http://localhost/artifactory/"}).CreateArtAuthConfig()
require.NoError(t, err)
Expand Down Expand Up @@ -8198,3 +8221,16 @@ func TestPackageStatusTableOmitsEmptyLinkColumn(t *testing.T) {
t.Errorf("PrepareTable(rows without links) has a link column:\n%s", got)
}
}

// The curation command changes into every scanned (--working-dirs) directory, so a relative --solution-path
// can only be resolved against the directory the command was run from if it is handed down to the NuGet flow.
func TestGetBuildInfoParamsByTechSolutionPath(t *testing.T) {
ca := NewCurationAuditCommand()
ca.SetSolutionFilePath(filepath.Join("..", "..", "Profitect.WebApi.sln"))
ca.invocationDir = filepath.Join("repo", "Development", "Profitect")

params, err := ca.getBuildInfoParamsByTech(techutils.Nuget)
require.NoError(t, err)
assert.Equal(t, filepath.Join("..", "..", "Profitect.WebApi.sln"), params.SolutionFilePath)
assert.Equal(t, filepath.Join("repo", "Development", "Profitect"), params.SolutionPathBaseDir)
}
5 changes: 5 additions & 0 deletions sca/bom/buildinfo/technologies/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,12 @@ type BuildInfoBomGeneratorParams struct {
// name when auditing multiple --working-dirs entries that share a basename.
HFProjectName string
// NuGet params
// Path to the '.sln'/'.slnx' file to use ('--solution-path'). It may point outside the scanned directory.
// A relative path is resolved against the scanned directory first, then against SolutionPathBaseDir.
SolutionFilePath string
// The directory the command was run from, used as a fallback base for a relative SolutionFilePath.
// It is needed because the command may change into each scanned (working) directory. Optional.
SolutionPathBaseDir string
// Uv params
ScriptPath string
}
Expand Down
119 changes: 107 additions & 12 deletions sca/bom/buildinfo/technologies/nuget/nuget.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,28 +52,32 @@ func BuildDependencyTree(params technologies.BuildInfoBomGeneratorParams) (depen
if err != nil {
return
}
if p := params.SolutionFilePath; p != "" {
if info, statErr := os.Stat(filepath.Join(wd, filepath.Base(p))); statErr != nil || info.IsDir() {
err = fmt.Errorf("--solution-path %q: no solution file named %q in %s "+
"(the flag is resolved relative to the scanned directory)", p, filepath.Base(p), wd)
// Load and restore from the solution file's own directory (may be a parent of the scanned one), or the scanned directory if none was given.
solutionDir := wd
if params.SolutionFilePath != "" {
var solutionFile string
if solutionFile, err = ResolveSolutionFilePath(params.SolutionFilePath, wd, params.SolutionPathBaseDir); err != nil {
return
}
solutionDir = filepath.Dir(solutionFile)
// Use the resolved path below, so a path written with '\' on Linux/macOS yields the right file name.
params.SolutionFilePath = solutionFile
}
sol, err := solution.Load(wd, solutionFileName(params.SolutionFilePath), params.ExclusionPattern, log.Logger)
sol, err := solution.Load(solutionDir, solutionFileName(params.SolutionFilePath), params.ExclusionPattern, log.Logger)
if err != nil && !strings.Contains(err.Error(), globalPackagesNotFoundErrorMessage) {
// In older NuGet projects that utilize NuGet Cli and package.config, if the project is not installed, the solution.Load function raises an error because it cannot find global package paths.
// This issue is resolved by executing the 'nuget restore' command followed by running solution.Load again. Therefore, in this scenario, we need to proceed with this process.
return
}

installRequired, err := isInstallRequired(params, sol, params.SkipAutoInstall, wd)
installRequired, err := isInstallRequired(params, sol, params.SkipAutoInstall, solutionDir)
if err != nil {
return
}

var buildInfo *entities.BuildInfo
if installRequired {
buildInfo, err = restoreInTempDirAndGetBuildInfo(params, wd, params.ExclusionPattern)
buildInfo, err = restoreInTempDirAndGetBuildInfo(params, solutionDir, params.ExclusionPattern, scannedSubDirOf(solutionDir, wd))
} else {
buildInfo, err = sol.BuildInfo("", log.Logger)
}
Expand All @@ -85,7 +89,83 @@ func BuildDependencyTree(params technologies.BuildInfoBomGeneratorParams) (depen
return
}

func restoreInTempDirAndGetBuildInfo(params technologies.BuildInfoBomGeneratorParams, wd string, exclusionPattern string) (buildInfo *entities.BuildInfo, err error) {
// ResolveSolutionFilePath returns the absolute path of the '--solution-path' file: used as is if absolute,
// otherwise the first existing match against searchDirs in order (scanned directory, then the directory the command was run from).
func ResolveSolutionFilePath(solutionPath string, searchDirs ...string) (string, error) {
if filepath.Separator == '/' {
solutionPath = strings.ReplaceAll(solutionPath, `\`, "/")
}
var candidates []string
if filepath.IsAbs(solutionPath) {
candidates = append(candidates, filepath.Clean(solutionPath))
} else {
seen := datastructures.MakeSet[string]()
for _, dir := range searchDirs {
if dir == "" || seen.Exists(dir) {
continue
}
seen.Add(dir)
candidates = append(candidates, filepath.Join(dir, solutionPath))
}
}
var invalidCandidate string
for _, candidate := range candidates {
info, err := os.Stat(candidate)
if err != nil {
continue
}
if !info.IsDir() && isSolutionFile(candidate) {
return filepath.Abs(candidate)
}
if invalidCandidate == "" {
invalidCandidate = candidate
}
}
if invalidCandidate != "" {
if absPath, err := filepath.Abs(invalidCandidate); err == nil {
invalidCandidate = absPath
}
if info, err := os.Stat(invalidCandidate); err == nil && info.IsDir() {
return "", fmt.Errorf("--solution-path %q: %q is a directory, not a solution file (.sln or .slnx)", solutionPath, invalidCandidate)
}
return "", fmt.Errorf("--solution-path %q: %q is not a solution file (.sln or .slnx)", solutionPath, invalidCandidate)
}
scannedDir := ""
for _, dir := range searchDirs {
if dir != "" {
scannedDir = dir
break
}
}
return "", fmt.Errorf("--solution-path %q: no solution file named %q in %s "+
"(the flag is resolved relative to the scanned directory)", solutionPath, filepath.Base(solutionPath), scannedDir)
}

// scannedSubDirOf returns the location of the scanned directory inside solutionDir, or "" if it is the same or not inside it.
// Real paths are compared, so a solution path that goes through a symlink still locates the scanned directory.
func scannedSubDirOf(solutionDir, scannedDir string) string {
rel, err := filepath.Rel(realPath(solutionDir), realPath(scannedDir))
if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return ""
}
return rel
}

func isSolutionFile(path string) bool {
ext := filepath.Ext(path)
return strings.EqualFold(ext, ".sln") || strings.EqualFold(ext, ".slnx")
}

// realPath resolves symlinks, falling back to the path as is if that fails.
func realPath(path string) string {
if resolved, err := filepath.EvalSymlinks(path); err == nil {
return resolved
}
return path
}

// Restores a temporary copy of dir (the scanned or the solution's directory); scannedSubDir is the scanned directory's location inside dir, if any.
func restoreInTempDirAndGetBuildInfo(params technologies.BuildInfoBomGeneratorParams, dir string, exclusionPattern string, scannedSubDir string) (buildInfo *entities.BuildInfo, err error) {
var tmpWd string
tmpWd, err = fileutils.CreateTempDir()
if err != nil {
Expand All @@ -97,14 +177,14 @@ func restoreInTempDirAndGetBuildInfo(params technologies.BuildInfoBomGeneratorPa
}()

// Exclude Visual Studio inner directory since it is not necessary for the scan process and may cause race condition.
err = biutils.CopyDir(wd, tmpWd, true, []string{technologies.DotVsRepoSuffix})
err = biutils.CopyDir(dir, tmpWd, true, []string{technologies.DotVsRepoSuffix})
if err != nil {
err = fmt.Errorf("failed copying project to temp dir: %w", err)
return
}

log.Info("Dependencies sources were not detected nor 'install' command provided. Running 'restore' command")
sol, err := runDotnetRestoreAndLoadSolution(params, tmpWd, exclusionPattern, params.InsecureTls)
sol, err := runDotnetRestoreAndLoadSolution(params, tmpWd, scannedSubDir, exclusionPattern, params.InsecureTls)
if err != nil {
return
}
Expand All @@ -127,11 +207,11 @@ func isInstallRequired(params technologies.BuildInfoBomGeneratorParams, sol solu
return installRequired, nil
}

func runDotnetRestoreAndLoadSolution(params technologies.BuildInfoBomGeneratorParams, tmpWd, exclusionPattern string, allowInsecureConnections bool) (sol solution.Solution, err error) {
func runDotnetRestoreAndLoadSolution(params technologies.BuildInfoBomGeneratorParams, tmpWd, scannedSubDir, exclusionPattern string, allowInsecureConnections bool) (sol solution.Solution, err error) {
toolName := params.InstallCommandName
if toolName == "" {
// Determine if the project is a NuGet or .NET project
toolName, err = getProjectToolName(tmpWd)
toolName, err = detectProjectToolName(tmpWd, scannedSubDir)
if err != nil {
err = fmt.Errorf("failed while checking for the project's tool type: %s", err.Error())
return
Expand Down Expand Up @@ -180,6 +260,21 @@ func solutionFileName(solutionFilePath string) string {
return filepath.Base(solutionFilePath)
}

// detectProjectToolName detects the tool from the scanned directory (root/scannedSubDir) first, so unrelated projects
// elsewhere under root can't change it, and falls back to the whole root if nothing is found there.
func detectProjectToolName(root, scannedSubDir string) (string, error) {
if scannedDir := filepath.Join(root, scannedSubDir); scannedSubDir != "" {
// Only look in the scanned directory if it exists in the copy.
if info, statErr := os.Stat(scannedDir); statErr == nil && info.IsDir() {
if toolName, detectErr := getProjectToolName(scannedDir); detectErr == nil {
return toolName, nil
}
}
log.Debug(fmt.Sprintf("The tool type was not detected in the scanned directory '%s', looking in the entire solution directory", scannedSubDir))
}
return getProjectToolName(root)
}

// Detects if the project is utilizing either .NET CLI or NuGet CLI, prioritizing .NET CLI.
// Note: For multi-module projects, only one of these tools can be identified and will be uniformly applied across all modules.
func getProjectToolName(wd string) (toolName string, err error) {
Expand Down
Loading
Loading