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
2 changes: 1 addition & 1 deletion docs/detectors/vcpkg.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ The detector parses these SPDX files to extract component information and recogn
- **Binary packages** (`SPDXRef-binary`): Compiled binaries with triplet information (e.g., `x64-windows`, `x64-linux`)
- **Resource packages** (`SPDXRef-resource-*`): External resources and dependencies referenced by ports

When a `manifest-info.json` exists in the `vcpkg_installed` directory, components are attributed to the source manifest rather than the SBOM file itself. The detector checks both the preferred location (`vcpkg_installed/vcpkg/manifest-info.json`) and a fallback location (`vcpkg_installed/manifest-info.json`). This enhancement, introduced in vcpkg >= 2025.02.14, ensures accurate dependency tracking and streamlines workflows like vulnerability resolution (e.g., Dependabot).
When a `manifest-info.json` exists in the installed tree, components are attributed to the source manifest rather than the SBOM file itself. Starting from the SBOM directory, the detector checks each ancestor up to and including the nearest `vcpkg_installed` directory. At each level it prefers `vcpkg/manifest-info.json` over the fallback `manifest-info.json`, and uses the nearest valid mapping. This supports both the standard install root and the triplet-specific install root used by MSBuild, such as `vcpkg_installed/x64-windows/vcpkg/manifest-info.json`. Manifest linking, introduced in vcpkg >= 2025.02.14, ensures accurate dependency tracking and streamlines workflows like vulnerability resolution (e.g., Dependabot).

