diff --git a/docs/detectors/vcpkg.md b/docs/detectors/vcpkg.md index decd095ba..20add4067 100644 --- a/docs/detectors/vcpkg.md +++ b/docs/detectors/vcpkg.md @@ -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. diff --git a/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs index c2fac266a..6ab8d1d01 100644 --- a/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs @@ -49,7 +49,7 @@ public VcpkgComponentDetector( public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Vcpkg]; - public override int Version => 3; + public override int Version => 4; protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary detectorArgs, CancellationToken cancellationToken = default) { @@ -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.", @@ -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) { diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs index 4cf279fd4..86caa7393 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs @@ -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; @@ -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 detectorTestUtility = new(); private readonly Mock mockCommandLineInvocationService; @@ -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 { ["manifest-path"] = manifestPath }); + private static string CrossPlatformPath(string relPath) { var segments = relPath.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries);