Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
6b2f348
C#: Add `CODEQL_PROXY_URLS` environment variable
mbg Jan 6, 2025
63d5517
C#: Add list of registries to `DependabotProxy`
mbg Jan 7, 2025
11efb55
C#: Parse environment variables to obtain list of registry URLs
mbg Jan 7, 2025
726123c
C#: Allow specifying package feeds for `dotnet restore` as command li…
mbg Jan 7, 2025
0db6a26
C#: Propagate explicit feeds to `RestoreProjects`
mbg Feb 24, 2025
6b15f77
C#: Fix test failures
mbg Mar 3, 2025
a8dde15
C#: Only provide feeds on command line if Dependabot proxy is enabled
mbg Mar 14, 2025
9560593
C#: Fix `.ToList()` being called on `null`
mbg Mar 14, 2025
b6c74fe
C#: Narrow `Exception` to `JsonException`
mbg Mar 14, 2025
284f612
C#: Use `StringBuilder` for feed arguments in `GetRestoreArgs`
mbg Mar 14, 2025
51874b8
Apply suggestions from code review
mbg Mar 17, 2025
7a92a72
C#: Change `RegistryConfig` to a record class
mbg Mar 18, 2025
d564529
C#: Change `RestoreSettings` to have general `extraArgs` parameter
mbg Mar 24, 2025
92eab47
C#: Refactor `CheckFeeds` to have an overloaded variant that accepts …
mbg Mar 24, 2025
4448369
C#: Check that private package registry feeds are reachable
mbg Mar 24, 2025
7cea2ad
Apply suggestions from code review
mbg Mar 25, 2025
d2b88ae
C#: Rename overloaded `CheckFeeds` method and fix comment
mbg Mar 25, 2025
4d3b024
C#: Do not manually add public feed when private registries are used
mbg Mar 25, 2025
73ca2eb
C#: Use `allFeeds` rather than `explicitFeeds` for `RestoreProjects`
mbg Mar 25, 2025
be95d33
C#: Obtain all feeds from source directory if there are no `nuget.con…
mbg Mar 25, 2025
fe1c098
C#: Accept changes to `.expected` files
mbg Mar 25, 2025
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
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Semmle.Util;
using Semmle.Util.Logging;
using Newtonsoft.Json;

namespace Semmle.Extraction.CSharp.DependencyFetching
{
public class DependabotProxy : IDisposable
{
/// <summary>
/// Represents configurations for package registries.
/// </summary>
public struct RegistryConfig
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any particular reason/benefit to declare this as a struct?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No particular reason. I thought I was mirroring a similar setup elsewhere in the codebase, but happy to change it.

{
/// <summary>
/// The type of package registry.
/// </summary>
public string Type { get; set; }
/// <summary>
/// The URL of the package registry.
/// </summary>
public string URL { get; set; }
}

private readonly string host;
private readonly string port;

Expand All @@ -17,6 +33,10 @@
/// </summary>
internal string Address { get; }
/// <summary>
/// The URLs of package registries that are configured for the proxy.
/// </summary>
internal HashSet<string> RegistryURLs { get; }
/// <summary>
/// The path to the temporary file where the certificate is stored.
/// </summary>
internal string? CertificatePath { get; private set; }
Expand Down Expand Up @@ -67,6 +87,39 @@
result.Certificate = X509Certificate2.CreateFromPem(cert);
}

// Try to obtain the list of private registry URLs.
var registryURLs = Environment.GetEnvironmentVariable(EnvironmentVariableNames.ProxyURLs);

if (!string.IsNullOrWhiteSpace(registryURLs))
{
try
{
// The value of the environment variable should be a JSON array of objects, such as:
// [ { "type": "nuget_feed", "url": "https://nuget.pkg.github.com/org/index.json" } ]
var array = JsonConvert.DeserializeObject<List<RegistryConfig>>(registryURLs);
if (array != null)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we expect the array to be null? Should we log if it is null?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main reason for the check is just to make sure we don't work with a null value. We could log it, but I have no strong view on it either way.

{
foreach (RegistryConfig config in array)
{
// The array contains all configured private registries, not just ones for C#.
// We ignore the non-C# ones here.
if (!config.Type.Equals("nuget_feed"))
{
logger.LogDebug($"Ignoring registry at '{config.URL}' since it is not of type 'nuget_feed'.");
continue;
}

logger.LogInfo($"Found private registry at '{config.URL}'");
result.RegistryURLs.Add(config.URL);
}
}
}
catch (Exception ex)
{
logger.LogError($"Unable to parse '{EnvironmentVariableNames.ProxyURLs}': {ex.Message}");
}
}

return result;
}