Because this detection strategy looks for the concrete files in the installed tree, it accurately detects the precise packages used during the build and excludes packages optionally used on other platforms.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public VcpkgComponentDetector(

public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = [ComponentType.Vcpkg];

public override int Version => 3;
public override int Version => 4;

protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs, CancellationToken cancellationToken = default)
{
Expand Down Expand Up @@ -202,8 +202,14 @@ private ISingleFileComponentRecorder GetManifestComponentRecorder(ISingleFileCom
{
var manifestFileLocation = singleFileComponentRecorder.ManifestFileLocation;

var vcpkgInstalledIndex = manifestFileLocation.IndexOf(VcpkgInstalledFolder, StringComparison.OrdinalIgnoreCase);
if (vcpkgInstalledIndex < 0)
var directory = Directory.GetParent(manifestFileLocation);
var installedDirectory = directory;
while (installedDirectory != null && !installedDirectory.Name.Equals(VcpkgInstalledFolder, StringComparison.OrdinalIgnoreCase))
{
installedDirectory = installedDirectory.Parent;
}

if (installedDirectory == null)
{
this.Logger.LogDebug(
"Could not find '{VcpkgInstalled}' in ManifestFileLocation: '{ManifestFileLocation}'. Returning original recorder.",
Expand All @@ -213,33 +219,40 @@ private ISingleFileComponentRecorder GetManifestComponentRecorder(ISingleFileCom
return singleFileComponentRecorder;
}

var vcpkgInstalledDir = manifestFileLocation[..(vcpkgInstalledIndex + VcpkgInstalledFolder.Length)];
// MSBuild installs into a triplet-specific root below vcpkg_installed.
// Resolve the closest manifest without crossing into another installed tree.
while (directory != null)
{
var preferredManifest = Path.Combine(directory.FullName, "vcpkg", ManifestInfoFile);
var fallbackManifest = Path.Combine(directory.FullName, ManifestInfoFile);

var preferredManifest = Path.Combine(vcpkgInstalledDir, "vcpkg", ManifestInfoFile);
var fallbackManifest = Path.Combine(vcpkgInstalledDir, ManifestInfoFile);
if (this.manifestMappings.TryGetValue(preferredManifest, out var manifestPath) && manifestPath != null)
{
return this.ComponentRecorder.CreateSingleFileComponentRecorder(manifestPath);
}
else if (this.manifestMappings.TryGetValue(fallbackManifest, out manifestPath) && manifestPath != null)
{
this.Logger.LogDebug(
"Preferred manifest at '{PreferredManifest}' was not found or invalid. Using fallback manifest at '{FallbackManifest}'.",
preferredManifest,
fallbackManifest);

// Try preferred location first
if (this.manifestMappings.TryGetValue(preferredManifest, out var manifestPath) && manifestPath != null)
{
return this.ComponentRecorder.CreateSingleFileComponentRecorder(manifestPath);
}
else if (this.manifestMappings.TryGetValue(fallbackManifest, out manifestPath) && manifestPath != null)
{
// Use the fallback location.
this.Logger.LogDebug(
"Preferred manifest at '{PreferredManifest}' was not found or invalid. Using fallback manifest at '{FallbackManifest}'.",
preferredManifest,
fallbackManifest);
return this.ComponentRecorder.CreateSingleFileComponentRecorder(manifestPath);
}

if (directory.Name.Equals(VcpkgInstalledFolder, StringComparison.OrdinalIgnoreCase))
{
break;
}

return this.ComponentRecorder.CreateSingleFileComponentRecorder(manifestPath);
directory = directory.Parent;
}

this.Logger.LogDebug(
"No valid {ManifestInfoFile} found at either '{PreferredManifest}' or '{FallbackManifest}' for base location '{VcpkgInstalledDir}'. Returning original recorder.",
"No valid {ManifestInfoFile} found between '{ManifestFileLocation}' and '{VcpkgInstalledDir}'. Returning original recorder.",
ManifestInfoFile,
preferredManifest,
fallbackManifest,
vcpkgInstalledDir);
manifestFileLocation,
installedDirectory.FullName);
}
catch (Exception ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using AwesomeAssertions;
using Microsoft.ComponentDetection.Common.DependencyGraph;
Expand All @@ -20,6 +21,18 @@ namespace Microsoft.ComponentDetection.Detectors.Tests;
[TestCategory("Governance/ComponentDetection")]
public class VcpkgComponentDetectorTests
{
private const string ManifestAttributionSbom = """
{
"packages": [
{
"name": "test-port",
"SPDXID": "SPDXRef-port",
"versionInfo": "1.0.0#0"
}
]
}
""";

private readonly DetectorTestUtilityBuilder<VcpkgComponentDetector> detectorTestUtility = new();

private readonly Mock<ICommandLineInvocationService> mockCommandLineInvocationService;
Expand Down Expand Up @@ -356,6 +369,127 @@ public async Task TestVcpkgManifestFileAsync(string manifestPath, string pathToV
expectedResult.Should().Be(t_pathToVcpkg);
}

[TestMethod]
[DataRow(false, false)]
[DataRow(false, true)]
[DataRow(true, false)]
[DataRow(true, true)]
public async Task TestVcpkgManifestAttributionForInstalledLayoutsAsync(bool nestedInstallRoot, bool fallbackManifest)
{
var projectRoot = Path.Combine(Path.GetTempPath(), "vcpkg-manifest-tests");
var installedRoot = Path.Combine(projectRoot, "vcpkg_installed");
if (nestedInstallRoot)
{
installedRoot = Path.Combine(installedRoot, "x64-windows");
}

var spdxPath = Path.Combine(installedRoot, "x64-windows", "share", "test-port", "vcpkg.spdx.json");
var manifestInfoPath = fallbackManifest
? Path.Combine(installedRoot, "manifest-info.json")
: Path.Combine(installedRoot, "vcpkg", "manifest-info.json");
var sourceManifest = Path.Combine(projectRoot, "vcpkg.json");

var (scanResult, componentRecorder) = await this.detectorTestUtility
.WithFile("vcpkg.spdx.json", ManifestAttributionSbom, fileLocation: spdxPath)
.WithFile("manifest-info.json", CreateManifestInfo(sourceManifest), fileLocation: manifestInfoPath)
.ExecuteDetectorAsync();

scanResult.ResultCode.Should().Be(ProcessingResultCode.Success);
var component = componentRecorder.GetDetectedComponents().Should().ContainSingle().Subject;
var graphs = componentRecorder.GetDependencyGraphsByLocation();
graphs.Keys.Should().ContainSingle().Which.Should().Be(sourceManifest);
graphs[sourceManifest].Contains(component.Component.Id).Should().BeTrue();
}

[TestMethod]
[DataRow(true)]
[DataRow(false)]
public async Task TestVcpkgManifestAttributionPrefersNearestValidManifestAsync(bool validPreferredManifest)
{
var projectRoot = Path.Combine(Path.GetTempPath(), "vcpkg-manifest-tests");
var outerRoot = Path.Combine(projectRoot, "vcpkg_installed");
var installedRoot = Path.Combine(outerRoot, "x64-windows");
var spdxPath = Path.Combine(installedRoot, "x64-windows", "share", "test-port", "vcpkg.spdx.json");
var preferredManifest = Path.Combine(projectRoot, "preferred", "vcpkg.json");
var fallbackManifest = Path.Combine(projectRoot, "fallback", "vcpkg.json");
var outerManifest = Path.Combine(projectRoot, "outer", "vcpkg.json");

var (scanResult, componentRecorder) = await this.detectorTestUtility
.WithFile("vcpkg.spdx.json", ManifestAttributionSbom, fileLocation: spdxPath)
.WithFile("manifest-info.json", validPreferredManifest ? CreateManifestInfo(preferredManifest) : "{}", fileLocation: Path.Combine(installedRoot, "vcpkg", "manifest-info.json"))
.WithFile("manifest-info.json", CreateManifestInfo(fallbackManifest), fileLocation: Path.Combine(installedRoot, "manifest-info.json"))
.WithFile("manifest-info.json", CreateManifestInfo(outerManifest), fileLocation: Path.Combine(outerRoot, "vcpkg", "manifest-info.json"))
.ExecuteDetectorAsync();

scanResult.ResultCode.Should().Be(ProcessingResultCode.Success);
componentRecorder.GetDetectedComponents().Should().ContainSingle();
componentRecorder.GetDependencyGraphsByLocation().Keys.Should().ContainSingle()
.Which.Should().Be(validPreferredManifest ? preferredManifest : fallbackManifest);
}

[TestMethod]
[DataRow(true)]
[DataRow(false)]
public async Task TestVcpkgManifestAttributionDoesNotUseSiblingInstallRootAsync(bool hasMatchingManifest)
{
var projectRoot = Path.Combine(Path.GetTempPath(), "vcpkg-manifest-tests");
var outerRoot = Path.Combine(projectRoot, "vcpkg_installed");
var installedRoot = Path.Combine(outerRoot, "x64-windows");
var spdxPath = Path.Combine(installedRoot, "x64-windows", "share", "test-port", "vcpkg.spdx.json");
var sourceManifest = Path.Combine(projectRoot, "vcpkg.json");

this.detectorTestUtility
.WithFile("vcpkg.spdx.json", ManifestAttributionSbom, fileLocation: spdxPath)
.WithFile("manifest-info.json", CreateManifestInfo(Path.Combine(projectRoot, "other", "vcpkg.json")), fileLocation: Path.Combine(outerRoot, "x86-windows", "vcpkg", "manifest-info.json"));

if (hasMatchingManifest)
{
this.detectorTestUtility.WithFile("manifest-info.json", CreateManifestInfo(sourceManifest), fileLocation: Path.Combine(installedRoot, "vcpkg", "manifest-info.json"));
}

var (scanResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetectorAsync();

scanResult.ResultCode.Should().Be(ProcessingResultCode.Success);
componentRecorder.GetDetectedComponents().Should().ContainSingle();
componentRecorder.GetDependencyGraphsByLocation().Keys.Should().ContainSingle()
.Which.Should().Be(hasMatchingManifest ? sourceManifest : spdxPath);
}

[TestMethod]
public async Task TestVcpkgManifestAttributionRequiresInstalledDirectoryAsync()
{
var projectRoot = Path.Combine(Path.GetTempPath(), "vcpkg-manifest-tests");
var installedRoot = Path.Combine(projectRoot, "vcpkg_installed_backup");
var spdxPath = Path.Combine(installedRoot, "x64-windows", "share", "test-port", "vcpkg.spdx.json");

var (scanResult, componentRecorder) = await this.detectorTestUtility
.WithFile("vcpkg.spdx.json", ManifestAttributionSbom, fileLocation: spdxPath)
.WithFile("manifest-info.json", CreateManifestInfo(Path.Combine(projectRoot, "vcpkg.json")), fileLocation: Path.Combine(installedRoot, "vcpkg", "manifest-info.json"))
.ExecuteDetectorAsync();

scanResult.ResultCode.Should().Be(ProcessingResultCode.Success);
componentRecorder.GetDependencyGraphsByLocation().Keys.Should().ContainSingle().Which.Should().Be(spdxPath);
}

[TestMethod]
public async Task TestVcpkgManifestAttributionDoesNotCrossInstalledTreeAsync()
{
var projectRoot = Path.Combine(Path.GetTempPath(), "vcpkg-manifest-tests");
var outerRoot = Path.Combine(projectRoot, "vcpkg_installed");
var installedRoot = Path.Combine(outerRoot, "nested-project", "vcpkg_installed");
var spdxPath = Path.Combine(installedRoot, "x64-windows", "share", "test-port", "vcpkg.spdx.json");

var (scanResult, componentRecorder) = await this.detectorTestUtility
.WithFile("vcpkg.spdx.json", ManifestAttributionSbom, fileLocation: spdxPath)
.WithFile("manifest-info.json", CreateManifestInfo(Path.Combine(projectRoot, "vcpkg.json")), fileLocation: Path.Combine(outerRoot, "vcpkg", "manifest-info.json"))
.ExecuteDetectorAsync();

scanResult.ResultCode.Should().Be(ProcessingResultCode.Success);
componentRecorder.GetDependencyGraphsByLocation().Keys.Should().ContainSingle().Which.Should().Be(spdxPath);
}

private static string CreateManifestInfo(string manifestPath) => JsonSerializer.Serialize(new Dictionary<string, string> { ["manifest-path"] = manifestPath });

private static string CrossPlatformPath(string relPath)
{
var segments = relPath.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries);
Expand Down