diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNet.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNet.cs index e93a29336126..e02d157dc620 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNet.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNet.cs @@ -80,11 +80,6 @@ private string GetRestoreArgs(RestoreSettings restoreSettings) args += $" /p:TargetFrameworkRootPath=\"{path}\" /p:NetCoreTargetingPackRoot=\"{path}\" /p:AllowMissingPrunePackageData=true"; } - if (restoreSettings.PathToNugetConfig != null) - { - args += $" --configfile \"{restoreSettings.PathToNugetConfig}\""; - } - if (restoreSettings.ForceReevaluation) { args += " --force"; diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/FeedManager.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/FeedManager.cs index b9b5e16afd85..99568fa9ce19 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/FeedManager.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/FeedManager.cs @@ -24,22 +24,79 @@ internal sealed partial class FeedManager : IDisposable private readonly FileProvider fileProvider; private readonly DependabotProxy? dependabotProxy; private readonly DependencyDirectory emptyPackageDirectory; + private readonly ImmutableHashSet privateRegistryFeeds; - public ImmutableHashSet PrivateRegistryFeeds { get; } public bool HasPrivateRegistryFeeds { get; } public bool CheckNugetFeedResponsiveness { get; } = EnvironmentVariables.GetBooleanOptOut(EnvironmentVariableNames.CheckNugetFeedResponsiveness); + private readonly Lazy> lazyExplicitFeeds; + + /// + /// Gets the list of NuGet feeds that are explicitly configured + /// - NuGet configuration files. + /// - Private package registries that are configured for C#. + /// + public ImmutableHashSet ExplicitFeeds => lazyExplicitFeeds.Value; + + private readonly Lazy> lazyAllFeeds; + + /// + /// Gets the list of all NuGet feeds that are configured in the environment. That is + /// - Explicit feeds + /// - Inherited feeds from the machine and environment (if not explicitly disabled by a + /// root directory NuGet configuration). + /// + public ImmutableHashSet AllFeeds => lazyAllFeeds.Value; + + /// + /// Gets the list of inherited NuGet feeds that are configured in the environment. + /// + public ImmutableHashSet InheritedFeeds => AllFeeds.Except(ExplicitFeeds).ToImmutableHashSet(); + + private readonly Lazy<(bool, ImmutableHashSet)> lazyReachableExplicitFeeds; + + /// + /// Gets whether there was a timeout when checking the reachability of the explicitly configured NuGet feeds. + /// + public bool ExplicitFeedTimeout => lazyReachableExplicitFeeds.Value.Item1; + + /// + /// Gets the list of reachable NuGet feeds that are explicitly configured. + /// + public ImmutableHashSet ReachableExplicitFeeds => lazyReachableExplicitFeeds.Value.Item2; + + private readonly Lazy> lazyReachableFeeds; + /// + /// Gets the list of reachable NuGet feeds that are configured in the environment. + /// + public ImmutableHashSet ReachableFeeds => lazyReachableFeeds.Value; + public FeedManager(ILogger logger, IDotNet dotnet, DependabotProxy? dependabotProxy, FileProvider fileProvider) { this.logger = logger; this.dotnet = dotnet; this.dependabotProxy = dependabotProxy; this.fileProvider = fileProvider; - PrivateRegistryFeeds = dependabotProxy?.RegistryURLs.ToImmutableHashSet() ?? []; - HasPrivateRegistryFeeds = PrivateRegistryFeeds.Count > 0; + privateRegistryFeeds = dependabotProxy?.RegistryURLs.ToImmutableHashSet() ?? []; + HasPrivateRegistryFeeds = privateRegistryFeeds.Count > 0; emptyPackageDirectory = new DependencyDirectory("empty", "empty package", logger); + + lazyExplicitFeeds = new Lazy>(GetExplicitFeeds); + lazyAllFeeds = new Lazy>(GetAllFeeds); + lazyReachableExplicitFeeds = new Lazy<(bool, ImmutableHashSet)>(() => + { + var timeout = CheckSpecifiedFeeds(ExplicitFeeds, out var reachableFeeds); + return (timeout, reachableFeeds); + }); + lazyReachableFeeds = new Lazy>(() => + { + // Inherited feeds should only be used, if they are indeed reachable (as they may be environment specific). + CheckSpecifiedFeeds(InheritedFeeds, out var reachableInheritedFeeds); + return ReachableExplicitFeeds.Union(reachableInheritedFeeds).ToImmutableHashSet(); + }); } + private string? GetDirectoryName(string path) { try @@ -88,12 +145,12 @@ private IEnumerable GetFeedsFromFolder(string folderPath) => private IEnumerable GetFeedsFromNugetConfig(string nugetConfigPath) => GetFeeds(() => dotnet.GetNugetFeeds(nugetConfigPath)); - private string FeedsToRestoreArgument(IEnumerable feeds) + public string FeedsToRestoreArgument(IEnumerable feeds, string sourceArgumentPrefix) { - // If there are no feeds, we want to override any default feeds that `dotnet restore` would use by passing a dummy source argument. + // If there are no feeds, we want to override any default feeds that `restore` would use by passing a dummy source argument. if (!feeds.Any()) { - return $" -s \"{emptyPackageDirectory.DirInfo.FullName}\""; + return $" {sourceArgumentPrefix} \"{emptyPackageDirectory.DirInfo.FullName}\""; } // Add package sources. If any are present, they override all sources specified in @@ -101,21 +158,62 @@ private string FeedsToRestoreArgument(IEnumerable feeds) var feedArgs = new StringBuilder(); foreach (var feed in feeds) { - feedArgs.Append($" -s \"{feed}\""); + feedArgs.Append($" {sourceArgumentPrefix} \"{feed}\""); } return feedArgs.ToString(); } + private IEnumerable FeedsToUseAux(HashSet feedsToConsider) + { + if (HasPrivateRegistryFeeds) + { + feedsToConsider.UnionWith(privateRegistryFeeds); + } + + var feedsToUse = CheckNugetFeedResponsiveness + ? feedsToConsider.Where(ReachableFeeds.Contains) + : feedsToConsider; + + return feedsToUse; + } + /// /// Constructs the list of NuGet sources to use for this restore. /// (1) Use the feeds we get from `dotnet nuget list source` /// (2) Use private registries, if they are configured /// + /// Path to project/solution/packages.config + /// The list of NuGet feeds to use for this restore. + public IEnumerable FeedsToUse(string path) + { + // Find the path specific feeds. + var folder = GetDirectoryName(path); + var feedsToConsider = folder is not null ? GetFeedsFromFolder(folder).ToHashSet() : new HashSet(); + + return FeedsToUseAux(feedsToConsider); + } + + public IEnumerable FeedsToUseFromConfig(string config) + { + var feedsToConsider = GetFeedsFromNugetConfig(config).ToHashSet(); + + return FeedsToUseAux(feedsToConsider); + } + + public string FeedsToDotnetRestoreArgument(IEnumerable feeds) + { + return FeedsToRestoreArgument(feeds, "-s"); + } + + /// + /// Constructs the list of NuGet sources to use for dotnet restore. + /// (1) Use the feeds we get from `dotnet nuget list source` + /// (2) Use private registries, if they are configured + /// /// Path to project/solution - /// The set of reachable NuGet feeds. /// A string representing the NuGet sources argument for the restore command. - public string? MakeRestoreSourcesArgument(string path, HashSet reachableFeeds) + public string? MakeDotnetRestoreSourcesArgument(string path) { // Do not construct a set of explicit NuGet sources to use for restore. if (!CheckNugetFeedResponsiveness && !HasPrivateRegistryFeeds) @@ -123,20 +221,9 @@ private string FeedsToRestoreArgument(IEnumerable feeds) return null; } - // Find the path specific feeds. - var folder = GetDirectoryName(path); - var feedsToConsider = folder is not null ? GetFeedsFromFolder(folder).ToHashSet() : new HashSet(); - - if (HasPrivateRegistryFeeds) - { - feedsToConsider.UnionWith(PrivateRegistryFeeds); - } + var feedsToUse = FeedsToUse(path); - var feedsToUse = CheckNugetFeedResponsiveness - ? feedsToConsider.Where(reachableFeeds.Contains) - : feedsToConsider; - - return FeedsToRestoreArgument(feedsToUse); + return FeedsToDotnetRestoreArgument(feedsToUse); } private (int initialTimeout, int tryCount) GetFeedRequestSettings(bool isFallback) @@ -256,7 +343,7 @@ private HashSet GetExcludedFeeds() /// True if there is a timeout when trying to reach the feeds (excluding any feeds that are configured /// to be excluded from the check) or false otherwise. /// - public bool CheckSpecifiedFeeds(HashSet feeds, out HashSet reachableFeeds) + private bool CheckSpecifiedFeeds(ImmutableHashSet feeds, out ImmutableHashSet reachableFeeds) { // Exclude any feeds from the feed check that are configured by the corresponding environment variable. // These feeds are always assumed to be reachable. @@ -272,10 +359,10 @@ public bool CheckSpecifiedFeeds(HashSet feeds, out HashSet reach return true; }).ToHashSet(); - reachableFeeds = GetReachableNuGetFeeds(feedsToCheck, isFallback: false, out var isTimeout).ToHashSet(); + var reachable = GetReachableNuGetFeeds(feedsToCheck, isFallback: false, out var isTimeout); // Always consider feeds excluded for the reachability check as reachable. - reachableFeeds.UnionWith(feeds.Where(feed => excludedFeeds.Contains(feed))); + reachableFeeds = reachable.Union(feeds.Where(feed => excludedFeeds.Contains(feed))).ToImmutableHashSet(); return isTimeout; } @@ -327,7 +414,7 @@ private List GetReachableNuGetFeeds(HashSet feedsToCheck, bool i return reachableFeeds; } - public List GetReachableFallbackNugetFeeds(HashSet? feedsFromNugetConfigs) + public List GetReachableFallbackNugetFeeds(ImmutableHashSet? feedsFromNugetConfigs) { var fallbackFeeds = EnvironmentVariables.GetURLs(EnvironmentVariableNames.FallbackNugetFeeds).ToHashSet(); if (fallbackFeeds.Count == 0) @@ -350,7 +437,7 @@ public List GetReachableFallbackNugetFeeds(HashSet? feedsFromNug return GetReachableNuGetFeeds(fallbackFeeds, isFallback: true, out var _); } - public (HashSet explicitFeeds, HashSet allFeeds) GetAllFeeds() + private ImmutableHashSet GetExplicitFeeds() { var nugetConfigs = fileProvider.NugetConfigs; @@ -372,14 +459,21 @@ public List GetReachableFallbackNugetFeeds(HashSet? feedsFromNug // in addition to the ones that are configured in `nuget.config` files. if (HasPrivateRegistryFeeds) { - logger.LogInfo($"Found {PrivateRegistryFeeds.Count} private registry feeds configured for C#: {string.Join(", ", PrivateRegistryFeeds.OrderBy(f => f))}"); - explicitFeeds.UnionWith(PrivateRegistryFeeds); + logger.LogInfo($"Found {privateRegistryFeeds.Count} private registry feeds configured for C#: {string.Join(", ", privateRegistryFeeds.OrderBy(f => f))}"); + explicitFeeds.UnionWith(privateRegistryFeeds); } + return explicitFeeds.ToImmutableHashSet(); + } + + private ImmutableHashSet GetAllFeeds() + { + var nugetConfigs = fileProvider.NugetConfigs; + HashSet allFeeds = []; // Add all explicitFeeds to the set of all feeds. - allFeeds.UnionWith(explicitFeeds); + allFeeds.UnionWith(ExplicitFeeds); // Obtain the list of feeds from the root source directory. // If a NuGet file is present it will be respected, otherwise we will just get the machine/environment specific feeds. @@ -399,7 +493,7 @@ public List GetReachableFallbackNugetFeeds(HashSet? feedsFromNug logger.LogInfo($"Found {allFeeds.Count} NuGet feeds (with inherited ones) in nuget.config files: {string.Join(", ", allFeeds.OrderBy(f => f))}"); - return (explicitFeeds, allFeeds); + return allFeeds.ToImmutableHashSet(); } [GeneratedRegex(@"^E\s(.*)$", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline)] diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/IDotNet.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/IDotNet.cs index d14dee506524..394a05e9e596 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/IDotNet.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/IDotNet.cs @@ -17,7 +17,7 @@ public interface IDotNet IList GetNugetFeedsFromFolder(string folderPath); } - public record class RestoreSettings(string File, string PackageDirectory, bool ForceDotnetRefAssemblyFetching, string? NugetSources = null, string? PathToNugetConfig = null, bool ForceReevaluation = false, bool TargetWindows = false); + public record class RestoreSettings(string File, string PackageDirectory, bool ForceDotnetRefAssemblyFetching, string? NugetSources = null, bool ForceReevaluation = false, bool TargetWindows = false); public partial record class RestoreResult(bool Success, IList Output) { diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs index eb6ddd4e69bf..72d9d3400cfa 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs @@ -110,59 +110,48 @@ public HashSet Restore() logger.LogInfo($"Checking NuGet feed responsiveness: {feedManager.CheckNugetFeedResponsiveness}"); compilationInfoContainer.CompilationInfos.Add(("NuGet feed responsiveness checked", feedManager.CheckNugetFeedResponsiveness ? "1" : "0")); - HashSet explicitFeeds = []; - HashSet reachableFeeds = []; + EmitNugetConfigDiagnostics(); - try - { - EmitNugetConfigDiagnostics(); + // Find feeds that are configured in NuGet.config files and divide them into ones that + // are explicitly configured for the project or by a private registry, and "all feeds" + // (including inherited ones) from other locations on the host outside of the working directory. + var explicitFeeds = feedManager.ExplicitFeeds; - // Find feeds that are configured in NuGet.config files and divide them into ones that - // are explicitly configured for the project or by a private registry, and "all feeds" - // (including inherited ones) from other locations on the host outside of the working directory. - (explicitFeeds, var allFeeds) = feedManager.GetAllFeeds(); + if (feedManager.CheckNugetFeedResponsiveness) + { + var inheritedFeeds = feedManager.InheritedFeeds; - if (feedManager.CheckNugetFeedResponsiveness) + if (inheritedFeeds.Count > 0) { - var inheritedFeeds = allFeeds.Except(explicitFeeds).ToHashSet(); - - if (inheritedFeeds.Count > 0) - { - compilationInfoContainer.CompilationInfos.Add(("Inherited NuGet feed count", inheritedFeeds.Count.ToString())); - } - - var timeout = feedManager.CheckSpecifiedFeeds(explicitFeeds, out var reachableExplicitFeeds); - reachableFeeds.UnionWith(reachableExplicitFeeds); - - var allExplicitReachable = explicitFeeds.Count == reachableExplicitFeeds.Count; - EmitUnreachableFeedsDiagnostics(allExplicitReachable); + compilationInfoContainer.CompilationInfos.Add(("Inherited NuGet feed count", inheritedFeeds.Count.ToString())); + } - if (timeout) - { - // If we experience a timeout, we use this fallback. - // todo: we could also check the reachability of the inherited nuget feeds, but to use those in the fallback we would need to handle authentication too. - var unresponsiveMissingPackageLocation = DownloadMissingPackagesFromSpecificFeeds([], explicitFeeds); - return unresponsiveMissingPackageLocation is null - ? [] - : [unresponsiveMissingPackageLocation]; - } + var allExplicitReachable = explicitFeeds.Count == feedManager.ReachableExplicitFeeds.Count; + EmitUnreachableFeedsDiagnostics(allExplicitReachable); - // Inherited feeds should only be used, if they are indeed reachable (as they may be environment specific). - feedManager.CheckSpecifiedFeeds(inheritedFeeds, out var reachableInheritedFeeds); - reachableFeeds.UnionWith(reachableInheritedFeeds); + if (feedManager.ExplicitFeedTimeout) + { + // If we experience a timeout, we use this fallback. + // todo: we could also check the reachability of the inherited nuget feeds, but to use those in the fallback we would need to handle authentication too. + var unresponsiveMissingPackageLocation = DownloadMissingPackagesFromSpecificFeeds([], explicitFeeds); + return unresponsiveMissingPackageLocation is null + ? [] + : [unresponsiveMissingPackageLocation]; } - using (var packagesConfigRestore = PackagesConfigRestoreFactory.Create(fileProvider, legacyPackageDirectory, logger, feedManager.IsDefaultFeedReachable)) - { - var count = packagesConfigRestore.InstallPackages(); + } - if (packagesConfigRestore.PackageCount > 0) - { - compilationInfoContainer.CompilationInfos.Add(("packages.config files", packagesConfigRestore.PackageCount.ToString())); - compilationInfoContainer.CompilationInfos.Add(("Successfully restored packages.config files", count.ToString())); - } + try + { + var packagesConfigRestore = PackagesConfigRestoreFactory.Create(fileProvider, legacyPackageDirectory, logger, feedManager); + var count = packagesConfigRestore.InstallPackages(); + if (packagesConfigRestore.PackageCount > 0) + { + compilationInfoContainer.CompilationInfos.Add(("packages.config files", packagesConfigRestore.PackageCount.ToString())); + compilationInfoContainer.CompilationInfos.Add(("Successfully restored packages.config files", count.ToString())); } + var nugetPackageDlls = legacyPackageDirectory.DirInfo.GetFiles("*.dll", new EnumerationOptions { RecurseSubdirectories = true }); var nugetPackageDllPaths = nugetPackageDlls.Select(f => f.FullName).ToHashSet(); var excludedPaths = nugetPackageDllPaths @@ -192,9 +181,9 @@ public HashSet Restore() } // Restore project dependencies with `dotnet restore`. - var restoredProjects = RestoreSolutions(reachableFeeds, out var container); + var restoredProjects = RestoreSolutions(out var container); var projects = fileProvider.Projects.Except(restoredProjects); - RestoreProjects(projects, reachableFeeds, out var containers); + RestoreProjects(projects, out var containers); var dependencies = containers.Flatten(container); @@ -226,7 +215,7 @@ public HashSet Restore() /// Populates dependencies with the relevant dependencies from the assets files generated by the restore. /// Returns a list of projects that are up to date with respect to restore. /// - private IEnumerable RestoreSolutions(HashSet reachableFeeds, out DependencyContainer dependencies) + private IEnumerable RestoreSolutions(out DependencyContainer dependencies) { var successCount = 0; var nugetSourceFailures = 0; @@ -239,7 +228,7 @@ private IEnumerable RestoreSolutions(HashSet reachableFeeds, out var projects = fileProvider.Solutions.SelectMany(solution => { logger.LogInfo($"Restoring solution {solution}..."); - var nugetSources = feedManager.MakeRestoreSourcesArgument(solution, reachableFeeds); + var nugetSources = feedManager.MakeDotnetRestoreSourcesArgument(solution); var res = dotnet.Restore(new(solution, PackageDirectory.DirInfo.FullName, ForceDotnetRefAssemblyFetching: true, NugetSources: nugetSources, TargetWindows: isWindows)); if (res.Success) { @@ -270,8 +259,7 @@ private IEnumerable RestoreSolutions(HashSet reachableFeeds, out /// Populates dependencies with the relative paths to the assets files generated by the restore. /// /// A list of paths to project files. - /// The set of reachable NuGet feeds. - private void RestoreProjects(IEnumerable projects, HashSet reachableFeeds, out ConcurrentBag dependencies) + private void RestoreProjects(IEnumerable projects, out ConcurrentBag dependencies) { var successCount = 0; var nugetSourceFailures = 0; @@ -288,7 +276,7 @@ private void RestoreProjects(IEnumerable projects, HashSet reach foreach (var project in projectGroup) { logger.LogInfo($"Restoring project {project}..."); - var nugetSources = feedManager.MakeRestoreSourcesArgument(project, reachableFeeds); + var nugetSources = feedManager.MakeDotnetRestoreSourcesArgument(project); var res = dotnet.Restore(new(project, PackageDirectory.DirInfo.FullName, ForceDotnetRefAssemblyFetching: true, NugetSources: nugetSources, TargetWindows: isWindows)); assets.AddDependenciesRange(res.AssetsFilePaths); lock (sync) @@ -315,7 +303,7 @@ private void RestoreProjects(IEnumerable projects, HashSet reach compilationInfoContainer.CompilationInfos.Add(("Failed project restore with missing package error", nugetMissingPackageFailures.ToString())); } - private AssemblyLookupLocation? DownloadMissingPackagesFromSpecificFeeds(IEnumerable usedPackageNames, HashSet? feedsFromNugetConfigs) + private AssemblyLookupLocation? DownloadMissingPackagesFromSpecificFeeds(IEnumerable usedPackageNames, ImmutableHashSet? feedsFromNugetConfigs) { var reachableFallbackFeeds = feedManager.GetReachableFallbackNugetFeeds(feedsFromNugetConfigs); compilationInfoContainer.CompilationInfos.Add(("Reachable fallback NuGet feed count", reachableFallbackFeeds.Count.ToString())); @@ -362,10 +350,18 @@ private void RestoreProjects(IEnumerable projects, HashSet reach } logger.LogInfo($"Found {notYetDownloadedPackages.Count} packages that are not yet restored"); - using var tempDir = new TemporaryDirectory(ComputeTempDirectoryPath("nugetconfig"), "generated nuget config", logger); - var nugetConfig = fallbackNugetFeeds is null - ? GetNugetConfig() - : CreateFallbackNugetConfig(fallbackNugetFeeds, tempDir.DirInfo.FullName); + + IEnumerable feeds = []; + if (fallbackNugetFeeds is not null) + { + feeds = fallbackNugetFeeds; + } + else if (GetNugetConfig() is string config) + { + feeds = feedManager.FeedsToUseFromConfig(config); + } + + var nugetSources = feedManager.FeedsToDotnetRestoreArgument(feeds); compilationInfoContainer.CompilationInfos.Add(("Fallback nuget restore", notYetDownloadedPackages.Count.ToString())); @@ -374,7 +370,7 @@ private void RestoreProjects(IEnumerable projects, HashSet reach Parallel.ForEach(notYetDownloadedPackages, new ParallelOptions { MaxDegreeOfParallelism = DependencyManager.Threads }, package => { - var success = TryRestorePackageManually(package.Name, nugetConfig, package.PackageReferenceSource, tryWithoutNugetConfig: fallbackNugetFeeds is null); + var success = TryRestorePackageManually(package.Name, nugetSources, package.PackageReferenceSource, tryWithoutNugetConfig: fallbackNugetFeeds is null); if (!success) { return; @@ -391,27 +387,6 @@ private void RestoreProjects(IEnumerable projects, HashSet reach return missingPackageDirectory.DirInfo.FullName; } - private string? CreateFallbackNugetConfig(IEnumerable fallbackNugetFeeds, string folderPath) - { - var sb = new StringBuilder(); - fallbackNugetFeeds.ForEach((feed, index) => sb.AppendLine($"")); - - var nugetConfigPath = Path.Join(folderPath, "nuget.config"); - logger.LogInfo($"Creating fallback nuget.config file {nugetConfigPath}."); - File.WriteAllText(nugetConfigPath, - $""" - - - - - {sb} - - - """); - - return nugetConfigPath; - } - private string? GetNugetConfig() { var nugetConfigs = fileProvider.NugetConfigs; @@ -427,6 +402,7 @@ private void RestoreProjects(IEnumerable projects, HashSet reach } else { + // TODO: This could cause non-deterministic behaviror, if the first config file is different between runs. nugetConfig = nugetConfigs.FirstOrDefault(); } @@ -501,7 +477,7 @@ private static IEnumerable GetRestoredPackageDirectoryNames(DirectoryInf .Select(d => Path.GetFileName(d).ToLowerInvariant()); } - private bool TryRestorePackageManually(string package, string? nugetConfig = null, PackageReferenceSource packageReferenceSource = PackageReferenceSource.SdkCsProj, + private bool TryRestorePackageManually(string package, string? nugetSources = null, PackageReferenceSource packageReferenceSource = PackageReferenceSource.SdkCsProj, bool tryWithoutNugetConfig = true, bool tryPrereleaseVersion = true) { logger.LogInfo($"Restoring package {package}..."); @@ -524,17 +500,17 @@ private bool TryRestorePackageManually(string package, string? nugetConfig = nul return false; } - var res = TryRestorePackageManually(package, nugetConfig, tempDir, tryPrereleaseVersion); + var res = TryRestorePackageManually(package, nugetSources, tempDir, tryPrereleaseVersion); if (res.Success) { return true; } - if (tryWithoutNugetConfig && res.HasNugetPackageSourceError && nugetConfig is not null) + if (tryWithoutNugetConfig && res.HasNugetPackageSourceError && nugetSources is not null && !feedManager.CheckNugetFeedResponsiveness) { logger.LogDebug($"Trying to restore '{package}' without nuget.config."); // Restore could not be completed because the listed source is unavailable. Try without the nuget.config: - res = TryRestorePackageManually(package, nugetConfig: null, tempDir, tryPrereleaseVersion); + res = TryRestorePackageManually(package, nugetSources: null, tempDir, tryPrereleaseVersion); if (res.Success) { return true; @@ -545,16 +521,16 @@ private bool TryRestorePackageManually(string package, string? nugetConfig = nul return false; } - private RestoreResult TryRestorePackageManually(string package, string? nugetConfig, TemporaryDirectory tempDir, bool tryPrereleaseVersion) + private RestoreResult TryRestorePackageManually(string package, string? nugetSources, TemporaryDirectory tempDir, bool tryPrereleaseVersion) { - var res = dotnet.Restore(new(tempDir.DirInfo.FullName, missingPackageDirectory.DirInfo.FullName, ForceDotnetRefAssemblyFetching: false, PathToNugetConfig: nugetConfig, ForceReevaluation: true)); + var res = dotnet.Restore(new(tempDir.DirInfo.FullName, missingPackageDirectory.DirInfo.FullName, ForceDotnetRefAssemblyFetching: false, NugetSources: nugetSources, ForceReevaluation: true)); if (!res.Success && tryPrereleaseVersion && res.HasNugetNoStablePackageVersionError) { logger.LogDebug($"Failed to restore nuget package {package} because no stable version was found."); TryChangePackageVersion(tempDir.DirInfo, "*-*"); - res = dotnet.Restore(new(tempDir.DirInfo.FullName, missingPackageDirectory.DirInfo.FullName, ForceDotnetRefAssemblyFetching: false, PathToNugetConfig: nugetConfig, ForceReevaluation: true)); + res = dotnet.Restore(new(tempDir.DirInfo.FullName, missingPackageDirectory.DirInfo.FullName, ForceDotnetRefAssemblyFetching: false, NugetSources: nugetSources, ForceReevaluation: true)); if (!res.Success) { TryChangePackageVersion(tempDir.DirInfo, "*"); diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/PackagesConfigRestorer.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/PackagesConfigRestorer.cs index 51cd27555787..05c10cfb2bf3 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/PackagesConfigRestorer.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/PackagesConfigRestorer.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; @@ -7,7 +8,7 @@ namespace Semmle.Extraction.CSharp.DependencyFetching { - internal interface IPackagesConfigRestore : IDisposable + internal interface IPackagesConfigRestore { /// /// The number of packages.config files found in the source tree. @@ -33,11 +34,11 @@ internal interface IPackagesConfigRestore : IDisposable /// internal class PackagesConfigRestoreFactory { - public static IPackagesConfigRestore Create(FileProvider fileProvider, DependencyDirectory packageDirectory, Semmle.Util.Logging.ILogger logger, Func useDefaultFeed) + public static IPackagesConfigRestore Create(FileProvider fileProvider, DependencyDirectory packageDirectory, Semmle.Util.Logging.ILogger logger, FeedManager feedManager) { if (SystemBuildActions.Instance.IsWindows() || SystemBuildActions.Instance.IsMonoInstalled()) { - return new NugetExeWrapper(fileProvider, packageDirectory, logger, useDefaultFeed); + return new NugetExeWrapper(fileProvider, packageDirectory, logger, feedManager); } return new NoOpPackagesConfig(fileProvider.PackagesConfigs, logger); @@ -55,8 +56,6 @@ private class NugetExeWrapper : IPackagesConfigRestore public int PackageCount => fileProvider.PackagesConfigs.Count; - private readonly string? backupNugetConfig; - private readonly string? nugetConfigPath; private readonly FileProvider fileProvider; /// @@ -65,57 +64,28 @@ private class NugetExeWrapper : IPackagesConfigRestore /// so as to not trample the source tree. /// private readonly DependencyDirectory packageDirectory; + private readonly FeedManager feedManager; private bool IsWindows => SystemBuildActions.Instance.IsWindows(); + private bool? isDefaultFeedReachable; + private bool IsDefaultFeedReachable => + isDefaultFeedReachable ??= feedManager.IsDefaultFeedReachable(); + /// /// Create the package manager for a specified source tree. /// - public NugetExeWrapper(FileProvider fileProvider, DependencyDirectory packageDirectory, Semmle.Util.Logging.ILogger logger, Func useDefaultFeed) + public NugetExeWrapper(FileProvider fileProvider, DependencyDirectory packageDirectory, Semmle.Util.Logging.ILogger logger, FeedManager feedManager) { this.fileProvider = fileProvider; this.packageDirectory = packageDirectory; this.logger = logger; + this.feedManager = feedManager; if (fileProvider.PackagesConfigs.Count > 0) { logger.LogInfo($"Found packages.config files, trying to use nuget.exe for package restore"); nugetExe = ResolveNugetExe(); - if (!HasPackageSource() && useDefaultFeed()) - { - // We only modify or add a top level nuget.config file - nugetConfigPath = Path.Join(fileProvider.SourceDir.FullName, "nuget.config"); - try - { - if (File.Exists(nugetConfigPath)) - { - var tempFolderPath = FileUtils.GetTemporaryWorkingDirectory(out _); - - do - { - backupNugetConfig = Path.Join(tempFolderPath, Path.GetRandomFileName()); - } - while (File.Exists(backupNugetConfig)); - File.Copy(nugetConfigPath, backupNugetConfig, true); - } - else - { - File.WriteAllText(nugetConfigPath, - """ - - - - - - """); - } - AddDefaultPackageSource(nugetConfigPath); - } - catch (Exception e) - { - logger.LogError($"Failed to add default package source to {nugetConfigPath}: {e}"); - } - } } } @@ -198,6 +168,21 @@ private bool TryRestoreNugetPackage(string packagesConfig) { logger.LogInfo($"Restoring file \"{packagesConfig}\"..."); + var sourcesArgument = ""; + var feedsToUse = feedManager.FeedsToUse(packagesConfig).ToList(); + var useDefaultFeed = feedsToUse.Count == 0 && IsDefaultFeedReachable; + + // Explicitly construct the sources to be used for the restore command when checking feed + // responsiveness, using private registries, or falling back to nuget.org. + if (feedManager.CheckNugetFeedResponsiveness || feedManager.HasPrivateRegistryFeeds || useDefaultFeed) + { + if (useDefaultFeed) + { + feedsToUse.Add(FeedManager.PublicNugetOrgFeed); + } + sourcesArgument = feedManager.FeedsToRestoreArgument(feedsToUse, "-Source"); + } + /* Use nuget.exe to install a package. * Note that there is a clutch of NuGet assemblies which could be used to * invoke this directly, which would arguably be nicer. However they are @@ -208,12 +193,12 @@ private bool TryRestoreNugetPackage(string packagesConfig) if (RunWithMono) { exe = "mono"; - args = $"\"{nugetExe}\" install -OutputDirectory \"{packageDirectory}\" \"{packagesConfig}\""; + args = $"\"{nugetExe}\" install -OutputDirectory \"{packageDirectory}\" {sourcesArgument} \"{packagesConfig}\""; } else { exe = nugetExe!; - args = $"install -OutputDirectory \"{packageDirectory}\" \"{packagesConfig}\""; + args = $"install -OutputDirectory \"{packageDirectory}\" {sourcesArgument} \"{packagesConfig}\""; } var pi = new ProcessStartInfo(exe, args) @@ -246,98 +231,6 @@ public int InstallPackages() { return fileProvider.PackagesConfigs.Count(TryRestoreNugetPackage); } - - private bool HasPackageSource() - { - if (IsWindows) - { - return true; - } - - try - { - logger.LogInfo("Checking if default package source is available..."); - RunMonoNugetCommand("sources list -ForceEnglishOutput", out var stdout); - if (stdout.All(line => line != "No sources found.")) - { - return true; - } - - return false; - } - catch (Exception e) - { - logger.LogWarning($"Failed to check if default package source is added: {e}"); - return true; - } - } - - private void RunMonoNugetCommand(string command, out IList stdout) - { - string exe, args; - if (RunWithMono) - { - exe = "mono"; - args = $"\"{nugetExe}\" {command}"; - } - else - { - exe = nugetExe!; - args = command; - } - - var pi = new ProcessStartInfo(exe, args) - { - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false - }; - - var threadId = Environment.CurrentManagedThreadId; - void onOut(string s) => logger.LogDebug(s, threadId); - void onError(string s) => logger.LogError(s, threadId); - pi.ReadOutput(out stdout, onOut, onError); - } - - private void AddDefaultPackageSource(string nugetConfig) - { - logger.LogInfo("Adding default package source..."); - RunMonoNugetCommand($"sources add -Name DefaultNugetOrg -Source {FeedManager.PublicNugetOrgFeed} -ConfigFile \"{nugetConfig}\"", out _); - } - - public void Dispose() - { - if (nugetConfigPath is null) - { - return; - } - - try - { - if (backupNugetConfig is null) - { - logger.LogInfo("Removing nuget.config file"); - File.Delete(nugetConfigPath); - return; - } - - logger.LogInfo("Reverting nuget.config file content"); - // The content of the original nuget.config file is reverted without changing the file's attributes or casing: - using (var backup = File.OpenRead(backupNugetConfig)) - using (var current = File.OpenWrite(nugetConfigPath)) - { - current.SetLength(0); // Truncate file - backup.CopyTo(current); // Restore original content - } - - logger.LogInfo("Deleting backup nuget.config file"); - File.Delete(backupNugetConfig); - } - catch (Exception exc) - { - logger.LogError($"Failed to restore original nuget.config file: {exc}"); - } - } } private class NoOpPackagesConfig : IPackagesConfigRestore @@ -361,8 +254,6 @@ public int InstallPackages() } return 0; } - - public void Dispose() { } } } } diff --git a/csharp/extractor/Semmle.Extraction.Tests/DotNet.cs b/csharp/extractor/Semmle.Extraction.Tests/DotNet.cs index a2996497e005..74939b61af5e 100644 --- a/csharp/extractor/Semmle.Extraction.Tests/DotNet.cs +++ b/csharp/extractor/Semmle.Extraction.Tests/DotNet.cs @@ -130,11 +130,11 @@ public void TestDotnetRestoreProjectToDirectory2() var dotnet = MakeDotnet(dotnetCliInvoker); // Execute - var res = dotnet.Restore(new("myproject.csproj", "mypackages", false, null, "myconfig.config")); + var res = dotnet.Restore(new("myproject.csproj", "mypackages", false, null)); // Verify var lastArgs = dotnetCliInvoker.GetLastArgs(); - Assert.Equal("restore --no-dependencies \"myproject.csproj\" --packages \"mypackages\" /p:DisableImplicitNuGetFallbackFolder=true --verbosity normal --configfile \"myconfig.config\"", lastArgs); + Assert.Equal("restore --no-dependencies \"myproject.csproj\" --packages \"mypackages\" /p:DisableImplicitNuGetFallbackFolder=true --verbosity normal", lastArgs); Assert.Equal(2, res.AssetsFilePaths.Count()); Assert.Contains("/path/to/project.assets.json", res.AssetsFilePaths); Assert.Contains("/path/to/project2.assets.json", res.AssetsFilePaths); @@ -148,11 +148,11 @@ public void TestDotnetRestoreProjectToDirectory3() var dotnet = MakeDotnet(dotnetCliInvoker); // Execute - var res = dotnet.Restore(new("myproject.csproj", "mypackages", false, null, "myconfig.config", true)); + var res = dotnet.Restore(new("myproject.csproj", "mypackages", false, null, true)); // Verify var lastArgs = dotnetCliInvoker.GetLastArgs(); - Assert.Equal("restore --no-dependencies \"myproject.csproj\" --packages \"mypackages\" /p:DisableImplicitNuGetFallbackFolder=true --verbosity normal --configfile \"myconfig.config\" --force", lastArgs); + Assert.Equal("restore --no-dependencies \"myproject.csproj\" --packages \"mypackages\" /p:DisableImplicitNuGetFallbackFolder=true --verbosity normal --force", lastArgs); Assert.Equal(2, res.AssetsFilePaths.Count()); Assert.Contains("/path/to/project.assets.json", res.AssetsFilePaths); Assert.Contains("/path/to/project2.assets.json", res.AssetsFilePaths); diff --git a/csharp/ql/lib/change-notes/2026-06-24-nuget-packages-config.md b/csharp/ql/lib/change-notes/2026-06-24-nuget-packages-config.md new file mode 100644 index 000000000000..5b236a118da7 --- /dev/null +++ b/csharp/ql/lib/change-notes/2026-06-24-nuget-packages-config.md @@ -0,0 +1,4 @@ +--- +category: majorAnalysis +--- +* Simplified and streamlined the use of NuGet sources when downloading dependencies via `[mono] nuget.exe` in `build-mode: none`: NuGet sources are now supplied via the `-Source` flag instead of moving or creating `nuget.config` files in the checked-out repository, private registries are used if configured, and only reachable feeds are used when NuGet feed checking is enabled (the default).