Expand All @@ -75,6 +128,7 @@
this.host = host;
this.port = port;
this.Address = $"http://{this.host}:{this.port}";
this.RegistryURLs = new HashSet<string>();
}

public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@
args += $" --configfile \"{restoreSettings.PathToNugetConfig}\"";
}

// Add package sources. If any are present, they override all sources specified in
// the configuration file(s).
if (restoreSettings.Sources != null)
{
foreach (string source in restoreSettings.Sources)
{
args += $" -s {source}";
}
}

if (restoreSettings.ForceReevaluation)
{
args += " --force";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,10 @@ internal static class EnvironmentVariableNames
/// Contains the certificate used by the Dependabot proxy.
/// </summary>
public const string ProxyCertificate = "CODEQL_PROXY_CA_CERTIFICATE";

/// <summary>
/// Contains the URLs of private nuget registries as a JSON array.
/// </summary>
public const string ProxyURLs = "CODEQL_PROXY_URLS";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public interface IDotNet
IList<string> GetNugetFeedsFromFolder(string folderPath);
}

public record class RestoreSettings(string File, string PackageDirectory, bool ForceDotnetRefAssemblyFetching, string? PathToNugetConfig = null, bool ForceReevaluation = false, bool TargetWindows = false);
public record class RestoreSettings(string File, string PackageDirectory, bool ForceDotnetRefAssemblyFetching, IList<string>? Sources = null, string? PathToNugetConfig = null, bool ForceReevaluation = false, bool TargetWindows = false);

public partial record class RestoreResult(bool Success, IList<string> Output)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@

var restoredProjects = RestoreSolutions(out var container);
var projects = fileProvider.Projects.Except(restoredProjects);
RestoreProjects(projects, out var containers);
RestoreProjects(projects, explicitFeeds, out var containers);

var dependencies = containers.Flatten(container);

Expand Down Expand Up @@ -260,8 +260,24 @@
/// Populates dependencies with the relative paths to the assets files generated by the restore.
/// </summary>
/// <param name="projects">A list of paths to project files.</param>
private void RestoreProjects(IEnumerable<string> projects, out ConcurrentBag<DependencyContainer> dependencies)
private void RestoreProjects(IEnumerable<string> projects, HashSet<string>? configuredSources, out ConcurrentBag<DependencyContainer> dependencies)
{
// Conservatively, we only set this to a non-null value if a Dependabot proxy is enabled.
// This ensures that we continue to get the old behaviour where feeds are taken from
// `nuget.config` files instead of the command-line arguments.
HashSet<string>? sources = null;

if (this.dependabotProxy != null)
{
// If the Dependabot proxy is configured, then our main goal is to make `dotnet` aware
// of the private registry feeds. However, since providing them as command-line arguments
// to `dotnet` ignores other feeds that may be configured, we also need to add the feeds
// we have discovered from analysing `nuget.config` files.
sources = configuredSources ?? new();
sources.Add(PublicNugetOrgFeed);
this.dependabotProxy?.RegistryURLs.ForEach(url => sources.Add(url));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider constructing the "source" string at this location instead. Otherwise it will be constructed once for each project that is restored in the parallel restore loop.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in d564529

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid timeouts, maybe there should be a feed validation check similar to:

var allFeedsReachable = explicitFeeds.All(feed => excludedFeeds.Contains(feed) || IsFeedReachable(feed, initialTimeout, tryCount));

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 4448369

}

var successCount = 0;
var nugetSourceFailures = 0;
ConcurrentBag<DependencyContainer> collectedDependencies = [];
Expand All @@ -276,7 +292,7 @@
foreach (var project in projectGroup)
{
logger.LogInfo($"Restoring project {project}...");
var res = dotnet.Restore(new(project, PackageDirectory.DirInfo.FullName, ForceDotnetRefAssemblyFetching: true, TargetWindows: isWindows));
var res = dotnet.Restore(new(project, PackageDirectory.DirInfo.FullName, ForceDotnetRefAssemblyFetching: true, sources.ToList(), TargetWindows: isWindows));

Check warning on line 295 in csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs

View workflow job for this annotation

GitHub Actions / unit-tests (ubuntu-latest)

Possible null reference argument for parameter 'source' in 'List<string> Enumerable.ToList<string>(IEnumerable<string> source)'.

Check warning on line 295 in csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs

View workflow job for this annotation

GitHub Actions / stubgentest

Possible null reference argument for parameter 'source' in 'List<string> Enumerable.ToList<string>(IEnumerable<string> source)'.

Check warning on line 295 in csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs

View workflow job for this annotation

GitHub Actions / stubgentest

Possible null reference argument for parameter 'source' in 'List<string> Enumerable.ToList<string>(IEnumerable<string> source)'.

Check warning on line 295 in csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs

View workflow job for this annotation

GitHub Actions / unit-tests (windows-2019)

Possible null reference argument for parameter 'source' in 'List<string> Enumerable.ToList<string>(IEnumerable<string> source)'.

Check warning on line 295 in csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs

View workflow job for this annotation

GitHub Actions / CodeQL-Build (actions)

Possible null reference argument for parameter 'source' in 'List<string> Enumerable.ToList<string>(IEnumerable<string> source)'.

Check warning on line 295 in csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs

View workflow job for this annotation

GitHub Actions / CodeQL-Build (actions)

Possible null reference argument for parameter 'source' in 'List<string> Enumerable.ToList<string>(IEnumerable<string> source)'.

Check warning on line 295 in csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs

View workflow job for this annotation

GitHub Actions / CodeQL-Build (csharp)

Possible null reference argument for parameter 'source' in 'List<string> Enumerable.ToList<string>(IEnumerable<string> source)'.

Check warning on line 295 in csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs

View workflow job for this annotation

GitHub Actions / CodeQL-Build (csharp)

Possible null reference argument for parameter 'source' in 'List<string> Enumerable.ToList<string>(IEnumerable<string> source)'.
assets.AddDependenciesRange(res.AssetsFilePaths);
lock (sync)
{
Expand Down
4 changes: 2 additions & 2 deletions csharp/extractor/Semmle.Extraction.Tests/DotNet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public void TestDotnetRestoreProjectToDirectory2()
var dotnet = MakeDotnet(dotnetCliInvoker);

// Execute
var res = dotnet.Restore(new("myproject.csproj", "mypackages", false, "myconfig.config"));
var res = dotnet.Restore(new("myproject.csproj", "mypackages", false, null, "myconfig.config"));

// Verify
var lastArgs = dotnetCliInvoker.GetLastArgs();
Expand All @@ -141,7 +141,7 @@ public void TestDotnetRestoreProjectToDirectory3()
var dotnet = MakeDotnet(dotnetCliInvoker);

// Execute
var res = dotnet.Restore(new("myproject.csproj", "mypackages", false, "myconfig.config", true));
var res = dotnet.Restore(new("myproject.csproj", "mypackages", false, null, "myconfig.config", true));

// Verify
var lastArgs = dotnetCliInvoker.GetLastArgs();
Expand Down
Loading