From 446faa652bda6a8d30a71f7480bf23b9563e7d9c Mon Sep 17 00:00:00 2001 From: Greg Villicana Date: Wed, 11 Nov 2026 01:32:11 -0800 Subject: [PATCH 1/5] Add Composer support --- README.md | 1 + docs/creating-a-new-detector.md | 10 + docs/detectors/README.md | 6 + docs/detectors/composer.md | 45 + docs/schema/manifest.schema.json | 8 +- .../CommandLineInvocationService.cs | 29 +- .../BcdeModels/TypedComponentMapping.cs | 2 + .../DetectorClass.cs | 3 + .../FileComponentDetector.cs | 12 + .../ICommandLineInvocationService.cs | 40 +- .../TypedComponent/ComponentType.cs | 6 + .../TypedComponent/ComposerComponent.cs | 41 + .../TypedComponent/PhpSdkComponent.cs | 41 + .../composer/ComposerComponentDetector.cs | 829 +++++++++++ .../composer/ComposerGraph.cs | 82 ++ .../composer/ComposerVersionConstraint.cs | 397 ++++++ .../Commands/ScanSettings.cs | 2 +- .../Experiments/Configs/ComposerExperiment.cs | 22 + .../Extensions/ServiceCollectionExtensions.cs | 5 + .../CommandLineInvocationServiceTests.cs | 81 ++ .../ComposerComponentTests.cs | 167 +++ ....ComponentDetection.Contracts.Tests.csproj | 1 + .../PhpSdkComponentTests.cs | 100 ++ .../ComponentDetectorTests.cs | 12 + .../ComposerDetectorTests.cs | 1253 +++++++++++++++++ .../ComposerPlatformTests.cs | 367 +++++ .../ComposerVersionConstraintTests.cs | 141 ++ ....ComponentDetection.Detectors.Tests.csproj | 6 + .../TestFiles/Composer/composer.json | 5 + .../TestFiles/Composer/composer.lock | 45 + .../Experiments/ExperimentConfigTests.cs | 33 + .../Experiments/ExperimentServiceTests.cs | 39 + ...mponentDetection.Orchestrator.Tests.csproj | 1 + .../Services/ComposerProcessingTests.cs | 132 ++ .../DetectorTestUtilityBuilder.cs | 5 +- .../resources/composer/composer.json | 5 + .../resources/composer/composer.lock | 45 + 37 files changed, 3991 insertions(+), 28 deletions(-) create mode 100644 docs/detectors/composer.md create mode 100644 src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComposerComponent.cs create mode 100644 src/Microsoft.ComponentDetection.Contracts/TypedComponent/PhpSdkComponent.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/ComposerGraph.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/ComposerVersionConstraint.cs create mode 100644 src/Microsoft.ComponentDetection.Orchestrator/Experiments/Configs/ComposerExperiment.cs create mode 100644 test/Microsoft.ComponentDetection.Contracts.Tests/ComposerComponentTests.cs create mode 100644 test/Microsoft.ComponentDetection.Contracts.Tests/PhpSdkComponentTests.cs create mode 100644 test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs create mode 100644 test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs create mode 100644 test/Microsoft.ComponentDetection.Detectors.Tests/ComposerVersionConstraintTests.cs create mode 100644 test/Microsoft.ComponentDetection.Detectors.Tests/TestFiles/Composer/composer.json create mode 100644 test/Microsoft.ComponentDetection.Detectors.Tests/TestFiles/Composer/composer.lock create mode 100644 test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/ComposerProcessingTests.cs create mode 100644 test/Microsoft.ComponentDetection.VerificationTests/resources/composer/composer.json create mode 100644 test/Microsoft.ComponentDetection.VerificationTests/resources/composer/composer.lock diff --git a/README.md b/README.md index e3b529899..3a58d56d3 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ Component Detection supports detecting libraries from the following ecosystems: | Ecosystem | Scanning | Graph Creation | | -------------------------------------------------------------------------------- | ----------------------------------------------- | -------------- | | [CocoaPods](docs/detectors/cocoapods.md) | ✔ | ✔ | +| [Composer (PHP, experimental)](docs/detectors/composer.md) | ✔ | ✔ | | [Conan](docs/detectors/conan.md) | ✔ | ❌ | | [Conda (Python)](docs/detectors/conda.md) | ✔ | ✔ | | [Docker Compose](docs/detectors/dockercompose.md) | ✔ | ❌ | diff --git a/docs/creating-a-new-detector.md b/docs/creating-a-new-detector.md index 41739b8d8..49afb4caf 100644 --- a/docs/creating-a-new-detector.md +++ b/docs/creating-a-new-detector.md @@ -39,6 +39,16 @@ The main parsing logic. Called once per matched file to: - Extract component information - Build the dependency graph via `ComponentRecorder` +For JSON formats where comments and trailing commas can be tolerated, derived +detectors can opt in to `FileComponentDetector.LenientJsonDocumentOptions`: + +```csharp +using var document = await JsonDocument.ParseAsync(stream, LenientJsonDocumentOptions, cancellationToken); +``` + +These options skip comments and allow trailing commas. They do not relax other +JSON syntax or package validation, and do not change parsing defaults automatically. + ### 3. `OnDetectionFinishedAsync` (Optional) Runs after all files are processed. Use this for: diff --git a/docs/detectors/README.md b/docs/detectors/README.md index 24602c9da..0c6363758 100644 --- a/docs/detectors/README.md +++ b/docs/detectors/README.md @@ -6,6 +6,12 @@ | -------------------- | ------ | | PodComponentDetector | Stable | +- [Composer](composer.md) + +| Detector | Status | +| ------------------------- | ------------ | +| ComposerComponentDetector | Experimental | + - [Conan](conan.md) | Detector | Status | diff --git a/docs/detectors/composer.md b/docs/detectors/composer.md new file mode 100644 index 000000000..8c474e723 --- /dev/null +++ b/docs/detectors/composer.md @@ -0,0 +1,45 @@ +# Composer + +The Composer detector finds packages used by PHP projects, including development +dependencies and the packages they depend on. PHP and Composer do not need to be +installed to scan the project's package files. + +## How detection works + +The detector looks for `composer.lock` and `composer.json` in your project: + +1. **If a lockfile exists**, it uses the package versions recorded there. + The `composer.json` in the same folder helps identify which packages your + project uses directly. +2. **If there is no lockfile**, it looks for installed package information in + `vendor\composer\installed.json`. +3. **If only `composer.json` is available**, it reports dependencies pinned to + exact versions, such as `1.2.3`. Ranges such as `^1.2` are skipped with a warning, + because they do not tell us which version was actually installed. + +For a custom vendor directory, the detector first checks the +[`COMPOSER_VENDOR_DIR` environment variable](https://getcomposer.org/doc/03-cli.md#composer_vendor_dir), +then `config.vendor-dir` in `composer.json`. Otherwise, it uses `vendor`. + +For more accurate results, run `composer install` before scanning so the lockfile +and installed package information are available. + +Results include dependency relationships and development flags when that +information is available. If your repository contains several PHP projects, each +is scanned separately. Vendor packages already covered by a parent project are +not scanned again. + +## PHP environment + +When PHP and Composer are available on `PATH`, the detector can also report the +local PHP version, Composer, extensions, and related libraries. It checks each +project separately and does not run this check inside vendor folders. + +These entries use the `PhpSdk` component type and are marked as development +dependencies. They describe the machine running the scan, not necessarily the +environment where your application will run. Excluding development dependencies +also excludes these entries. Simulated versions from `config.platform` are not +reported as installed software. + +Missing tools or a failed environment check do not stop package detection. +The scan does not install or update packages. diff --git a/docs/schema/manifest.schema.json b/docs/schema/manifest.schema.json index 0db3bdc7d..5f51fec66 100644 --- a/docs/schema/manifest.schema.json +++ b/docs/schema/manifest.schema.json @@ -154,7 +154,9 @@ "Conan", "Swift", "DotNet", - "CppSdk" + "CppSdk", + "Composer", + "PhpSdk" ] } } @@ -428,7 +430,9 @@ "Conan", "Swift", "DotNet", - "CppSdk" + "CppSdk", + "Composer", + "PhpSdk" ] }, "id": { diff --git a/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs b/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs index dc66db9ac..d36f7998c 100644 --- a/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs +++ b/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs @@ -21,6 +21,18 @@ internal class CommandLineInvocationService : ICommandLineInvocationService /// public async Task CanCommandBeLocatedAsync(string command, IEnumerable additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters) { + return await this.CanCommandBeLocatedAsync(command, additionalCandidateCommands, workingDirectory, CancellationToken.None, parameters); + } + + /// + public async Task CanCommandBeLocatedAsync( + string command, + IEnumerable additionalCandidateCommands, + DirectoryInfo workingDirectory, + CancellationToken cancellationToken, + params string[] parameters) + { + cancellationToken.ThrowIfCancellationRequested(); additionalCandidateCommands ??= []; parameters ??= []; var allCommands = new[] { command }.Concat(additionalCandidateCommands); @@ -28,12 +40,13 @@ public async Task CanCommandBeLocatedAsync(string command, IEnumerable ExecuteCommandAsync( CancellationToken cancellationToken = default, params string[] parameters) { - var isCommandLocatable = await this.CanCommandBeLocatedAsync(command, additionalCandidateCommands, workingDirectory, parameters); + var isCommandLocatable = await this.CanCommandBeLocatedAsync(command, additionalCandidateCommands, workingDirectory, cancellationToken, parameters); if (!isCommandLocatable) { throw new InvalidOperationException( @@ -80,7 +93,7 @@ public async Task ExecuteCommandAsync( var joinedParameters = string.Join(" ", parameters); try { - var result = await RunProcessAsync(pathToRun, joinedParameters, workingDirectory, cancellationToken); + var result = await RunProcessAsync(pathToRun, joinedParameters, workingDirectory, cancellationToken: cancellationToken); record.Track(result, pathToRun, joinedParameters); return result; } @@ -125,13 +138,9 @@ public async Task ExecuteCommandAsync(string command return await this.ExecuteCommandAsync(command, additionalCandidateCommands, workingDirectory: null, CancellationToken.None, parameters); } - private static Task RunProcessAsync(string fileName, string parameters, DirectoryInfo workingDirectory = null) - { - return RunProcessAsync(fileName, parameters, workingDirectory, CancellationToken.None); - } - private static Task RunProcessAsync(string fileName, string parameters, DirectoryInfo workingDirectory = null, CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); var tcs = new TaskCompletionSource(); if (fileName.EndsWith(".cmd") || fileName.EndsWith(".bat")) @@ -188,7 +197,7 @@ private static Task RunProcessAsync(string fileName, { try { - process.Kill(); + process.Kill(entireProcessTree: true); } catch (InvalidOperationException) { @@ -199,6 +208,6 @@ private static Task RunProcessAsync(string fileName, } }); - return tcs.Task; + return tcs.Task.WaitAsync(cancellationToken); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentMapping.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentMapping.cs index 84661e658..574c5c081 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentMapping.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentMapping.cs @@ -37,6 +37,8 @@ internal static class TypedComponentMapping { nameof(ComponentType.DotNet), typeof(DotNetComponent) }, { nameof(ComponentType.Swift), typeof(SwiftComponent) }, { nameof(ComponentType.CppSdk), typeof(CppSdkComponent) }, + { nameof(ComponentType.Composer), typeof(ComposerComponent) }, + { nameof(ComponentType.PhpSdk), typeof(PhpSdkComponent) }, }; /// diff --git a/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs b/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs index 45886d8a1..bd44aac7f 100644 --- a/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs +++ b/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs @@ -53,4 +53,7 @@ public enum DetectorClass /// Indicates a detector applies to Helm chart image references. Helm, + + /// Indicates a detector applies to Composer packages. + Composer, } diff --git a/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs b/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs index dc7ea6c26..ecf060350 100644 --- a/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs @@ -7,6 +7,7 @@ namespace Microsoft.ComponentDetection.Contracts; using System.IO; using System.Linq; using System.Reactive.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; @@ -17,6 +18,15 @@ namespace Microsoft.ComponentDetection.Contracts; /// Specialized base class for file based component detection. public abstract class FileComponentDetector : IComponentDetector { + /// + /// Gets opt-in JSON parsing options that skip comments and allow trailing commas. + /// + protected static readonly JsonDocumentOptions LenientJsonDocumentOptions = new() + { + CommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true, + }; + /// /// Gets or sets the factory for handing back component streams to File detectors. /// @@ -124,6 +134,8 @@ private async Task ProcessAsync( async processRequest => await this.OnFileFoundAsync(processRequest, detectorArgs, cleanupCreatedFiles, cancellationToken), new ExecutionDataflowBlockOptions { + CancellationToken = cancellationToken, + // MaxDegreeOfParallelism is the lower of the processor count and the max threads arg that the customer passed in MaxDegreeOfParallelism = threadsToUse, }); diff --git a/src/Microsoft.ComponentDetection.Contracts/ICommandLineInvocationService.cs b/src/Microsoft.ComponentDetection.Contracts/ICommandLineInvocationService.cs index e4a55f1c4..defd371ee 100644 --- a/src/Microsoft.ComponentDetection.Contracts/ICommandLineInvocationService.cs +++ b/src/Microsoft.ComponentDetection.Contracts/ICommandLineInvocationService.cs @@ -17,29 +17,42 @@ public interface ICommandLineInvocationService /// Used to gate logic that requires a command line execution environment. /// /// True if it is a command line execution environment, false otherwise. - bool IsCommandLineExecution(); + public bool IsCommandLineExecution(); /// - /// Checks to see if the given command can be located -- in cases of absolute paths, this is a simple File.Exists. For non-absolute paths, all PATH entries are checked. + /// Executes candidate commands until one exits successfully, then caches the working command. + /// Cancellation stops the current probe's process tree and the wait. Overloads without a token use CancellationToken.None. + /// + /// The command name to execute. + /// Alternative commands with the same calling pattern. + /// The directory under which to execute the probe. + /// Token used for cancelling command lookup. + /// Arguments to pass to each candidate command. + /// True if a candidate command exits successfully, false otherwise. + public Task CanCommandBeLocatedAsync(string command, IEnumerable additionalCandidateCommands, DirectoryInfo workingDirectory, CancellationToken cancellationToken, params string[] parameters); + + /// + /// Executes candidate commands until one exits successfully, then caches the working command. Uses CancellationToken.None. /// /// The command name to execute. Environment variables like PATH on windows will also be considered if the command is not an absolute path. /// Other commands that could satisfy the need for the first command. Assumption is that they all share similar calling patterns. /// The directory under which to execute the command. /// The parameters that should be passed to the command. The parameters will be space-joined. /// Awaitable task with true if the command can be found in the local environment, false otherwise. - Task CanCommandBeLocatedAsync(string command, IEnumerable additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters); + public Task CanCommandBeLocatedAsync(string command, IEnumerable additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters); /// - /// Checks to see if the given command can be located -- in cases of absolute paths, this is a simple File.Exists. For non-absolute paths, all PATH entries are checked. + /// Executes candidate commands until one exits successfully, then caches the working command. Uses CancellationToken.None. /// /// The command name to execute. Environment variables like PATH on windows will also be considered if the command is not an absolute path. /// Other commands that could satisfy the need for the first command. Assumption is that they all share similar calling patterns. /// The parameters that should be passed to the command. The parameters will be space-joined. /// Awaitable task with true if the command can be found in the local environment, false otherwise. - Task CanCommandBeLocatedAsync(string command, IEnumerable additionalCandidateCommands = null, params string[] parameters); + public Task CanCommandBeLocatedAsync(string command, IEnumerable additionalCandidateCommands = null, params string[] parameters); /// - /// Executes a command line command. If the command has not been located yet, CanCommandBeLocated will be invoked without the submitted parameters. + /// Executes a command line command. If not cached, the same arguments are first used to probe candidate commands. + /// The cancellation token applies to both the availability probe and execution. /// /// The command name to execute. Environment variables like PATH on windows will also be considered if the command is not an absolute path. /// Other commands that could satisfy the need for the first command. Assumption is that they all share similar calling patterns. @@ -47,20 +60,20 @@ public interface ICommandLineInvocationService /// Token used for cancelling the command. /// The parameters that should be passed to the command. The parameters will be space-joined. /// Awaitable task with the result of executing the command, including exit code. - Task ExecuteCommandAsync(string command, IEnumerable additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, CancellationToken cancellationToken = default, params string[] parameters); + public Task ExecuteCommandAsync(string command, IEnumerable additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, CancellationToken cancellationToken = default, params string[] parameters); /// - /// Executes a command line command. If the command has not been located yet, CanCommandBeLocated will be invoked without the submitted parameters. + /// Executes a command line command. If not cached, the same arguments are first used to probe candidate commands. /// /// The command name to execute. Environment variables like PATH on windows will also be considered if the command is not an absolute path. /// Other commands that could satisfy the need for the first command. Assumption is that they all share similar calling patterns. /// The parameters that should be passed to the command. The parameters will be space-joined. /// Awaitable task with the result of executing the command, including exit code. [Obsolete($"This implementation of {nameof(ExecuteCommandAsync)} is deprecated. Please use a version with CancellationTokens.")] - Task ExecuteCommandAsync(string command, IEnumerable additionalCandidateCommands = null, params string[] parameters); + public Task ExecuteCommandAsync(string command, IEnumerable additionalCandidateCommands = null, params string[] parameters); /// - /// Executes a command line command. If the command has not been located yet, CanCommandBeLocated will be invoked without the submitted parameters. + /// Executes a command line command. If not cached, the same arguments are first used to probe candidate commands. /// /// The command name to execute. Environment variables like PATH on windows will also be considered if the command is not an absolute path. /// Other commands that could satisfy the need for the first command. Assumption is that they all share similar calling patterns. @@ -68,17 +81,18 @@ public interface ICommandLineInvocationService /// The parameters that should be passed to the command. The parameters will be space-joined. /// Awaitable task with the result of executing the command, including exit code. [Obsolete($"This implementation of {nameof(ExecuteCommandAsync)} is deprecated. Please use a version with CancellationTokens.")] - Task ExecuteCommandAsync(string command, IEnumerable additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters); + public Task ExecuteCommandAsync(string command, IEnumerable additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters); /// - /// Executes a command line command. If the command has not been located yet, CanCommandBeLocated will be invoked without the submitted parameters. + /// Executes a command line command. If not cached, the same arguments are first used to probe candidate commands. + /// The cancellation token applies to both the availability probe and execution. /// /// The command name to execute. Environment variables like PATH on windows will also be considered if the command is not an absolute path. /// Other commands that could satisfy the need for the first command. Assumption is that they all share similar calling patterns. /// Token used for cancelling the command. /// The parameters that should be passed to the command. The parameters will be space-joined. /// Awaitable task with the result of executing the command, including exit code. - Task ExecuteCommandAsync(string command, IEnumerable additionalCandidateCommands = null, CancellationToken cancellationToken = default, params string[] parameters); + public Task ExecuteCommandAsync(string command, IEnumerable additionalCandidateCommands = null, CancellationToken cancellationToken = default, params string[] parameters); } /// diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComponentType.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComponentType.cs index 391bc82bc..8623b15b8 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComponentType.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComponentType.cs @@ -67,4 +67,10 @@ public enum ComponentType : byte [EnumMember] CppSdk = 20, + + [EnumMember] + Composer = 21, + + [EnumMember] + PhpSdk = 22, } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComposerComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComposerComponent.cs new file mode 100644 index 000000000..9960959d6 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComposerComponent.cs @@ -0,0 +1,41 @@ +#nullable disable +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; + +using System.Text.Json.Serialization; +using PackageUrl; + +/// A Composer package identified by its full vendor/package name and version. +public sealed class ComposerComponent : TypedComponent +{ + public ComposerComponent() + { + /* Reserved for deserialization */ + } + + public ComposerComponent(string name, string version) + { + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Composer)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Composer)); + } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("version")] + public string Version { get; set; } + + [JsonIgnore] + public override ComponentType Type => ComponentType.Composer; + + [JsonPropertyName("packageUrl")] + public override PackageURL PackageUrl + { + get + { + var separator = this.Name.IndexOf('/'); + return new PackageURL("composer", this.Name.Substring(0, separator), this.Name.Substring(separator + 1), this.Version, null, null); + } + } + + protected override string ComputeBaseId() => $"{this.Name} {this.Version} - {this.Type}"; +} diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PhpSdkComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PhpSdkComponent.cs new file mode 100644 index 000000000..63f9168a9 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PhpSdkComponent.cs @@ -0,0 +1,41 @@ +#nullable disable +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; + +using System.Collections.Generic; +using System.Text.Json.Serialization; +using PackageUrl; + +/// A PHP runtime, extension, library, or Composer tool observed in the scan environment. +public sealed class PhpSdkComponent : TypedComponent +{ + public PhpSdkComponent() + { + /* Reserved for deserialization */ + } + + public PhpSdkComponent(string name, string version) + { + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.PhpSdk)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.PhpSdk)); + } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("version")] + public string Version { get; set; } + + [JsonIgnore] + public override ComponentType Type => ComponentType.PhpSdk; + + [JsonPropertyName("packageUrl")] + public override PackageURL PackageUrl => new( + "generic", + null, + this.Name, + this.Version, + new SortedDictionary { { "type", "phpsdk" } }, + null); + + protected override string ComputeBaseId() => $"{this.Name} {this.Version} - {this.Type}"; +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs new file mode 100644 index 000000000..1093148d8 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs @@ -0,0 +1,829 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer; + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Reactive.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.ComponentDetection.Contracts; +using Microsoft.ComponentDetection.Contracts.Internal; +using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.Extensions.Logging; + +/// Reads Composer package files and optionally inventories the local PHP environment through Composer. +public sealed class ComposerComponentDetector : FileComponentDetector, IExperimentalDetector +{ + private const string ComposerLockFileName = "composer.lock"; + private const string ComposerManifestFileName = "composer.json"; + private const string InstalledPackagesFileName = "installed.json"; + private const string ComposerName = "composer"; + private const string DefaultVendorDirectoryName = "vendor"; + private const string PackagesPropertyName = "packages"; + private const string DevPackageNamesPropertyName = "dev-package-names"; + private const string NamePropertyName = "name"; + private const string VersionPropertyName = "version"; + private const string RequirePropertyName = "require"; + private const string RequireDevPropertyName = "require-dev"; + private const string ProvidePropertyName = "provide"; + private const string ReplacePropertyName = "replace"; + private const string ExtraPropertyName = "extra"; + private const string BranchAliasPropertyName = "branch-alias"; + private const string AliasesPropertyName = "aliases"; + private const string SelfVersionConstraint = "self.version"; + private static readonly TimeSpan PlatformInventoryTimeout = TimeSpan.FromSeconds(10); + + private readonly IEnvironmentVariableService environmentVariableService; + private readonly IFileUtilityService fileUtilityService; + private readonly ICommandLineInvocationService commandLineInvocationService; + private readonly ConcurrentHashSet coveredVendorDirectories = []; + private readonly ConcurrentHashSet knownPlatformVendorDirectories = []; + + public ComposerComponentDetector( + IComponentStreamEnumerableFactory componentStreamEnumerableFactory, + IObservableDirectoryWalkerFactory walkerFactory, + IEnvironmentVariableService environmentVariableService, + IFileUtilityService fileUtilityService, + ICommandLineInvocationService commandLineInvocationService, + ILogger logger) + { + this.ComponentStreamEnumerableFactory = componentStreamEnumerableFactory; + this.Scanner = walkerFactory; + this.environmentVariableService = environmentVariableService; + this.fileUtilityService = fileUtilityService; + this.commandLineInvocationService = commandLineInvocationService; + this.Logger = logger; + } + + public override string Id => "Composer"; + + public override IEnumerable Categories => [nameof(DetectorClass.Composer)]; + + public override IList SearchPatterns => [ComposerLockFileName, ComposerManifestFileName]; + + public override IEnumerable SupportedComponentTypes => [ComponentType.Composer, ComponentType.PhpSdk]; + + public override int Version => 1; + + public override bool NeedsAutomaticRootDependencyCalculation => false; + + protected override async Task> OnPrepareDetectionAsync( + IObservable processRequests, + IDictionary detectorArgs, + CancellationToken cancellationToken = default) + { + this.coveredVendorDirectories.Clear(); + this.knownPlatformVendorDirectories.Clear(); + var files = await processRequests.ToList(); + cancellationToken.ThrowIfCancellationRequested(); + + // Process projects before their installed packages, regardless of discovery order. Return only the lockfiles when both a manifest and lockfile are present in the same directory. + return files.GroupBy(request => Path.GetDirectoryName(request.ComponentStream.Location)) + .OrderBy(group => group.Key!.Length) + .Select(group => group.FirstOrDefault(request => Path.GetFileName(request.ComponentStream.Location).Equals(ComposerLockFileName, StringComparison.OrdinalIgnoreCase)) ?? group.First()) + .ToObservable(); + } + + protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary detectorArgs, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + var file = processRequest.ComponentStream; + + // Check if current or a parent directory were scanned already to improve perf and avoid noise from child manifest files. + for (var directory = Path.GetDirectoryName(file.Location); directory is not null; directory = Path.GetDirectoryName(directory)) + { + if (this.coveredVendorDirectories.Contains(directory)) + { + this.Logger.LogDebug("Ignoring Composer file {Location} inside an already processed project's vendor directory.", file.Location); + return; + } + } + + var recorder = processRequest.SingleFileComponentRecorder; + this.Logger.LogDebug("Reading Composer file {Location}", file.Location); + using var document = await this.ReadDocumentAsync(file.Stream, file.Location, recorder, cancellationToken); + if (document is null) + { + return; + } + + var isManifest = Path.GetFileName(file.Location).Equals(ComposerManifestFileName, StringComparison.OrdinalIgnoreCase); + using var manifest = isManifest ? null : await this.ReadManifestAsync(file.Location, recorder, cancellationToken); + var manifestRoot = isManifest ? document.RootElement : manifest?.RootElement; + var vendorDirectory = this.GetVendorDirectory(file.Location, manifestRoot); + this.knownPlatformVendorDirectories.Add(vendorDirectory); + await this.RegisterPlatformInventoryAsync(file.Location, recorder, cancellationToken); + + var packages = new Dictionary(); + if (isManifest) + { + if (!await this.ReadInstalledPackagesAsync(vendorDirectory, packages, recorder, cancellationToken)) + { + this.Logger.LogWarning( + $"Composer manifest {{Location}} without a sibling {ComposerLockFileName} or usable {InstalledPackagesFileName}. Provide either to improve accuracy; otherwise only exact versions are detected.", + file.Location); + this.ReadManifestRequirements(document.RootElement, recorder, file.Location, cancellationToken); + return; + } + } + else + { + this.ReadPackages(document.RootElement, PackagesPropertyName, false, packages, recorder, cancellationToken); + this.ReadPackages(document.RootElement, "packages-dev", true, packages, recorder, cancellationToken); + this.ReadLockAliases(document.RootElement, packages, recorder, cancellationToken); + } + + this.coveredVendorDirectories.Add(vendorDirectory); + this.RegisterPackages(packages, manifestRoot, recorder, cancellationToken); + } + + private static Dictionary> CreateProviderLookup(Dictionary packages) + { + var providers = new Dictionary>(StringComparer.Ordinal); + foreach (var package in packages.Values) + { + foreach (var (name, constraint) in package.Provides.Concat(package.Replaces)) + { + if (!providers.TryGetValue(name, out var claims)) + { + providers[name] = claims = []; + } + + if (constraint == SelfVersionConstraint) + { + claims.Add((package, package.Component.Version)); + foreach (var alias in package.Aliases) + { + claims.Add((package, alias)); + } + } + else + { + claims.Add((package, constraint)); + } + } + } + + return providers; + } + + private static bool TryGetNonEmptyString(JsonElement entry, string propertyName, [NotNullWhen(true)] out string? value) + { + value = entry.ValueKind == JsonValueKind.Object && entry.TryGetProperty(propertyName, out var property) && property.ValueKind == JsonValueKind.String + ? property.GetString() + : null; + return !string.IsNullOrWhiteSpace(value); + } + + private void RegisterPackages( + Dictionary packages, + JsonElement? manifestRoot, + ISingleFileComponentRecorder recorder, + CancellationToken cancellationToken) + { + // Names and aliases are lookup keys, never additional detected components. + var names = packages.Values.GroupBy(package => package.Component.Name.Trim(), StringComparer.OrdinalIgnoreCase) + .ToDictionary(group => group.Key, group => group.ToList(), StringComparer.OrdinalIgnoreCase); + var providers = CreateProviderLookup(packages); + var rootClaims = manifestRoot is null + ? [] + : this.ReadRootClaims(manifestRoot.Value, recorder); + var roots = manifestRoot is null + ? [] + : this.ReadLinks(manifestRoot.Value, RequirePropertyName, recorder, ComposerManifestFileName) + .Concat(this.ReadLinks(manifestRoot.Value, RequireDevPropertyName, recorder, ComposerManifestFileName)) + .Select(pair => this.Resolve(pair.Key, pair.Value, names, providers, rootClaims)?.Component.Id) + .OfType().ToHashSet(); + + foreach (var package in packages.Values) + { + cancellationToken.ThrowIfCancellationRequested(); + recorder.RegisterUsage(new DetectedComponent(package.Component), isExplicitReferencedDependency: roots.Contains(package.Component.Id), isDevelopmentDependency: package.IsDevelopment); + } + + foreach (var package in packages.Values) + { + foreach (var (name, constraint) in package.Requires) + { + cancellationToken.ThrowIfCancellationRequested(); + var dependency = this.Resolve(name, constraint, names, providers, rootClaims); + if (dependency is not null && dependency.Component.Id != package.Component.Id) + { + recorder.RegisterUsage(new DetectedComponent(dependency.Component), parentComponentId: package.Component.Id, isDevelopmentDependency: dependency.IsDevelopment); + } + } + } + + if (manifestRoot is null) + { + foreach (var root in ComposerGraph.FindRoots(recorder.DependencyGraph, packages.Keys, cancellationToken)) + { + cancellationToken.ThrowIfCancellationRequested(); + var package = packages[root]; + recorder.RegisterUsage(new DetectedComponent(package.Component), isExplicitReferencedDependency: true, isDevelopmentDependency: package.IsDevelopment); + } + } + } + + private async Task RegisterPlatformInventoryAsync(string location, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + for (var directory = Path.GetDirectoryName(location); directory is not null; directory = Path.GetDirectoryName(directory)) + { + if (this.knownPlatformVendorDirectories.Contains(directory) || Path.GetFileName(directory).Equals(DefaultVendorDirectoryName, StringComparison.OrdinalIgnoreCase)) + { + this.Logger.LogDebug("Skipping Composer platform inventory for {Location} inside a vendor directory.", location); + return; + } + } + + if (!this.commandLineInvocationService.IsCommandLineExecution()) + { + this.Logger.LogDebug("Composer platform inventory requires command-line execution; only package files will be scanned."); + return; + } + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(PlatformInventoryTimeout); + CommandLineExecutionResult result; + try + { + string[] arguments = ["--no-plugins", "--no-scripts", "--no-interaction", "--no-ansi", "show", "--platform", "--format=json"]; + result = await this.commandLineInvocationService.ExecuteCommandAsync( + ComposerName, [$"{ComposerName}.cmd", $"{ComposerName}.bat"], new DirectoryInfo(Path.GetDirectoryName(location)!), timeout.Token, arguments); + timeout.Token.ThrowIfCancellationRequested(); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + this.Logger.LogWarning("Composer platform inventory exceeded its {TimeoutSeconds}-second limit; continuing with package files only.", PlatformInventoryTimeout.TotalSeconds); + return; + } + catch (Exception exception) + { + this.Logger.LogWarning(exception, "Unable to run Composer platform inventory; continuing with package files only."); + return; + } + + if (result.ExitCode != 0) + { + this.Logger.LogWarning("Composer platform inventory failed with exit code {ExitCode}: {StdErr}", result.ExitCode, result.StdErr); + return; + } + + this.RegisterPlatformComponents(result.StdOut, recorder, cancellationToken); + } + + private void RegisterPlatformComponents(string output, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + try + { + using var document = JsonDocument.Parse(output); + if (document.RootElement.ValueKind != JsonValueKind.Object || + !document.RootElement.TryGetProperty("platform", out var entries) || entries.ValueKind != JsonValueKind.Array) + { + this.Logger.LogWarning("Composer platform inventory did not contain a platform array; no environment components will be reported."); + return; + } + + foreach (var entry in entries.EnumerateArray()) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!TryGetNonEmptyString(entry, NamePropertyName, out var packageName) || + !TryGetNonEmptyString(entry, VersionPropertyName, out var version)) + { + this.Logger.LogWarning("Composer platform inventory contained an invalid package identity; the entry is omitted."); + continue; + } + + if (packageName.Contains('/', StringComparison.Ordinal) || + (packageName is not ("php" or "hhvm" or ComposerName) && + !packageName.StartsWith("ext-", StringComparison.Ordinal) && !packageName.StartsWith("lib-", StringComparison.Ordinal))) + { + continue; + } + + if (entry.TryGetProperty("description", out var description) && description.ValueKind == JsonValueKind.String && + description.GetString()!.Contains("via config.platform", StringComparison.Ordinal)) + { + this.Logger.LogDebug("Composer platform entry {Name} is simulated or disabled by config.platform; its configured version is not reported as installed.", packageName); + continue; + } + + var hasDirectDependency = entry.TryGetProperty("direct-dependency", out var directDependency); + if (hasDirectDependency && directDependency.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) + { + this.Logger.LogWarning("Composer platform entry {Name} has invalid direct-dependency metadata; it is not marked explicitly referenced.", packageName); + } + + recorder.RegisterUsage( + new DetectedComponent(new PhpSdkComponent(packageName, version)), + isExplicitReferencedDependency: hasDirectDependency && directDependency.ValueKind == JsonValueKind.True, + isDevelopmentDependency: true); + } + } + catch (JsonException exception) + { + this.Logger.LogWarning(exception, "Composer platform inventory was not valid JSON; no environment components will be reported."); + } + } + + private void MergeLinks(Dictionary target, Dictionary source, HashSet conflicts, string section, ISingleFileComponentRecorder recorder, string location) + { + foreach (var (name, constraint) in source) + { + var key = $"{section}.{name}"; + if (conflicts.Contains(key)) + { + continue; + } + + if (target.TryGetValue(name, out var existing) && existing != constraint) + { + this.ReportFailure(recorder, $"{location}.{key}", "Duplicate locked identity declares conflicting constraints; this dependency declaration is omitted."); + target.Remove(name); + conflicts.Add(key); + } + else + { + target.TryAdd(name, constraint); + } + } + } + + private string GetVendorDirectory(string location, JsonElement? manifest) + { + var projectDirectory = Path.GetDirectoryName(location)!; + var defaultVendorDirectory = Path.Combine(projectDirectory, DefaultVendorDirectoryName); + var vendorDirectory = this.environmentVariableService.GetEnvironmentVariable("COMPOSER_VENDOR_DIR"); + if (string.IsNullOrWhiteSpace(vendorDirectory)) + { + vendorDirectory = DefaultVendorDirectoryName; + if (manifest is not null && manifest.Value.TryGetProperty("config", out var config)) + { + if (config.ValueKind != JsonValueKind.Object) + { + this.Logger.LogWarning("Invalid Composer config at {Location}; using the default vendor directory.", location); + return defaultVendorDirectory; + } + + if (config.TryGetProperty("vendor-dir", out var configuredDirectory)) + { + if (configuredDirectory.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(configuredDirectory.GetString())) + { + this.Logger.LogWarning("Invalid Composer config.vendor-dir at {Location}; using the default vendor directory.", location); + return defaultVendorDirectory; + } + + vendorDirectory = configuredDirectory.GetString()!; + } + } + } + + try + { + return Path.TrimEndingDirectorySeparator(Path.GetFullPath(vendorDirectory, projectDirectory)); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + this.Logger.LogWarning(exception, "Invalid Composer vendor directory at {Location}; using the default vendor directory.", location); + return defaultVendorDirectory; + } + } + + private async Task ReadInstalledPackagesAsync(string vendorDirectory, Dictionary packages, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + var location = Path.Combine(vendorDirectory, ComposerName, InstalledPackagesFileName); + if (!this.fileUtilityService.Exists(location)) + { + return false; + } + + using var stream = this.fileUtilityService.MakeFileStream(location); + using var document = await this.ReadDocumentAsync(stream, location, recorder, cancellationToken, allowPackageArray: true); + if (document is null) + { + return false; + } + + var root = document.RootElement; + if (root.ValueKind == JsonValueKind.Object && (!root.TryGetProperty(PackagesPropertyName, out var entries) || entries.ValueKind != JsonValueKind.Array)) + { + this.ReportFailure(recorder, location, $"Expected an installed package array in {PackagesPropertyName}."); + return false; + } + + this.ReadPackages(root, PackagesPropertyName, false, packages, recorder, cancellationToken); + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty(DevPackageNamesPropertyName, out var devNames)) + { + return true; + } + + if (devNames.ValueKind != JsonValueKind.Array) + { + this.ReportFailure(recorder, $"{location}.{DevPackageNamesPropertyName}", "Expected an array of development package names."); + return true; + } + + var developmentPackages = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var name in devNames.EnumerateArray()) + { + if (name.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(name.GetString())) + { + this.ReportFailure(recorder, $"{location}.{DevPackageNamesPropertyName}", "Expected a nonempty development package name."); + continue; + } + + developmentPackages.Add(name.GetString()!.Trim()); + } + + foreach (var package in packages.Values) + { + package.IsDevelopment = developmentPackages.Contains(package.Component.Name.Trim()); + } + + return true; + } + + private async Task ReadDocumentAsync(Stream stream, string location, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken, bool allowPackageArray = false) + { + try + { + var document = await JsonDocument.ParseAsync(stream, LenientJsonDocumentOptions, cancellationToken); + if (document.RootElement.ValueKind == JsonValueKind.Object || (allowPackageArray && document.RootElement.ValueKind == JsonValueKind.Array)) + { + return document; + } + + document.Dispose(); + this.ReportFailure(recorder, location, allowPackageArray ? "Expected a JSON object or installed package array." : "Expected a JSON object."); + } + catch (JsonException exception) + { + this.Logger.LogError(exception, "Invalid Composer JSON in {Location}", location); + recorder.RegisterPackageParseFailure(location); + } + + return null; + } + + private async Task ReadManifestAsync(string lockLocation, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + var directory = new DirectoryInfo(Path.GetDirectoryName(lockLocation)!); + foreach (var file in this.ComponentStreamEnumerableFactory.GetComponentStreams( + directory, [ComposerManifestFileName], null, recursivelyScanDirectories: false)) + { + cancellationToken.ThrowIfCancellationRequested(); + return await this.ReadDocumentAsync(file.Stream, file.Location, recorder, cancellationToken); + } + + return null; + } + + private void ReadPackages(JsonElement root, string section, bool isDevelopment, Dictionary packages, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + var entries = root; + if (root.ValueKind != JsonValueKind.Array && !root.TryGetProperty(section, out entries)) + { + return; + } + + if (entries.ValueKind != JsonValueKind.Array) + { + this.ReportFailure(recorder, section, "Expected a package array."); + return; + } + + var index = 0; + foreach (var entry in entries.EnumerateArray()) + { + cancellationToken.ThrowIfCancellationRequested(); + var location = $"{section}[{index++}]"; + if (!TryGetNonEmptyString(entry, NamePropertyName, out var name) || + !TryGetNonEmptyString(entry, VersionPropertyName, out var version)) + { + this.ReportFailure(recorder, location, "Expected a package with nonempty string name and version."); + continue; + } + + var packageName = name.Trim(); + var separator = packageName.IndexOf('/'); + if (separator <= 0 || separator == packageName.Length - 1) + { + this.ReportFailure(recorder, location, "Expected a nonempty vendor and package name for a Composer package URL."); + continue; + } + + var component = new ComposerComponent(name, version); + var package = new LockedPackage( + component, + isDevelopment, + this.ReadLinks(entry, RequirePropertyName, recorder, location), + this.ReadLinks(entry, ProvidePropertyName, recorder, location), + this.ReadLinks(entry, ReplacePropertyName, recorder, location), + this.ReadBranchAliases(entry, component.Version.Trim(), recorder, location)); + if (packages.TryGetValue(component.Id, out var existing)) + { + // A package needed in production is never development-only, irrespective of entry order. + existing.IsDevelopment &= isDevelopment; + this.MergeLinks(existing.Requires, package.Requires, existing.Conflicts, RequirePropertyName, recorder, location); + this.MergeLinks(existing.Provides, package.Provides, existing.Conflicts, ProvidePropertyName, recorder, location); + this.MergeLinks(existing.Replaces, package.Replaces, existing.Conflicts, ReplacePropertyName, recorder, location); + existing.Aliases.UnionWith(package.Aliases); + } + else + { + packages.Add(component.Id, package); + } + } + } + + private HashSet ReadBranchAliases(JsonElement entry, string version, ISingleFileComponentRecorder recorder, string location) + { + if (!entry.TryGetProperty(ExtraPropertyName, out var extra) || extra.ValueKind != JsonValueKind.Object || + !extra.TryGetProperty(BranchAliasPropertyName, out var aliases)) + { + return []; + } + + var aliasLocation = $"{location}.{ExtraPropertyName}.{BranchAliasPropertyName}"; + if (aliases.ValueKind != JsonValueKind.Object) + { + this.ReportFailure(recorder, aliasLocation, "Expected a branch alias object."); + return []; + } + + if (aliases.TryGetProperty(version, out var alias)) + { + var aliasValue = alias.ValueKind == JsonValueKind.String ? alias.GetString() : null; + if (!string.IsNullOrWhiteSpace(aliasValue)) + { + return [aliasValue.Trim()]; + } + + this.ReportFailure(recorder, $"{aliasLocation}.{version}", "Expected a nonempty branch alias."); + } + + return []; + } + + private void ReadLockAliases(JsonElement root, Dictionary packages, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + if (!root.TryGetProperty(AliasesPropertyName, out var aliases)) + { + return; + } + + if (aliases.ValueKind != JsonValueKind.Array) + { + this.ReportFailure(recorder, AliasesPropertyName, "Expected an alias array."); + return; + } + + var packagesByName = packages.Values.ToLookup(package => package.Component.Name.Trim(), StringComparer.OrdinalIgnoreCase); + var index = 0; + foreach (var entry in aliases.EnumerateArray()) + { + cancellationToken.ThrowIfCancellationRequested(); + var location = $"{AliasesPropertyName}[{index++}]"; + if (!TryGetNonEmptyString(entry, "package", out var name) || + !TryGetNonEmptyString(entry, VersionPropertyName, out var version) || + !TryGetNonEmptyString(entry, "alias", out var alias)) + { + this.ReportFailure(recorder, location, "Expected nonempty string package, version and alias fields."); + continue; + } + + var matching = packagesByName[name.Trim()] + .Where(package => ComposerVersionConstraint.VersionsEqual(package.Component.Version, version)).ToList(); + if (matching.Count == 1) + { + matching[0].Aliases.Add(alias.Trim()); + } + else + { + this.Logger.LogWarning("Composer alias at {Location} does not uniquely identify an installed package.", location); + } + } + } + + [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Composer package lookup names require lowercase.")] + private Dictionary ReadLinks(JsonElement entry, string section, ISingleFileComponentRecorder recorder, string location) + { + var links = new Dictionary(StringComparer.Ordinal); + var conflicts = new HashSet(StringComparer.Ordinal); + if (!entry.TryGetProperty(section, out var value)) + { + return links; + } + + if (value.ValueKind != JsonValueKind.Object) + { + this.ReportFailure(recorder, $"{location}.{section}", "Expected a dependency object."); + return links; + } + + foreach (var property in value.EnumerateObject()) + { + var name = property.Name.Trim().ToLowerInvariant(); + if (property.Value.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(property.Value.GetString())) + { + this.ReportFailure(recorder, $"{location}.{section}.{name}", "Expected a nonempty version constraint."); + continue; + } + + // php, ext-*, lib-* and composer-* platform requirements do not have a vendor namespace. + // Names such as composer/installers and ext-vendor/package are real packages, not platforms. + if (!name.Contains('/', StringComparison.Ordinal)) + { + this.Logger.LogDebug( + "Skipping Composer dependency {Name} at {Location} without a vendor namespace; it may be a platform requirement.", + name, + $"{location}.{section}"); + continue; + } + + if (name.StartsWith('/') || name.EndsWith('/')) + { + this.ReportFailure(recorder, $"{location}.{section}.{name}", "Expected a nonempty vendor and package name for a Composer package URL."); + continue; + } + + var constraint = property.Value.GetString()!.Trim(); + if (conflicts.Contains(name)) + { + continue; + } + + if (links.TryGetValue(name, out var previous) && previous != constraint) + { + this.ReportFailure(recorder, $"{location}.{section}.{name}", "Duplicate dependency name declares conflicting constraints; the declaration is omitted."); + links.Remove(name); + conflicts.Add(name); + } + else + { + links[name] = constraint; + } + } + + return links; + } + + [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Composer package lookup names require lowercase.")] + private void ReadManifestRequirements(JsonElement root, ISingleFileComponentRecorder recorder, string location, CancellationToken cancellationToken) + { + foreach (var (section, isDevelopment) in new[] { (RequirePropertyName, false), (RequireDevPropertyName, true) }) + { + var requirements = this.ReadLinks(root, section, recorder, location); + if (requirements.Count == 0) + { + continue; + } + + foreach (var property in root.GetProperty(section).EnumerateObject()) + { + cancellationToken.ThrowIfCancellationRequested(); + var name = property.Name; + if (!requirements.Remove(name.Trim().ToLowerInvariant(), out var constraint)) + { + continue; + } + + if (!ComposerVersionConstraint.TryGetExactVersion(constraint, out var version)) + { + this.Logger.LogWarning( + $"Composer dependency {{Name}} at {{Location}} has unresolved constraint {{Constraint}}; this declaration is omitted. Provide {ComposerLockFileName}, {InstalledPackagesFileName}, or an exact version to improve accuracy.", + name, + location, + constraint); + continue; + } + + recorder.RegisterUsage( + new DetectedComponent(new ComposerComponent(name, version)), + isExplicitReferencedDependency: true, + isDevelopmentDependency: isDevelopment); + } + } + } + + private Dictionary> ReadRootClaims(JsonElement root, ISingleFileComponentRecorder recorder) + { + var claims = this.ReadLinks(root, ProvidePropertyName, recorder, ComposerManifestFileName) + .Concat(this.ReadLinks(root, ReplacePropertyName, recorder, ComposerManifestFileName)) + .GroupBy(pair => pair.Key).ToDictionary(group => group.Key, group => group.Select(pair => pair.Value).ToList()); + if (claims.Values.Any(constraints => constraints.Contains(SelfVersionConstraint)) && + TryGetNonEmptyString(root, VersionPropertyName, out var version)) + { + var rootVersion = version.Trim(); + var versions = this.ReadBranchAliases(root, rootVersion, recorder, ComposerManifestFileName); + versions.Add(rootVersion); + foreach (var name in claims.Keys.ToList()) + { + claims[name] = claims[name].SelectMany(constraint => constraint == SelfVersionConstraint ? versions : [constraint]).ToList(); + } + } + + // Without a declared root version, self.version cannot be inferred offline from Git. + // Leave it unresolved so Resolve declines to guess an edge to an installed provider. + return claims; + } + + private LockedPackage? Resolve( + string name, + string constraint, + Dictionary> names, + Dictionary> providers, + Dictionary> rootClaims) + { + if (names.TryGetValue(name, out var actual)) + { + if (actual.Count == 1) + { + // Resolved identities are authoritative, including branch aliases and references. + return actual[0]; + } + + this.Logger.LogWarning("Composer dependency {Name} has multiple resolved versions; no edge can be inferred.", name); + return null; + } + + if (rootClaims.TryGetValue(name, out var rootConstraints)) + { + foreach (var rootConstraint in rootConstraints) + { + if (!ComposerVersionConstraint.TryIntersects(constraint, rootConstraint, out var compatible)) + { + this.Logger.LogWarning("Composer root virtual dependency {Name} has an unresolved constraint; no edge can be inferred offline.", name); + return null; + } + + if (compatible) + { + // Root-provided virtual dependencies are not components of the locked package graph. + return null; + } + } + } + + if (!providers.TryGetValue(name, out var claims)) + { + this.Logger.LogWarning("Composer dependency {Name} is not present in the resolved package inventory.", name); + return null; + } + + var candidates = new HashSet(); + foreach (var (package, declaredConstraint) in claims) + { + if (!ComposerVersionConstraint.TryIntersects(constraint, declaredConstraint, out var compatible)) + { + this.Logger.LogWarning("Composer virtual dependency {Name} has an unsupported constraint; provider uniqueness cannot be established.", name); + return null; + } + + if (compatible) + { + candidates.Add(package); + } + } + + if (candidates.Count == 1) + { + return candidates.Single(); + } + + this.Logger.LogWarning("Composer virtual dependency {Name} has {Count} compatible installed providers; no edge can be inferred.", name, candidates.Count); + return null; + } + + private void ReportFailure(ISingleFileComponentRecorder recorder, string location, string reason) + { + this.Logger.LogError("Malformed Composer data at {Location}: {Reason}", location, reason); + recorder.RegisterPackageParseFailure(location); + } + + private sealed class LockedPackage( + ComposerComponent component, + bool isDevelopment, + Dictionary requires, + Dictionary provides, + Dictionary replaces, + HashSet aliases) + { + internal ComposerComponent Component { get; } = component; + + internal bool IsDevelopment { get; set; } = isDevelopment; + + internal Dictionary Requires { get; } = requires; + + internal Dictionary Provides { get; } = provides; + + internal Dictionary Replaces { get; } = replaces; + + internal HashSet Aliases { get; } = aliases; + + internal HashSet Conflicts { get; } = []; + } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/ComposerGraph.cs b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerGraph.cs new file mode 100644 index 000000000..9c9dff78d --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerGraph.cs @@ -0,0 +1,82 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer; + +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Microsoft.ComponentDetection.Contracts; + +/// Infers candidate roots from source strongly connected groups when no root manifest exists. +internal static class ComposerGraph +{ + internal static HashSet FindRoots(IDependencyGraph graph, IEnumerable componentIds, CancellationToken cancellationToken) + { + // Iterative Kosaraju traversal avoids exhausting the stack on long dependency chains. + var visited = new HashSet(); + var order = new List(); + foreach (var start in componentIds) + { + var stack = new Stack<(string Id, bool Finished)>(); + stack.Push((start, false)); + while (stack.TryPop(out var entry)) + { + cancellationToken.ThrowIfCancellationRequested(); + if (entry.Finished) + { + order.Add(entry.Id); + } + else if (visited.Add(entry.Id)) + { + stack.Push((entry.Id, true)); + foreach (var child in graph.GetDependenciesForComponent(entry.Id)) + { + if (!visited.Contains(child)) + { + stack.Push((child, false)); + } + } + } + } + } + + var reverse = componentIds.ToDictionary(id => id, _ => new HashSet()); + foreach (var parent in componentIds) + { + foreach (var child in graph.GetDependenciesForComponent(parent)) + { + reverse[child].Add(parent); + } + } + + var groups = new Dictionary(); + for (var index = order.Count - 1; index >= 0; index--) + { + var stack = new Stack(); + stack.Push(order[index]); + while (stack.TryPop(out var id)) + { + cancellationToken.ThrowIfCancellationRequested(); + if (groups.TryAdd(id, index)) + { + foreach (var parent in reverse[id]) + { + stack.Push(parent); + } + } + } + } + + var nonRootGroups = new HashSet(); + foreach (var (child, parents) in reverse) + { + foreach (var parent in parents) + { + if (groups[parent] != groups[child]) + { + nonRootGroups.Add(groups[child]); + } + } + } + + return groups.Where(pair => !nonRootGroups.Contains(pair.Value)).Select(pair => pair.Key).ToHashSet(); + } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/ComposerVersionConstraint.cs b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerVersionConstraint.cs new file mode 100644 index 000000000..73570d504 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerVersionConstraint.cs @@ -0,0 +1,397 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer; + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; + +/// Compares virtual-package declarations without inventing a version for the virtual package. +/// +/// Local patterns implement a subset of the syntax in +/// Composer's upstream version parser. +/// +internal static class ComposerVersionConstraint +{ + private static readonly TimeSpan RegexTimeout = TimeSpan.FromSeconds(3); + private static readonly Regex LockedBranchRegex = new( + @"^(?\d+(?:\.\d+){0,2})\.[xX*](?:\.[xX*])*-dev$", + RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex StabilityFlagRegex = new( + @"@(dev|alpha|beta|RC|stable)\b", + RegexOptions.Compiled | RegexOptions.IgnoreCase, + RegexTimeout); + + private static readonly Regex HyphenRangeRegex = new( + @"^\s*(\S+)\s+-\s+(\S+)\s*$", + RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex ConstraintTokenRegex = new( + @"^(?!=|<>|>=|<=|==|[=><~^])?\s*(?[^\s]+)(?: +as +[^,\s]+)?", + RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex WildcardVersionRegex = new( + @"^[vV]?(?\d+(?:\.\d+){0,2})\.(?:[xX*])(?:\.[xX*])*(?:-dev)?$", + RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex NumericVersionRegex = new( + @"^[vV]?(?\d+(?:\.\d+){0,3})(?:[._-]?(?dev|alpha|beta|rc|stable|patch|pl|p|a|b)[.-]?(?\d*))?(?:\+[a-zA-Z0-9.-]+)?$", + RegexOptions.Compiled | RegexOptions.IgnoreCase, + RegexTimeout); + + internal static bool TryGetExactVersion(string constraint, out string version) + { + version = constraint.Trim(); + if (version.StartsWith("==", StringComparison.Ordinal)) + { + version = version[2..].TrimStart(); + } + else if (version.StartsWith('=')) + { + version = version[1..].TrimStart(); + } + + // Branch names and aliases do not identify an installed revision without a lockfile. + return TryVersion(version, out _, out _, out _); + } + + internal static bool Intersects(string required, string provided) => + TryIntersects(required, provided, out var intersects) && intersects; + + internal static bool TryIntersects(string required, string provided, out bool intersects) + { + intersects = false; + if (!TryParse(required, out var requirement) || !TryParse(provided, out var provision)) + { + return false; + } + + intersects = requirement.Any(left => provision.Any(right => left.Intersect(right).IsNonempty)); + return true; + } + + internal static bool VersionsEqual(string left, string right) + { + left = left.Trim(); + right = right.Trim(); + return left.Equals(right, StringComparison.Ordinal) || + (TryLockedVersion(left, out var first) && TryLockedVersion(right, out var second) && first == second); + } + + private static bool TryLockedVersion(string text, out ComposerVersion version) + { + if (TryVersion(text, out version, out _, out _)) + { + return true; + } + + var branch = LockedBranchRegex.Match(text); + if (!branch.Success) + { + return false; + } + + var segments = branch.Groups["prefix"].Value.Split('.'); + var normalized = string.Join('.', segments.Concat(Enumerable.Repeat("9999999", 4 - segments.Length))); + return TryVersion($"{normalized}-dev", out version, out _, out _); + } + + private static bool TryParse(string text, out List alternatives) + { + alternatives = []; + text = StabilityFlagRegex.Replace(text.Trim(), string.Empty); + foreach (var alternative in text.Split(["||", "|"], StringSplitOptions.TrimEntries)) + { + // Hyphen bounds retain Composer's precision-sensitive inclusive upper limit. + var hyphen = HyphenRangeRegex.Match(alternative); + if (hyphen.Success) + { + if (!TryVersion(hyphen.Groups[1].Value, out var lower, out _, out var lowerSuffix) || + !TryVersion(hyphen.Groups[2].Value, out var upper, out var precision, out _)) + { + return false; + } + + if (precision < 3) + { + if (!TryUpperBound(upper, precision - 1, out upper)) + { + return false; + } + + alternatives.Add(VersionSet.Numeric(new Interval(lowerSuffix ? lower : lower.WithDevStability(), true, upper, false))); + } + else + { + alternatives.Add(VersionSet.Numeric(new Interval(lowerSuffix ? lower : lower.WithDevStability(), true, upper, true))); + } + + continue; + } + + var remaining = alternative.Replace(',', ' ').Trim(); + var result = VersionSet.All(); + if (remaining.Length == 0) + { + return false; + } + + while (remaining.Length > 0) + { + // Native parseConstraint compares an inline alias's source, not its display alias. + // Consume aliasing per constraint so surrounding AND/OR terms remain intact. + var token = ConstraintTokenRegex.Match(remaining); + if (!token.Success || !TryToken(token.Groups["op"].Value, token.Groups["version"].Value, out var constraint)) + { + return false; + } + + result = result.Intersect(constraint); + remaining = remaining[token.Length..].TrimStart(); + } + + alternatives.Add(result); + } + + return true; + } + + private static bool TryToken(string operation, string text, out VersionSet result) + { + result = VersionSet.Empty(); + var reference = text.IndexOf('#', StringComparison.Ordinal); + if (reference >= 0) + { + text = text[..reference]; + } + + if (text is "*" or "x" or "X") + { + if (operation is "" or "=" or "==") + { + result = VersionSet.All(); + return true; + } + + return false; + } + + if (text.StartsWith("dev-", StringComparison.Ordinal) && text.Length > 4) + { + if (operation is "" or "=" or "==") + { + result.Branch = text; + return true; + } + + if (operation is "!=" or "<>") + { + result = VersionSet.All(); + result.ExcludedBranches.Add(text); + return true; + } + + return false; + } + + var wildcard = WildcardVersionRegex.Match(text); + if (wildcard.Success) + { + if (operation is not ("" or "=" or "==") || + !TryVersion(wildcard.Groups["prefix"].Value, out var minimum, out var precision, out _) || + !TryUpperBound(minimum, precision - 1, out var maximum)) + { + return false; + } + + result = VersionSet.Numeric(new Interval(minimum.WithDevStability(), true, maximum, false)); + return true; + } + + if (!TryVersion(text, out var version, out var parts, out var hasSuffix)) + { + return false; + } + + // Composer's implicit >= and < bounds use dev stability; npm-style ranges differ. + var bound = !hasSuffix && operation is ">=" or "<" ? version.WithDevStability() : version; + switch (operation) + { + case "": + case "=": + case "==": + result = VersionSet.Numeric(new Interval(version, true, version, true)); + break; + case "!=": + case "<>": + result = VersionSet.All(); + result.Intervals = [new Interval(null, false, version, false), new Interval(version, false, null, false)]; + break; + case ">": + case ">=": + result = VersionSet.Numeric(new Interval(bound, operation == ">=", null, false)); + break; + case "<": + case "<=": + result = VersionSet.Numeric(new Interval(null, false, bound, operation == "<=")); + break; + case "~": + case "^": + var index = operation == "~" ? Math.Max(0, parts - 2) : + version.Major != 0 || parts == 1 ? 0 : version.Minor != 0 || parts == 2 ? 1 : 2; + if (!TryUpperBound(version, index, out var upper)) + { + return false; + } + + result = VersionSet.Numeric(new Interval(hasSuffix ? version : version.WithDevStability(), true, upper, false)); + break; + default: + return false; + } + + return true; + } + + private static bool TryVersion(string text, out ComposerVersion version, out int precision, out bool hasSuffix) + { + version = default; + precision = 0; + hasSuffix = false; + var match = NumericVersionRegex.Match(text); + if (!match.Success) + { + return false; + } + + var segments = match.Groups["number"].Value.Split('.'); + var numbers = new long[4]; + for (var index = 0; index < segments.Length; index++) + { + if (!long.TryParse(segments[index], NumberStyles.None, CultureInfo.InvariantCulture, out numbers[index])) + { + return false; + } + } + + hasSuffix = match.Groups["stability"].Success; + var stability = match.Groups["stability"].Value.ToUpperInvariant() switch + { + "DEV" => 0, + "ALPHA" or "A" => 1, + "BETA" or "B" => 2, + "RC" => 3, + "PATCH" or "PL" or "P" => 5, + _ => 4, + }; + var suffix = 0L; + if (match.Groups["suffix"].Value.Length > 0 && + !long.TryParse(match.Groups["suffix"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out suffix)) + { + return false; + } + + precision = segments.Length; + version = new ComposerVersion(numbers[0], numbers[1], numbers[2], numbers[3], stability, suffix); + return true; + } + + private static bool TryUpperBound(ComposerVersion version, int index, out ComposerVersion bound) + { + long[] numbers = [version.Major, version.Minor, version.Patch, version.Revision]; + bound = default; + if (numbers[index] == long.MaxValue) + { + return false; + } + + numbers[index]++; + Array.Clear(numbers, index + 1, numbers.Length - index - 1); + bound = new ComposerVersion(numbers[0], numbers[1], numbers[2], numbers[3], 0, 0); + return true; + } + + private readonly record struct ComposerVersion(long Major, long Minor, long Patch, long Revision, int Stability, long Suffix) + { + internal ComposerVersion WithDevStability() => this with { Stability = 0, Suffix = 0 }; + + internal int CompareTo(ComposerVersion other) + { + var comparison = this.Major.CompareTo(other.Major); + comparison = comparison != 0 ? comparison : this.Minor.CompareTo(other.Minor); + comparison = comparison != 0 ? comparison : this.Patch.CompareTo(other.Patch); + comparison = comparison != 0 ? comparison : this.Revision.CompareTo(other.Revision); + comparison = comparison != 0 ? comparison : this.Stability.CompareTo(other.Stability); + return comparison != 0 ? comparison : this.Suffix.CompareTo(other.Suffix); + } + } + + private readonly record struct Interval(ComposerVersion? Lower, bool LowerInclusive, ComposerVersion? Upper, bool UpperInclusive) + { + internal bool IsNonempty => this.Lower is not { } lower || this.Upper is not { } upper || + lower.CompareTo(upper) < 0 || (lower == upper && this.LowerInclusive && this.UpperInclusive); + + internal Interval Intersect(Interval other) + { + var lower = this.Lower; + var lowerInclusive = this.LowerInclusive; + if (lower is null || (other.Lower is { } otherLower && otherLower.CompareTo(lower.Value) > 0)) + { + lower = other.Lower; + lowerInclusive = other.LowerInclusive; + } + else if (lower == other.Lower) + { + lowerInclusive &= other.LowerInclusive; + } + + var upper = this.Upper; + var upperInclusive = this.UpperInclusive; + if (upper is null || (other.Upper is { } otherUpper && otherUpper.CompareTo(upper.Value) < 0)) + { + upper = other.Upper; + upperInclusive = other.UpperInclusive; + } + else if (upper == other.Upper) + { + upperInclusive &= other.UpperInclusive; + } + + return new Interval(lower, lowerInclusive, upper, upperInclusive); + } + } + + private sealed class VersionSet + { + internal List Intervals { get; set; } = []; + + internal string? Branch { get; set; } + + internal HashSet ExcludedBranches { get; } = []; + + internal bool IsNonempty => this.Intervals.Count > 0 || (this.Branch is not null && !this.ExcludedBranches.Contains(this.Branch)); + + internal static VersionSet All() => new() { Intervals = [new Interval(default(ComposerVersion), true, null, false)], Branch = "*" }; + + internal static VersionSet Empty() => new(); + + internal static VersionSet Numeric(Interval interval) => new() { Intervals = interval.IsNonempty ? [interval] : [] }; + + internal VersionSet Intersect(VersionSet other) + { + var result = new VersionSet + { + Intervals = this.Intervals.SelectMany(left => other.Intervals.Select(left.Intersect)).Where(interval => interval.IsNonempty).ToList(), + Branch = this.Branch == "*" ? other.Branch : other.Branch == "*" || this.Branch == other.Branch ? this.Branch : null, + }; + result.ExcludedBranches.UnionWith(this.ExcludedBranches); + result.ExcludedBranches.UnionWith(other.ExcludedBranches); + return result; + } + } +} diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Commands/ScanSettings.cs b/src/Microsoft.ComponentDetection.Orchestrator/Commands/ScanSettings.cs index e209f7773..3f7a9d5e7 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Commands/ScanSettings.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Commands/ScanSettings.cs @@ -47,7 +47,7 @@ public class ScanSettings : BaseSettings [CommandOption("--DetectorCategories")] [Description( - "A comma separated list with the categories of components that are going to be scanned. The detectors that are going to run are the ones that belongs to the categories. The possible values are: Npm, NuGet, Maven, RubyGems, Cargo, Pip, GoMod, CocoaPods, Linux.")] + "A comma separated list with the categories of components that are going to be scanned. The detectors that are going to run are the ones that belongs to the categories. The possible values are: Npm, NuGet, Maven, RubyGems, Cargo, Pip, GoMod, CocoaPods, Linux, Composer.")] [TypeConverter(typeof(CommaDelimitedConverter))] public IEnumerable DetectorCategories { get; set; } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Configs/ComposerExperiment.cs b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Configs/ComposerExperiment.cs new file mode 100644 index 000000000..16779c298 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Configs/ComposerExperiment.cs @@ -0,0 +1,22 @@ +namespace Microsoft.ComponentDetection.Orchestrator.Experiments.Configs; + +using Microsoft.ComponentDetection.Contracts; +using Microsoft.ComponentDetection.Detectors.Composer; + +/// +/// Validates the against an empty baseline because there is no existing Composer detector. +/// +public class ComposerExperiment : IExperimentConfiguration +{ + /// + public string Name => "Composer"; + + /// + public bool IsInControlGroup(IComponentDetector componentDetector) => false; + + /// + public bool IsInExperimentGroup(IComponentDetector componentDetector) => componentDetector is ComposerComponentDetector; + + /// + public bool ShouldRecord(IComponentDetector componentDetector, int numComponents) => true; +} diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/ServiceCollectionExtensions.cs b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/ServiceCollectionExtensions.cs index 8f94838b1..707f04c55 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/ServiceCollectionExtensions.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/ServiceCollectionExtensions.cs @@ -4,6 +4,7 @@ namespace Microsoft.ComponentDetection.Orchestrator.Extensions; using Microsoft.ComponentDetection.Common.Telemetry; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Detectors.CocoaPods; +using Microsoft.ComponentDetection.Detectors.Composer; using Microsoft.ComponentDetection.Detectors.Conan; using Microsoft.ComponentDetection.Detectors.CondaLock; using Microsoft.ComponentDetection.Detectors.DockerCompose; @@ -71,6 +72,7 @@ public static IServiceCollection AddComponentDetection(this IServiceCollection s // Experiments services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -78,6 +80,9 @@ public static IServiceCollection AddComponentDetection(this IServiceCollection s // CocoaPods services.AddSingleton(); + // Composer + services.AddSingleton(); + // Conan services.AddSingleton(); diff --git a/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs index a689b27e7..d91330b2c 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs @@ -4,6 +4,7 @@ namespace Microsoft.ComponentDetection.Common.Tests; using System; using System.IO; using System.Text; +using System.Threading; using System.Threading.Tasks; using AwesomeAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -129,4 +130,84 @@ await action.Should() .ThrowAsync() .WithMessage("ExecuteCommandAsync was called with a working directory that could not be located: *"); } + + [TestMethod] + [OSCondition(OperatingSystems.Windows)] + public async Task ColdCommand_ProbesOnceAndReusesTheCachedCommandAsync() + { + var marker = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + try + { + var result = await this.commandLineService.ExecuteCommandAsync("cmd.exe", workingDirectory: null, cancellationToken: CancellationToken.None, parameters: ["/D", "/C", $"echo invocation>>\"{marker}\""]); + + result.ExitCode.Should().Be(0); + (await File.ReadAllLinesAsync(marker)).Should().Equal("invocation", "invocation"); + + result = await this.commandLineService.ExecuteCommandAsync("cmd.exe", workingDirectory: null, cancellationToken: CancellationToken.None, parameters: ["/D", "/C", $"echo invocation>>\"{marker}\""]); + + result.ExitCode.Should().Be(0); + (await File.ReadAllLinesAsync(marker)).Should().Equal("invocation", "invocation", "invocation"); + } + finally + { + File.Delete(marker); + } + } + + [TestMethod] + [OSCondition(OperatingSystems.Windows)] + public async Task CachedCommand_ReturnsNonzeroExitAsync() + { + (await this.commandLineService.CanCommandBeLocatedAsync("cmd.exe", default, "/C")).Should().BeTrue(); + var result = await this.commandLineService.ExecuteCommandAsync("cmd.exe", workingDirectory: null, cancellationToken: CancellationToken.None, parameters: ["/D", "/C", "exit 7"]); + + result.ExitCode.Should().Be(7); + } + + [TestMethod] + public async Task ExecuteCommand_PropagatesCancellationBeforeStartingAsync() + { + Func action = async () => await this.commandLineService.ExecuteCommandAsync("not-an-executable", workingDirectory: null, cancellationToken: new CancellationToken(true)); + + await action.Should().ThrowAsync(); + } + + [TestMethod] + public async Task AvailabilityProbe_PropagatesCancellationBeforeStartingAsync() + { + Func action = async () => await this.commandLineService.CanCommandBeLocatedAsync("not-an-executable", null, null, new CancellationToken(true)); + + await action.Should().ThrowAsync(); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + [OSCondition(OperatingSystems.Windows)] + public async Task ExecuteCommand_CancelsAvailabilityProbeAndCachedExecutionAsync(bool cached) + { + if (cached) + { + (await this.commandLineService.CanCommandBeLocatedAsync("cmd.exe", default, "/C")).Should().BeTrue(); + } + + using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(500)); + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + Func action = async () => await this.commandLineService.ExecuteCommandAsync("cmd.exe", workingDirectory: null, cancellationToken: cancellation.Token, parameters: ["/D", "/C", "ping -n 30 127.0.0.1 >nul"]); + + await action.Should().ThrowAsync(); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(5)); + } + + [TestMethod] + [OSCondition(OperatingSystems.Windows)] + public async Task AvailabilityProbe_CancelsARunningProcessAsync() + { + using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(500)); + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + Func action = async () => await this.commandLineService.CanCommandBeLocatedAsync("cmd.exe", null, null, cancellation.Token, "/D", "/C", "ping -n 30 127.0.0.1 >nul"); + + await action.Should().ThrowAsync(); + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(5)); + } } diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/ComposerComponentTests.cs b/test/Microsoft.ComponentDetection.Contracts.Tests/ComposerComponentTests.cs new file mode 100644 index 000000000..5be463e3b --- /dev/null +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/ComposerComponentTests.cs @@ -0,0 +1,167 @@ +#nullable disable +namespace Microsoft.ComponentDetection.Contracts.Tests; + +using System; +using System.Text.Json; +using AwesomeAssertions; +using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Newtonsoft.Json; + +[TestClass] +[TestCategory("Governance/All")] +[TestCategory("Governance/ComponentDetection")] +public class ComposerComponentTests +{ + [TestMethod] + public void ParameterlessConstructor_LeavesIdentityUninitialized() + { + var component = new ComposerComponent(); + + component.Name.Should().BeNull(); + component.Version.Should().BeNull(); + component.Type.Should().Be(ComponentType.Composer); + } + + [TestMethod] + [DataRow(" v1.2.3 ")] + [DataRow("V2.0.0")] + [DataRow(" dev-main ")] + [DataRow("1.x-dev")] + [DataRow("vnext")] + [DataRow("dev-main#abc123")] + [DataRow("v1.0.0-beta.1+build")] + public void Identity_PreservesRawFieldsAndBaseId(string version) + { + var component = new ComposerComponent(" Vendor/Package ", version); + + component.Name.Should().Be(" Vendor/Package "); + component.Version.Should().Be(version); + component.Id.Should().Be($" Vendor/Package {version} - Composer"); + component.BaseId.Should().Be(component.Id); + component.Type.Should().Be(ComponentType.Composer); + ((byte)component.Type).Should().Be(21); + } + + [TestMethod] + [DataRow(null, "1.0")] + [DataRow("vendor/package", null)] + public void Constructor_RejectsMissingInputs(string name, string version) + { + Action action = () => new ComposerComponent(name, version); + action.Should().Throw(); + } + + [TestMethod] + public void Constructor_DoesNotEnforceManifestNameGrammar() + { + var component = new ComposerComponent("Vendor--Name/Package", "1.0"); + + component.Name.Should().Be("Vendor--Name/Package"); + component.Id.Should().Be("Vendor--Name/Package 1.0 - Composer"); + component.PackageUrl.ToString().Should().Be("pkg:composer/vendor--name/package@1.0"); + } + + [TestMethod] + [DataRow("vendor/package--name", "vendor/package--name")] + [DataRow("Vendor/Package--Name", "vendor/package--name")] + [DataRow("vendor-name/package-name", "vendor-name/package-name")] + [DataRow("vendor.name_with-hyphen/package.test_other--name12", "vendor.name_with-hyphen/package.test_other--name12")] + [DataRow("0/1", "0/1")] + public void Name_IsPreservedInComponentAndBaseId(string name, string expected) + { + var component = new ComposerComponent(name, "v1.2.3"); + + component.Name.Should().Be(name); + component.Version.Should().Be("v1.2.3"); + component.Id.Should().Be($"{name} v1.2.3 - Composer"); + component.PackageUrl.ToString().Should().Be($"pkg:composer/{expected}@v1.2.3"); + } + + [TestMethod] + public void DifferentRawIdentities_AreNotNormalizedToTheSameBaseId() + { + var original = new ComposerComponent("Vendor/Package", "v1.2.3"); + var different = new ComposerComponent("vendor/package", "1.2.3"); + + original.BaseId.Should().Be("Vendor/Package v1.2.3 - Composer"); + different.BaseId.Should().Be("vendor/package 1.2.3 - Composer"); + original.Id.Should().NotBe(different.Id); + original.PackageUrl.Version.Should().Be("v1.2.3"); + different.PackageUrl.Version.Should().Be("1.2.3"); + } + + [TestMethod] + public void PackageUrl_UsesVendorNamespaceAndPackageName() + { + var component = new ComposerComponent("Monolog/Monolog", "v3.9.0"); + component.PackageUrl.Type.Should().Be("composer"); + component.PackageUrl.Namespace.Should().Be("monolog"); + component.PackageUrl.Name.Should().Be("monolog"); + component.PackageUrl.Version.Should().Be("v3.9.0"); + component.PackageUrl.ToString().Should().Be("pkg:composer/monolog/monolog@v3.9.0"); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void PolymorphicJson_RoundTripsIdentityAndMetadata(bool newtonsoft) + { + TypedComponent component = new ComposerComponent("Vendor/Package", "v1.2.3") + { + Licenses = ["MIT"], + }; + var json = newtonsoft ? JsonConvert.SerializeObject(component) : System.Text.Json.JsonSerializer.Serialize(component); + var restored = newtonsoft ? JsonConvert.DeserializeObject(json) : System.Text.Json.JsonSerializer.Deserialize(json); + + restored.Should().BeOfType().Which.Should().BeEquivalentTo(component); + using var document = JsonDocument.Parse(json); + document.RootElement.GetProperty("type").GetString().Should().Be("Composer"); + document.RootElement.GetProperty("name").GetString().Should().Be("Vendor/Package"); + document.RootElement.GetProperty("version").GetString().Should().Be("v1.2.3"); + document.RootElement.GetProperty("id").GetString().Should().Be("Vendor/Package v1.2.3 - Composer"); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void ScanTransport_UsesFlatDiscriminatedComponent(bool newtonsoft) + { + var scanned = new ScannedComponent + { + DetectorId = "Composer", + Component = new ComposerComponent("vendor/package", "dev-main"), + IsDevelopmentDependency = true, + }; + var json = newtonsoft ? JsonConvert.SerializeObject(scanned) : System.Text.Json.JsonSerializer.Serialize(scanned); + var restored = newtonsoft ? JsonConvert.DeserializeObject(json) : System.Text.Json.JsonSerializer.Deserialize(json); + + restored.Component.Should().BeOfType(); + restored.IsDevelopmentDependency.Should().BeTrue(); + using var document = JsonDocument.Parse(json); + var payload = document.RootElement.GetProperty("component"); + payload.GetProperty("type").GetString().Should().Be("Composer"); + payload.GetProperty("name").GetString().Should().Be("vendor/package"); + payload.TryGetProperty("composer", out _).Should().BeFalse(); + var packageUrl = payload.GetProperty("packageUrl"); + packageUrl.GetProperty("Type").GetString().Should().Be("composer"); + packageUrl.GetProperty("Namespace").GetString().Should().Be("vendor"); + packageUrl.GetProperty("Name").GetString().Should().Be("package"); + } + + [TestMethod] + public void IdentityProperties_CanBeInitializedForDeserialization() + { + var component = new ComposerComponent + { + Name = "vendor/package", + Version = "v1.2.3", + }; + + component.Name.Should().Be("vendor/package"); + component.Version.Should().Be("v1.2.3"); + component.Id.Should().Be("vendor/package v1.2.3 - Composer"); + component.PackageUrl.ToString().Should().Be("pkg:composer/vendor/package@v1.2.3"); + } +} diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/Microsoft.ComponentDetection.Contracts.Tests.csproj b/test/Microsoft.ComponentDetection.Contracts.Tests/Microsoft.ComponentDetection.Contracts.Tests.csproj index 680fd7d91..492d92b2b 100644 --- a/test/Microsoft.ComponentDetection.Contracts.Tests/Microsoft.ComponentDetection.Contracts.Tests.csproj +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/Microsoft.ComponentDetection.Contracts.Tests.csproj @@ -6,6 +6,7 @@ + diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/PhpSdkComponentTests.cs b/test/Microsoft.ComponentDetection.Contracts.Tests/PhpSdkComponentTests.cs new file mode 100644 index 000000000..3264d5261 --- /dev/null +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/PhpSdkComponentTests.cs @@ -0,0 +1,100 @@ +#nullable disable +namespace Microsoft.ComponentDetection.Contracts.Tests; + +using System; +using System.Text.Json; +using AwesomeAssertions; +using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Newtonsoft.Json; + +[TestClass] +[TestCategory("Governance/All")] +[TestCategory("Governance/ComponentDetection")] +public class PhpSdkComponentTests +{ + [TestMethod] + public void ParameterlessConstructor_LeavesIdentityUninitialized() + { + var component = new PhpSdkComponent(); + + component.Name.Should().BeNull(); + component.Version.Should().BeNull(); + component.Type.Should().Be(ComponentType.PhpSdk); + } + + [TestMethod] + public void IdentityProperties_CanBeInitializedForDeserialization() + { + var component = new PhpSdkComponent + { + Name = "php", + Version = "8.4.27", + }; + + component.Name.Should().Be("php"); + component.Version.Should().Be("8.4.27"); + component.Id.Should().Be("php 8.4.27 - PhpSdk"); + component.PackageUrl.ToString().Should().Be("pkg:generic/php@8.4.27?type=phpsdk"); + } + + [TestMethod] + [DataRow("php", "8.4.27")] + [DataRow("ext-openssl", "8.4.27")] + [DataRow("lib-openssl", "3.5.0")] + [DataRow("composer", "2.11.1")] + public void IdentityAndPackageUrl_DescribeTheObservedEnvironment(string name, string version) + { + var component = new PhpSdkComponent(name, version); + + component.Name.Should().Be(name); + component.Version.Should().Be(version); + component.Type.Should().Be(ComponentType.PhpSdk); + ((byte)component.Type).Should().Be(22); + component.Id.Should().Be($"{name} {version} - PhpSdk"); + component.PackageUrl.ToString().Should().Be($"pkg:generic/{name}@{version}?type=phpsdk"); + } + + [TestMethod] + [DataRow(null, "1.0")] + [DataRow("", "1.0")] + [DataRow("php", null)] + [DataRow("php", " ")] + public void Constructor_RejectsMissingIdentity(string name, string version) + { + Action action = () => new PhpSdkComponent(name, version); + action.Should().Throw(); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void PolymorphicJson_RoundTripsIdentityAndMetadata(bool newtonsoft) + { + TypedComponent component = new PhpSdkComponent("lib-curl", "8.12.1") { Licenses = ["MIT"] }; + var json = newtonsoft ? JsonConvert.SerializeObject(component) : System.Text.Json.JsonSerializer.Serialize(component); + var restored = newtonsoft ? JsonConvert.DeserializeObject(json) : System.Text.Json.JsonSerializer.Deserialize(json); + + restored.Should().BeOfType().Which.Should().BeEquivalentTo(component); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void ScanTransport_UsesThePhpSdkDiscriminator(bool newtonsoft) + { + var scanned = new ScannedComponent { DetectorId = "Composer", Component = new PhpSdkComponent("php", "8.4.27"), IsDevelopmentDependency = false }; + var json = newtonsoft ? JsonConvert.SerializeObject(scanned) : System.Text.Json.JsonSerializer.Serialize(scanned); + var restored = newtonsoft ? JsonConvert.DeserializeObject(json) : System.Text.Json.JsonSerializer.Deserialize(json); + + restored.Component.Should().BeOfType().Which.Version.Should().Be("8.4.27"); + restored.IsDevelopmentDependency.Should().BeFalse(); + using var document = JsonDocument.Parse(json); + var payload = document.RootElement.GetProperty("component"); + payload.GetProperty("type").GetString().Should().Be("PhpSdk"); + payload.GetProperty("name").GetString().Should().Be("php"); + payload.GetProperty("version").GetString().Should().Be("8.4.27"); + payload.GetProperty("packageUrl").GetProperty("Type").GetString().Should().Be("generic"); + } +} diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ComponentDetectorTests.cs index 6d2851210..a2ff3efc5 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/ComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ComponentDetectorTests.cs @@ -5,6 +5,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Linq; using AwesomeAssertions; using Microsoft.ComponentDetection.Contracts; +using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.ComponentDetection.Orchestrator.Extensions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -37,6 +38,17 @@ public void AllDetectorsHaveUniqueIds() ids.Should().OnlyHaveUniqueItems(); } + [TestMethod] + public void ComposerComponentDetector_IsDiscoverableAndExperimental() + { + var detector = this.detectors.Single(d => d.Id == "Composer"); + detector.Should().BeAssignableTo(); + detector.Should().NotBeAssignableTo(); + detector.Categories.Should().Equal(nameof(DetectorClass.Composer)); + detector.SupportedComponentTypes.Should().Equal(ComponentType.Composer, ComponentType.PhpSdk); + ((FileComponentDetector)detector).SearchPatterns.Should().Equal("composer.lock", "composer.json"); + } + [TestMethod] public void AllDetectorsHavePositiveVersion() { diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs new file mode 100644 index 000000000..d79840d93 --- /dev/null +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs @@ -0,0 +1,1253 @@ +#nullable disable +namespace Microsoft.ComponentDetection.Detectors.Tests; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using AwesomeAssertions; +using Microsoft.ComponentDetection.Contracts; +using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.ComponentDetection.Detectors.Composer; +using Microsoft.ComponentDetection.TestsUtilities; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +[TestClass] +[TestCategory("Governance/All")] +[TestCategory("Governance/ComponentDetection")] +public class ComposerDetectorTests : BaseDetectorTest +{ + [TestInitialize] + public void Initialize() + { + this.DetectorTestUtility.AddServiceMock(new Mock()); + this.DetectorTestUtility.AddServiceMock(new Mock()); + } + + [TestMethod] + [DataRow("{\n// A manifest comment\n\"require\":{\"vendor/package\":\"v1.2.3\"}}")] + [DataRow("{\"require\":{\"vendor/package\":\"v1.2.3\",},}")] + [DataRow("{/* A manifest comment */\"require\":{\"vendor/package\":\"v1.2.3\",},}")] + public async Task ManifestOnly_AllowsCommentsAndTrailingCommasAsync(string content) + { + var (result, recorder) = await this.DetectorTestUtility.WithFile("composer.json", content).ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/package", "v1.2.3")); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + public async Task Lockfile_AllowsCommentsAndTrailingCommasAsync() + { + const string content = """ + { + // Resolved packages + "packages":[ + {"name":"vendor/app","version":"v1.2.3","require":{"vendor/child":"^2",},}, + {"name":"vendor/child","version":"2.1.0",}, + ], + } + """; + var (result, recorder) = await this.DetectAsync(content); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo([Id("vendor/app", "v1.2.3"), Id("vendor/child", "2.1.0")]); + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "v1.2.3")).Should().Equal(Id("vendor/child", "2.1.0")); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + public async Task Lockfile_ReadsSiblingManifestForDirectRootsWithoutAdditionalLocationsOrInstalledLookupAsync() + { + var factory = this.WithManifest("""{/* Both packages are direct */"require":{"vendor/app":"^1","vendor/child":"^2",},}"""); + var files = new Mock(MockBehavior.Strict); + var (_, recorder) = await this.DetectorTestUtility.AddServiceMock(files) + .WithFile("composer.lock", """{"packages":[{"name":"vendor/app","version":"1.2.3","require":{"vendor/child":"^2"}},{"name":"vendor/child","version":"2.1.0"}]}""") + .ExecuteDetectorAsync(); + + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo([Id("vendor/app", "1.2.3"), Id("vendor/child", "2.1.0")]); + graph.GetDependenciesForComponent(Id("vendor/app", "1.2.3")).Should().Equal(Id("vendor/child", "2.1.0")); + graph.GetAdditionalRelatedFiles().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().BeEmpty(); + factory.Verify(value => value.GetComponentStreams(It.IsAny(), It.Is>(patterns => patterns.SequenceEqual(new[] { "composer.json" })), It.IsAny(), false), Times.Once); + files.VerifyNoOtherCalls(); + } + + [TestMethod] + [DataRow("{/* Installed inventory */\"packages\":[{\"name\":\"vendor/package\",\"version\":\"v1.2.3\",},],}")] + [DataRow("[/* Legacy installed inventory */{\"name\":\"vendor/package\",\"version\":\"v1.2.3\",},]")] + public async Task InstalledInventory_AllowsCommentsAndTrailingCommasAsync(string content) + { + this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), content); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/package":"^1"}}""").ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/package", "v1.2.3")); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow(259)] + [DataRow(260)] + [DataRow(261)] + [DataRow(4095)] + [DataRow(4096)] + [DataRow(4097)] + [DataRow(32766)] + [DataRow(32767)] + [DataRow(32768)] + [DataRow(65536)] + [DataRow(1000000)] + public void DirectoryNameExtraction_DoesNotApplyFilesystemLengthLimits(int pathLength) + { + const string fileName = "composer.json"; + var location = CreateLongFileLocation(pathLength, fileName); + var expectedDirectory = location[..^(fileName.Length + 1)]; + + location.Length.Should().Be(pathLength); + Path.GetDirectoryName(location).Should().Be(expectedDirectory); + } + + [TestMethod] + [DataRow(261, false)] + [DataRow(261, true)] + [DataRow(4097, false)] + [DataRow(4097, true)] + [DataRow(32000, false)] + [DataRow(32000, true)] + public async Task LongCheckoutPaths_PreserveLocationsAndPreferSiblingLockfilesAsync(int pathLength, bool hasLockfile) + { + var fileName = hasLockfile ? "composer.lock" : "composer.json"; + var location = CreateLongFileLocation(pathLength, fileName); + var directory = location[..^(fileName.Length + 1)]; + this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/package":"v9.0.0"}}""", fileLocation: Path.Combine(directory, "composer.json")); + if (hasLockfile) + { + this.DetectorTestUtility.WithFile("composer.lock", """{"packages":[{"name":"vendor/package","version":"v1.2.3"}]}""", fileLocation: location); + } + + var (result, recorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); + + location.Length.Should().Be(pathLength); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/package", hasLockfile ? "v1.2.3" : "v9.0.0")); + recorder.GetDependencyGraphsByLocation().Keys.Should().Equal(location); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow(null, null, "vendor")] + [DataRow(null, "dependencies", "dependencies")] + [DataRow("", "dependencies", "dependencies")] + [DataRow("env-vendor", "dependencies", "env-vendor")] + [DataRow("env-vendor", null, "env-vendor")] + [DataRow("absolute", "dependencies", "absolute")] + [DataRow(null, "absolute", "absolute")] + public async Task InstalledInventory_UsesEnvironmentThenManifestThenDefaultVendorDirectoryAsync(string environmentDirectory, string configuredDirectory, string expectedDirectory) + { + var absoluteDirectory = Path.Combine(Path.GetTempPath(), "composer-artifacts"); + environmentDirectory = environmentDirectory == "absolute" ? absoluteDirectory : environmentDirectory; + configuredDirectory = configuredDirectory == "absolute" ? absoluteDirectory : configuredDirectory; + var vendorDirectory = expectedDirectory == "absolute" ? absoluteDirectory : Path.Combine(Path.GetTempPath(), expectedDirectory); + var environment = new Mock(); + environment.Setup(value => value.GetEnvironmentVariable("COMPOSER_VENDOR_DIR")).Returns(environmentDirectory); + var config = System.Text.Json.JsonSerializer.Serialize(new { config = new Dictionary { ["vendor-dir"] = configuredDirectory } }); + var manifest = configuredDirectory is null + ? """{"require":{"vendor/app":"^1"},"require-dev":{"vendor/tests":"^2"}}""" + : config[..^1] + ""","require":{"vendor/app":"^1"},"require-dev":{"vendor/tests":"^2"}}"""; + const string installed = """ + {"packages":[ + {"name":"vendor/app","version":"v1.4.0","version_normalized":"1.4.0.0","require":{"vendor/child":"^3"}}, + {"name":"vendor/child","version":"3.1.0"}, + {"name":"vendor/tests","version":"2.2.0","require":{"vendor/child":"^3"}} + ],"dev":true,"dev-package-names":["vendor/tests"]} + """; + var files = this.WithInstalledFile(vendorDirectory, installed); + var logger = new Mock>(); + var (result, recorder) = await this.DetectorTestUtility.AddServiceMock(environment).AddServiceMock(logger) + .WithFile("composer.json", manifest).ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo( + [Id("vendor/app", "v1.4.0"), Id("vendor/child", "3.1.0"), Id("vendor/tests", "2.2.0")]); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo([Id("vendor/app", "v1.4.0"), Id("vendor/tests", "2.2.0")]); + graph.GetDependenciesForComponent(Id("vendor/app", "v1.4.0")).Should().Equal(Id("vendor/child", "3.1.0")); + graph.GetDependenciesForComponent(Id("vendor/tests", "2.2.0")).Should().Equal(Id("vendor/child", "3.1.0")); + graph.IsDevelopmentDependency(Id("vendor/app", "v1.4.0")).Should().BeFalse(); + graph.IsDevelopmentDependency(Id("vendor/child", "3.1.0")).Should().BeFalse(); + graph.IsDevelopmentDependency(Id("vendor/tests", "2.2.0")).Should().BeTrue(); + graph.GetAdditionalRelatedFiles().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().BeEmpty(); + files.Verify(value => value.MakeFileStream(Path.Combine(vendorDirectory, "composer", "installed.json")), Times.Once); + logger.Verify(value => value.Log(LogLevel.Warning, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>()), Times.Never); + } + + [TestMethod] + public async Task InstalledInventory_LegacyArrayPreservesRawIdentitiesAndResolvesVirtualDependenciesAsync() + { + const string installed = """ + [{"name":" Vendor/App ","version":"dev-main","require":{"virtual/api":"^3"}}, + {"name":"vendor/provider","version":"v3.2.0","provide":{"virtual/api":"self.version"}}] + """; + this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), installed); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/app":"dev-main"}}""").ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo([Id(" Vendor/App ", "dev-main"), Id("vendor/provider", "v3.2.0")]); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetAllExplicitlyReferencedComponents().Should().Equal(Id(" Vendor/App ", "dev-main")); + graph.GetDependenciesForComponent(Id(" Vendor/App ", "dev-main")).Should().Equal(Id("vendor/provider", "v3.2.0")); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + public async Task InstalledInventory_IsNotDiscoveredWithoutAComposerFileAsync() + { + var files = this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), """{"packages":[{"name":"vendor/no-project","version":"1"}]}"""); + var (_, recorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Should().BeEmpty(); + files.VerifyNoOtherCalls(); + } + + [TestMethod] + [DataRow("[]")] + [DataRow("{\"packages\":[]}")] + public async Task EmptyInstalledInventory_DoesNotInventDeclaredPackagesAsync(string content) + { + this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), content); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/not-installed":"1.0.0"}}""").ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow("{")] + [DataRow("null")] + [DataRow("{}")] + [DataRow("{\"packages\":false}")] + public async Task MalformedInstalledInventory_ReportsFailureAndFallsBackToExactDeclarationsAsync(string content) + { + this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), content); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/pinned":"1.2.3","vendor/ranged":"^2"}}""").ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/pinned", "1.2.3")); + recorder.GetSkippedComponents().Should().ContainSingle(); + } + + [TestMethod] + [DataRow("{\"config\":false}")] + [DataRow("{\"config\":null}")] + [DataRow("{\"config\":[]}")] + [DataRow("{\"config\":{\"vendor-dir\":42}}")] + [DataRow("{\"config\":{\"vendor-dir\":null}}")] + [DataRow("{\"config\":{\"vendor-dir\":\"\"}}")] + [DataRow("{\"config\":{\"vendor-dir\":\" \"}}")] + [DataRow("{\"config\":{\"vendor-dir\":\"\\u0000\"}}")] + public async Task InvalidVendorConfiguration_WarnsAndReadsDefaultVendorInventoryAsync(string content) + { + var location = Path.Combine(Path.GetTempPath(), "vendor", "composer", "installed.json"); + var files = this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), """{"packages":[{"name":"vendor/installed","version":"1.2.3"}]}"""); + var logger = new Mock>(); + var (_, recorder) = await this.DetectorTestUtility.AddServiceMock(logger).WithFile("composer.json", content).ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/installed", "1.2.3")); + recorder.GetSkippedComponents().Should().BeEmpty(); + files.Verify(value => value.MakeFileStream(location), Times.Once); + logger.Verify( + value => value.Log( + LogLevel.Warning, + It.IsAny(), + It.Is((state, _) => state.ToString().Contains("using the default vendor directory")), + It.IsAny(), + It.IsAny>()), + Times.Once); + } + + [TestMethod] + public async Task InvalidVendorEnvironmentPath_WarnsAndUsesDefaultRatherThanConfiguredDirectoryAsync() + { + var environment = new Mock(); + environment.Setup(value => value.GetEnvironmentVariable("COMPOSER_VENDOR_DIR")).Returns("invalid\0path"); + this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), """{"packages":[{"name":"vendor/installed","version":"1.2.3"}]}"""); + var logger = new Mock>(); + var (_, recorder) = await this.DetectorTestUtility.AddServiceMock(environment).AddServiceMock(logger) + .WithFile("composer.json", """{"config":{"vendor-dir":"dependencies"}}""").ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/installed", "1.2.3")); + recorder.GetSkippedComponents().Should().BeEmpty(); + logger.Verify( + value => value.Log( + LogLevel.Warning, + It.IsAny(), + It.Is((state, _) => state.ToString().Contains("using the default vendor directory")), + It.IsAny(), + It.IsAny>()), + Times.Once); + } + + [TestMethod] + [DataRow(false, "vendor")] + [DataRow(true, "vendor")] + [DataRow(false, "dependencies")] + [DataRow(true, "dependencies")] + public async Task Lockfile_SkipsVendorInputsAndNeverOpensInstalledMetadataAsync(bool lockFirst, string vendorDirectory) + { + this.WithManifest($$$"""{"config":{"vendor-dir":"{{{vendorDirectory}}}"}}"""); + var files = this.WithInstalledFile(Path.Combine(Path.GetTempPath(), vendorDirectory), "{"); + var nestedLocation = Path.Combine(Path.GetTempPath(), vendorDirectory, "vendor", "package", "composer.json"); + if (lockFirst) + { + this.DetectorTestUtility.WithFile("composer.lock", """{"packages":[{"name":"vendor/locked","version":"1.4.0"}]}"""); + } + + this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/not-installed":"9.0.0"}}""", fileLocation: nestedLocation); + if (!lockFirst) + { + this.DetectorTestUtility.WithFile("composer.lock", """{"packages":[{"name":"vendor/locked","version":"1.4.0"}]}"""); + } + + var (_, recorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/locked", "1.4.0")); + recorder.GetSkippedComponents().Should().BeEmpty(); + files.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task ParentLock_DoesNotSuppressAnIndependentNestedProjectAsync() + { + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"vendor/nested":"2.0.0"}}""", fileLocation: Path.Combine(Path.GetTempPath(), "nested-project", "composer.json")) + .WithFile("composer.lock", """{"packages":[{"name":"vendor/parent","version":"1.0.0"}]}""") + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo([Id("vendor/parent", "1.0.0"), Id("vendor/nested", "2.0.0")]); + } + + [TestMethod] + public async Task InstalledInventory_SkipsNestedPackageManifestsAsync() + { + this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), """{"packages":[{"name":"vendor/app","version":"1.4.0"}]}"""); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"vendor/not-installed":"9.0.0"}}""", fileLocation: Path.Combine(Path.GetTempPath(), "vendor", "vendor", "app", "composer.json")) + .WithFile("composer.json", """{"require":{"vendor/app":"^1"}}""") + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/app", "1.4.0")); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + public async Task MissingInstalledInventory_DoesNotSuppressNestedManifestFallbackAsync() + { + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"vendor/nested":"2.0.0"}}""", fileLocation: Path.Combine(Path.GetTempPath(), "vendor", "vendor", "app", "composer.json")) + .WithFile("composer.json", """{"require":{"vendor/app":"^1"}}""") + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/nested", "2.0.0")); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + public async Task ManifestOnly_RegistersExactDirectRequirementsWithProductionPrecedenceAsync() + { + const string manifest = """ + {"name":"vendor/project","version":"9.0.0", + "require":{"php":"^8","vendor/runtime":"v1.2.3","vendor/shared":"2.0.0"}, + "require-dev":{"vendor/tests":"== 3.0.0-beta2","vendor/shared":"2.0.0"}} + """; + var logger = new Mock>(); + var (result, recorder) = await this.DetectorTestUtility + .AddServiceMock(logger) + .WithFile("composer.json", manifest) + .ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo( + [Id("vendor/runtime", "v1.2.3"), Id("vendor/shared", "2.0.0"), Id("vendor/tests", "3.0.0-beta2")]); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetAllExplicitlyReferencedComponents().Should().HaveCount(3); + graph.IsDevelopmentDependency(Id("vendor/runtime", "v1.2.3")).Should().BeFalse(); + graph.IsDevelopmentDependency(Id("vendor/shared", "2.0.0")).Should().BeFalse(); + graph.IsDevelopmentDependency(Id("vendor/tests", "3.0.0-beta2")).Should().BeTrue(); + graph.GetDependenciesForComponent(Id("vendor/runtime", "v1.2.3")).Should().BeEmpty(); + recorder.GetSkippedComponents().Should().BeEmpty(); + logger.Verify( + value => value.Log( + LogLevel.Warning, + It.IsAny(), + It.Is((state, _) => state.ToString().Contains("without a sibling composer.lock") && state.ToString().Contains("improve accuracy")), + It.IsAny(), + It.IsAny>()), + Times.Once); + } + + [TestMethod] + public async Task ManifestOnly_PreservesSourceNameAndVersionPrefixAsync() + { + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{" Vendor/Package ":"v1.2.3"}}""") + .ExecuteDetectorAsync(); + + var component = recorder.GetDetectedComponents().Should().ContainSingle().Which.Component.Should().BeOfType().Which; + component.Name.Should().Be(" Vendor/Package "); + component.Version.Should().Be("v1.2.3"); + component.BaseId.Should().Be(" Vendor/Package v1.2.3 - Composer"); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + public async Task Lockfile_PreservesSourceFieldsWhileResolvingNormalizedNamesAndAliasesAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":" Vendor/Root ","version":" v1.2.3 ","require":{"VENDOR/CHILD":"*","virtual/api":"^3"}}, + {"name":" Vendor/Child ","version":" dev-main ","provide":{"virtual/api":"self.version"}, + "extra":{"branch-alias":{"dev-main":"3.x-dev"}}} + ]} + """); + + var components = recorder.GetDetectedComponents().Select(component => component.Component).OfType().ToDictionary(component => component.Id); + components.Should().HaveCount(2); + components[Id(" Vendor/Root ", " v1.2.3 ")].Name.Should().Be(" Vendor/Root "); + components[Id(" Vendor/Root ", " v1.2.3 ")].Version.Should().Be(" v1.2.3 "); + components[Id(" Vendor/Child ", " dev-main ")].Name.Should().Be(" Vendor/Child "); + components[Id(" Vendor/Child ", " dev-main ")].Version.Should().Be(" dev-main "); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetDependenciesForComponent(Id(" Vendor/Root ", " v1.2.3 ")).Should().Equal(Id(" Vendor/Child ", " dev-main ")); + graph.GetAllExplicitlyReferencedComponents().Should().Equal(Id(" Vendor/Root ", " v1.2.3 ")); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow("^1.0", false)] + [DataRow("^1.2.3", false)] + [DataRow("^v1.2.3", false)] + [DataRow("^ 1.2.3", false)] + [DataRow("^1.2.3", true)] + [DataRow("~1.2", false)] + [DataRow("~1.2.3", false)] + [DataRow("~v1.2.3", false)] + [DataRow("~ 1.2.3", false)] + [DataRow("~1.2.3", true)] + [DataRow("^1.2.3-beta2", false)] + [DataRow("~1.2.3-beta2", true)] + [DataRow("^", false)] + [DataRow("~", false)] + [DataRow("^1 || ^2", false)] + [DataRow("~1 >=1.2", false)] + [DataRow("*", false)] + [DataRow("*", true)] + [DataRow("1.2.*", false)] + [DataRow("^1.2.*", false)] + [DataRow("~1.2.*", false)] + [DataRow(">=1 <2", false)] + [DataRow(">1", false)] + [DataRow("<2", false)] + [DataRow("<=2", false)] + [DataRow("!=1.5", false)] + [DataRow("1.0 || 2.0", false)] + [DataRow("1.0 - 2.0", false)] + [DataRow("dev-main", false)] + [DataRow("1.x-dev", false)] + [DataRow("dev-main as 1.0.0", false)] + public async Task ManifestOnly_UnresolvedConstraintsAreOmittedWithWarningsAsync(string constraint, bool isDevelopment) + { + var logger = new Mock>(); + var section = isDevelopment ? "require-dev" : "require"; + var content = $$$"""{"{{{section}}}":{"vendor/unresolved":"{{{constraint}}}","vendor/pinned":"1.2.3"}}"""; + var (_, recorder) = await this.DetectorTestUtility.AddServiceMock(logger).WithFile("composer.json", content).ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/pinned", "1.2.3")); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetAllExplicitlyReferencedComponents().Should().Equal(Id("vendor/pinned", "1.2.3")); + graph.IsDevelopmentDependency(Id("vendor/pinned", "1.2.3")).Should().Be(isDevelopment); + recorder.GetSkippedComponents().Should().BeEmpty(); + logger.Verify( + value => value.Log( + LogLevel.Warning, + It.IsAny(), + It.Is((state, _) => state.ToString().Contains("vendor/unresolved") && state.ToString().Contains(constraint) && state.ToString().Contains("this declaration is omitted")), + It.IsAny(), + It.IsAny>()), + Times.Once); + } + + [TestMethod] + [DataRow("composer.json")] + [DataRow("COMPOSER.JSON")] + [DataRow("Composer.Json")] + public async Task ManifestFilenameMatching_IsCaseInsensitiveAsync(string fileName) + { + var (result, recorder) = await this.DetectorTestUtility + .WithFile(fileName, """{"require":{"vendor/pinned":"1.2.3"}}""") + .ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/pinned", "1.2.3")); + recorder.GetDependencyGraphsByLocation().Keys.Should().Equal(Path.Combine(Path.GetTempPath(), fileName)); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow(false, "composer.lock", "composer.json")] + [DataRow(true, "composer.lock", "composer.json")] + [DataRow(false, "COMPOSER.LOCK", "COMPOSER.JSON")] + [DataRow(true, "COMPOSER.LOCK", "COMPOSER.JSON")] + [DataRow(false, "Composer.Lock", "Composer.Json")] + [DataRow(true, "Composer.Lock", "Composer.Json")] + public async Task ManifestAndLock_AlwaysUseLockedVersionsRegardlessOfDiscoveryOrderAsync(bool lockFirst, string lockName, string manifestName) + { + const string manifest = """{"require":{"vendor/app":"^1.0","vendor/child":"^2.0","vendor/not-installed":"2.0.0"}}"""; + const string locked = """{"packages":[{"name":"vendor/app","version":"1.4.0","require":{"vendor/child":"^2.0"}},{"name":"vendor/child","version":"2.1.0"}]}"""; + this.WithManifest(manifest, manifestName); + var logger = new Mock>(); + this.DetectorTestUtility.AddServiceMock(logger); + if (lockFirst) + { + this.DetectorTestUtility.WithFile(lockName, locked).WithFile(manifestName, manifest); + } + else + { + this.DetectorTestUtility.WithFile(manifestName, manifest).WithFile(lockName, locked); + } + + var (_, recorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo([Id("vendor/app", "1.4.0"), Id("vendor/child", "2.1.0")]); + var graphs = recorder.GetDependencyGraphsByLocation(); + graphs.Keys.Should().Equal(Path.Combine(Path.GetTempPath(), lockName)); + graphs.Values.Single().GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo([Id("vendor/app", "1.4.0"), Id("vendor/child", "2.1.0")]); + graphs.Values.Single().GetAdditionalRelatedFiles().Should().BeEmpty(); + logger.Verify( + value => value.Log( + LogLevel.Warning, + It.IsAny(), + It.Is((state, _) => state.ToString().Contains("without a sibling composer.lock")), + It.IsAny(), + It.IsAny>()), + Times.Never); + } + + [TestMethod] + public async Task DirectoryGrouping_DistinguishesPathsByCaseAsync() + { + var manifestLocation = Path.Combine(Path.GetTempPath(), "ComposerProject", "composer.json"); + var lockLocation = Path.Combine(Path.GetTempPath(), "composerproject", "composer.lock"); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"vendor/not-locked":"1.2.3"}}""", fileLocation: manifestLocation) + .WithFile("composer.lock", """{"packages":[{"name":"vendor/locked","version":"2.0.0"}]}""", fileLocation: lockLocation) + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo([Id("vendor/not-locked", "1.2.3"), Id("vendor/locked", "2.0.0")]); + recorder.GetDependencyGraphsByLocation().Keys.Should().BeEquivalentTo([manifestLocation, lockLocation]); + } + + [TestMethod] + public async Task LockInOtherDirectory_DoesNotSuppressManifestFallbackAsync() + { + var manifestLocation = Path.Combine(Path.GetTempPath(), "manifest-only", "composer.json"); + var lockLocation = Path.Combine(Path.GetTempPath(), "locked", "composer.lock"); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"vendor/direct":"1.2.3"}}""", fileLocation: manifestLocation) + .WithFile("composer.lock", """{"packages":[{"name":"vendor/locked","version":"2.0.0"}]}""", fileLocation: lockLocation) + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo([Id("vendor/direct", "1.2.3"), Id("vendor/locked", "2.0.0")]); + recorder.GetDependencyGraphsByLocation().Keys.Should().BeEquivalentTo([manifestLocation, lockLocation]); + } + + [TestMethod] + public async Task MalformedLock_DoesNotFallBackToManifestDeclarationsAsync() + { + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"vendor/not-locked":"1.2.3"}}""") + .WithFile("composer.lock", "{") + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().ContainSingle(); + } + + [TestMethod] + [DataRow("{")] + [DataRow("null")] + [DataRow("[]")] + [DataRow("""{"require":[]}""")] + [DataRow("""{"require":{"vendor/invalid":42}}""")] + [DataRow("""{"require":{"php-future-capability":42}}""")] + public async Task ManifestOnly_MalformedDataReportsParseFailureAsync(string content) + { + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", content).ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().ContainSingle(); + } + + [TestMethod] + [DataRow("package")] + [DataRow("vendor/")] + [DataRow("/package")] + [DataRow(" ")] + public async Task MissingPackageIdentity_ReportsParseFailureAsync(string name) + { + var content = $$$"""{"packages":[{"name":"{{{name}}}","version":"1.0"}]}"""; + var (_, recorder) = await this.DetectAsync(content); + + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().ContainSingle(); + } + + [TestMethod] + [DataRow("vendor--name/package---name", "release-next")] + [DataRow("vendor./package__name", "custom-version#revision")] + [DataRow("vendor_/package.-name", "2026.11.06-preview+vendor-build")] + [DataRow("vendor/pack age", "vnext")] + public async Task LockedIdentities_AreNotRestrictedToNameOrVersionGrammarAsync(string name, string version) + { + var content = $$$"""{"packages":[{"name":"{{{name}}}","version":"{{{version}}}"}]}"""; + var (_, recorder) = await this.DetectAsync(content); + + var component = recorder.GetDetectedComponents().Should().ContainSingle().Which.Component.Should().BeOfType().Which; + component.Name.Should().Be(name); + component.Version.Should().Be(version); + component.PackageUrl.Type.Should().Be("composer"); + component.PackageUrl.Version.Should().Be(version); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + public async Task ProductionAndDevPackages_HaveAccurateFlagsAndEdgesAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"Vendor/App","version":"v1.0.0","require":{"vendor/shared":"^2.0"}}, + {"name":"vendor/shared","version":"2.1.0"} + ],"packages-dev":[ + {"name":"vendor/tests","version":"dev-main","require":{"vendor/shared":"^2.0"}, + "require-dev":{"vendor/uninstalled":"*"}} + ]} + """); + + recorder.GetDetectedComponents().Should().HaveCount(3); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetDependenciesForComponent(Id("Vendor/App", "v1.0.0")).Should().Equal(Id("vendor/shared", "2.1.0")); + graph.GetDependenciesForComponent(Id("vendor/tests", "dev-main")).Should().Equal(Id("vendor/shared", "2.1.0")); + graph.GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo([Id("Vendor/App", "v1.0.0"), Id("vendor/tests", "dev-main")]); + graph.IsDevelopmentDependency(Id("vendor/tests", "dev-main")).Should().BeTrue(); + graph.IsDevelopmentDependency(Id("vendor/shared", "2.1.0")).Should().BeFalse(); + } + + [TestMethod] + public async Task DuplicateProductionAndDevEntries_MergeWithProductionPrecedenceAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[{"name":"vendor/shared","version":"1.0.0"}], + "packages-dev":[ + {"name":"vendor/shared","version":"1.0.0","require":{"vendor/child":"*"}}, + {"name":"vendor/child","version":"1.0.0"}]} + """); + + recorder.GetDetectedComponents().Should().HaveCount(2); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.IsDevelopmentDependency(Id("vendor/shared", "1.0.0")).Should().BeFalse(); + graph.IsDevelopmentDependency(Id("vendor/child", "1.0.0")).Should().BeTrue(); + graph.GetDependenciesForComponent(Id("vendor/shared", "1.0.0")).Should().Equal(Id("vendor/child", "1.0.0")); + } + + [TestMethod] + public async Task DifferentRawIdentities_AreRetainedAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"Vendor/Package","version":"v1.2.3"}, + {"name":"vendor/package","version":"v1.2.3"}, + {"name":"vendor/package","version":"1.2.3"} + ]} + """); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo( + ["Vendor/Package v1.2.3 - Composer", "vendor/package v1.2.3 - Composer", "vendor/package 1.2.3 - Composer"]); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + public async Task VirtualProvideAndReplace_ResolveToActualPackagesOnlyAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1.0","require":{"psr/log-implementation":"^3","vendor/old":"^2"}}, + {"name":"vendor/logger","version":"9.0","provide":{"psr/log-implementation":"3.0"}}, + {"name":"vendor/new","version":"v2.1.0","replace":{"vendor/old":"self.version"}} + ]} + """); + + recorder.GetDetectedComponents().Should().HaveCount(3); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetDependenciesForComponent(Id("vendor/app", "1.0")).Should().BeEquivalentTo([Id("vendor/logger", "9.0"), Id("vendor/new", "v2.1.0")]); + graph.GetAllExplicitlyReferencedComponents().Should().Equal(Id("vendor/app", "1.0")); + } + + [TestMethod] + public async Task VirtualProviders_AreFilteredByDeclaredVersionNotProviderVersionAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"^2"}}, + {"name":"vendor/one","version":"2","provide":{"virtual/api":"1.0"}}, + {"name":"vendor/two","version":"99","provide":{"virtual/api":"2.0"}} + ]} + """); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")) + .Should().Equal(Id("vendor/two", "99")); + } + + [TestMethod] + public async Task AmbiguousProviders_DoNotFabricateEdgesAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"*"}}, + {"name":"vendor/one","version":"1","provide":{"virtual/api":"*"}}, + {"name":"vendor/two","version":"1","replace":{"virtual/api":"*"}} + ]} + """); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")).Should().BeEmpty(); + recorder.GetDetectedComponents().Should().HaveCount(3); + } + + [TestMethod] + public async Task UnsupportedProviderConstraint_DoesNotCreateFalseUniqueProviderAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"^2"}}, + {"name":"vendor/known","version":"1","provide":{"virtual/api":"2"}}, + {"name":"vendor/unknown","version":"1","provide":{"virtual/api":"unsupported"}} + ]} + """); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")).Should().BeEmpty(); + } + + [TestMethod] + public async Task ActualPackage_TakesPrecedenceOverVirtualProviderAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"vendor/api":"*"}}, + {"name":"vendor/api","version":"2"}, + {"name":"vendor/provider","version":"3","provide":{"vendor/api":"*"}} + ]} + """); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")) + .Should().Equal(Id("vendor/api", "2")); + } + + [TestMethod] + public async Task DirectPackageAndManifestInlineAliases_KeepLockedSourceIdentityAsync() + { + this.WithManifest("""{"require":{"vendor/app":"*","vendor/branch":"dev-main as 1.0.0"}}"""); + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"vendor/branch":"dev-main as 1.0.0"}}, + {"name":"vendor/branch","version":"dev-main"} + ]} + """); + + recorder.GetDetectedComponents().Should().HaveCount(2); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetDependenciesForComponent(Id("vendor/app", "1")).Should().Equal(Id("vendor/branch", "dev-main")); + graph.GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo([Id("vendor/app", "1"), Id("vendor/branch", "dev-main")]); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow("provide")] + [DataRow("replace")] + public async Task VirtualInlineAliases_CompareSourceWithoutInventingRhsEdgesAsync(string section) + { + var content = $$$""" + {"packages":[ + {"name":"vendor/source","version":"1","require":{"virtual/source":"dev-main as 1.0.0"}}, + {"name":"vendor/numeric","version":"1","require":{"virtual/alias":"^1"}}, + {"name":"vendor/provider","version":"9","{{{section}}}":{"virtual/source":"dev-main","virtual/alias":"dev-main as 1.0.0"}} + ]} + """; + var (_, recorder) = await this.DetectAsync(content); + + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetDependenciesForComponent(Id("vendor/source", "1")).Should().Equal(Id("vendor/provider", "9")); + graph.GetDependenciesForComponent(Id("vendor/numeric", "1")).Should().BeEmpty(); + recorder.GetDetectedComponents().Should().HaveCount(3); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow("dev-main", false)] + [DataRow("^1", true)] + public async Task ManifestInlineAliasVirtualClaim_UsesSourceAsync(string requirement, bool expectProvider) + { + this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/app":"*"},"provide":{"virtual/api":"dev-main as 1.0.0"}}"""); + var content = $$$""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"{{{requirement}}}"}}, + {"name":"vendor/provider","version":"1","provide":{"virtual/api":"dev-main || ^1"}} + ]} + """; + this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), content); + var (_, recorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); + + var dependencies = recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")); + dependencies.Should().BeEquivalentTo(expectProvider ? [Id("vendor/provider", "1")] : []); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + public async Task PlatformRequirements_AreExcludedButNamespacedComposerPackagesRemainAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{ + "php":"^8","ext-json":"*","lib-pcre":"*","composer-plugin-api":"^2", + "composer-runtime-api":"^2","composer/installers":"*","ext-vendor/real":"*"}}, + {"name":"composer/installers","version":"2"}, + {"name":"ext-vendor/real","version":"3"} + ]} + """); + + recorder.GetDetectedComponents().Should().HaveCount(3); + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")) + .Should().BeEquivalentTo([Id("composer/installers", "2"), Id("ext-vendor/real", "3")]); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow("composer.lock", """{"packages":[{"name":"vendor/app","version":"1","require":{"php-future-capability":"^9"}}]}""")] + [DataRow("composer.json", """{"require":{"php-future-capability":"^9","vendor/app":"1"}}""")] + [DataRow("composer.json", """{"require-dev":{"php-future-capability":"^9","vendor/app":"1"}}""")] + public async Task UnnamespacedRequirements_AreDebugLoggedWithoutReportingFailuresAsync(string fileName, string content) + { + var logger = new Mock>(); + var (result, recorder) = await this.DetectorTestUtility.AddServiceMock(logger).WithFile(fileName, content).ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/app", "1")); + recorder.GetSkippedComponents().Should().BeEmpty(); + logger.Verify( + value => value.Log( + LogLevel.Debug, + It.IsAny(), + It.Is((state, _) => state.ToString().Contains("Skipping Composer dependency php-future-capability")), + It.IsAny(), + It.IsAny>()), + Times.Once); + logger.Verify( + value => value.Log( + LogLevel.Error, + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny>()), + Times.Never); + } + + [TestMethod] + public async Task Aliases_PreserveLockedIdentityAndResolveSelfVersionClaimsAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"^2"}}, + {"name":"vendor/branch","version":"dev-main","provide":{"virtual/api":"self.version"}, + "extra":{"branch-alias":{"dev-main":"2.x-dev"}}} + ],"aliases":[{"package":"vendor/branch","version":"dev-main","alias":"2.x-dev"}]} + """); + + recorder.GetDetectedComponents().Should().HaveCount(2); + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")) + .Should().Equal(Id("vendor/branch", "dev-main")); + } + + [TestMethod] + public async Task LockAliases_ResolveNormalizedVersionsWithoutBranchMetadataAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"^2"}}, + {"name":" Vendor--Name/Provider---Name ","version":" v1.0.0 ","provide":{"virtual/api":"self.version"}} + ],"aliases":[{"package":"vendor--name/provider---name","version":"1.0.0.0","alias":"2.x-dev"}]} + """); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")) + .Should().Equal(Id(" Vendor--Name/Provider---Name ", " v1.0.0 ")); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow("vendor/other", "1.0", true)] + [DataRow(" Vendor/Provider ", "3.0", true)] + [DataRow(" Vendor/Provider ", " v1.0.0 ", false)] + public async Task LockAliases_RequireUniqueNameAndVersionMatchesAsync(string otherName, string otherVersion, bool resolvesAlias) + { + var logger = new Mock>(); + this.DetectorTestUtility.AddServiceMock(logger); + var (_, recorder) = await this.DetectAsync($$$""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"^2"}}, + {"name":"vendor/provider","version":"1.0","provide":{"virtual/api":"self.version"}}, + {"name":"{{{otherName}}}","version":"{{{otherVersion}}}","provide":{"virtual/api":"self.version"}} + ],"aliases":[{"package":" VENDOR/PROVIDER ","version":"1.0.0.0","alias":" 2.x-dev "}]} + """); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo( + [Id("vendor/app", "1"), Id("vendor/provider", "1.0"), Id(otherName, otherVersion)]); + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")) + .Should().BeEquivalentTo(resolvesAlias ? [Id("vendor/provider", "1.0")] : []); + recorder.GetSkippedComponents().Should().BeEmpty(); + logger.Verify( + value => value.Log( + LogLevel.Warning, + It.IsAny(), + It.Is((state, _) => state.ToString().Contains("does not uniquely identify an installed package")), + It.IsAny(), + It.IsAny>()), + resolvesAlias ? Times.Never() : Times.Once()); + } + + [TestMethod] + [DataRow("null")] + [DataRow("[]")] + [DataRow("{}")] + [DataRow("""{"package":42,"version":"dev-main","alias":"2.x-dev"}""")] + [DataRow("""{"package":" ","version":"dev-main","alias":"2.x-dev"}""")] + [DataRow("""{"package":"vendor/branch","version":null,"alias":"2.x-dev"}""")] + [DataRow("""{"package":"vendor/branch","version":"dev-main","alias":false}""")] + [DataRow("""{"package":"vendor/branch","version":"dev-main","alias":" "}""")] + public async Task MalformedLockAliases_ReportFailureAndRetainValidAliasesAsync(string invalidAlias) + { + var (_, recorder) = await this.DetectAsync($$$""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"^2"}}, + {"name":"vendor/branch","version":"dev-main","provide":{"virtual/api":"self.version"}} + ],"aliases":[{{{invalidAlias}}},{"package":"vendor/branch","version":"dev-main","alias":"2.x-dev"}]} + """); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo( + [Id("vendor/app", "1"), Id("vendor/branch", "dev-main")]); + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")) + .Should().Equal(Id("vendor/branch", "dev-main")); + recorder.GetSkippedComponents().Should().Equal("aliases[0]"); + } + + [TestMethod] + [DataRow("null", "packages[1].extra.branch-alias")] + [DataRow("[]", "packages[1].extra.branch-alias")] + [DataRow("""{"dev-main":null}""", "packages[1].extra.branch-alias.dev-main")] + [DataRow("""{"dev-main":42}""", "packages[1].extra.branch-alias.dev-main")] + [DataRow("""{"dev-main":" "}""", "packages[1].extra.branch-alias.dev-main")] + public async Task MalformedBranchAliases_ReportFailureWithoutDroppingLockedPackagesAsync(string aliases, string failureLocation) + { + var (_, recorder) = await this.DetectAsync($$$""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"^2"}}, + {"name":"vendor/branch","version":"dev-main","provide":{"virtual/api":"self.version"}, + "extra":{"branch-alias":{{{aliases}}}}} + ]} + """); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo( + [Id("vendor/app", "1"), Id("vendor/branch", "dev-main")]); + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")) + .Should().BeEmpty(); + recorder.GetSkippedComponents().Should().Equal(failureLocation); + } + + [TestMethod] + public async Task ConflictingDuplicateDeclarations_ReportFailureWithoutFabricatedVirtualEdgesAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"^2"}}, + {"name":"vendor/provider","version":"1","provide":{"virtual/api":"1"}} + ],"packages-dev":[ + {"name":"vendor/provider","version":"1","provide":{"virtual/api":"2"}}, + {"name":"vendor/provider","version":"1","provide":{"virtual/api":"2"}} + ]} + """); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")).Should().BeEmpty(); + recorder.GetDetectedComponents().Should().HaveCount(2); + recorder.GetSkippedComponents().Should().HaveCount(1); + } + + [TestMethod] + public async Task ConflictingDuplicateDependencyNames_ReportFailuresAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/app","version":"1","require":{ + "invalid":"*","vendor/bad/name":"*","vendor/api":"1","VENDOR/API":"2","vendor/api":"2"}}, + {"name":"vendor/api","version":"2"} + ]} + """); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")).Should().BeEmpty(); + recorder.GetSkippedComponents().Should().Equal("packages[0].require.vendor/api"); + } + + [TestMethod] + public async Task SourceCycles_HaveCandidateRootsWithoutInventedEdgesAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/a","version":"1","require":{"vendor/b":"*","vendor/a":"*"}}, + {"name":"vendor/b","version":"1","require":{"vendor/a":"*","vendor/c":"*"}}, + {"name":"vendor/c","version":"1"} + ]} + """); + + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo([Id("vendor/a", "1"), Id("vendor/b", "1")]); + graph.GetDependenciesForComponent(Id("vendor/a", "1")).Should().Equal(Id("vendor/b", "1")); + graph.GetExplicitReferencedDependencyIds(Id("vendor/c", "1")).Should().BeEquivalentTo([Id("vendor/a", "1"), Id("vendor/b", "1")]); + } + + [TestMethod] + public async Task ReachableCycles_AreNotRootsAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor/root","version":"1","require":{"vendor/a":"*"}}, + {"name":"vendor/a","version":"1","require":{"vendor/b":"*"}}, + {"name":"vendor/b","version":"1","require":{"vendor/a":"*"}} + ]} + """); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetAllExplicitlyReferencedComponents().Should().Equal(Id("vendor/root", "1")); + } + + [TestMethod] + public async Task Manifest_KeepsDirectDependenciesEvenWhenAlsoTransitiveAsync() + { + this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/a":"*","vendor/b":"*"}}"""); + const string installed = """ + {"packages":[ + {"name":"vendor/a","version":"1","require":{"vendor/b":"*"}}, + {"name":"vendor/b","version":"1"} + ]} + """; + this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), installed); + var (_, recorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetAllExplicitlyReferencedComponents() + .Should().BeEquivalentTo([Id("vendor/a", "1"), Id("vendor/b", "1")]); + } + + [TestMethod] + public async Task Manifest_ProvidedVirtualDependencyDoesNotBecomePackageEdgeAsync() + { + this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/app":"*"},"provide":{"virtual/api":"1"}}"""); + const string installed = """ + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"*"}}, + {"name":"vendor/provider","version":"1","provide":{"virtual/api":"1"}} + ]} + """; + this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), installed); + var (_, recorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); + + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetDependenciesForComponent(Id("vendor/app", "1")).Should().BeEmpty(); + graph.GetAllExplicitlyReferencedComponents().Should().Equal(Id("vendor/app", "1")); + } + + [TestMethod] + [DataRow("""{"require":{"vendor/app":"*"},"version":"dev-main","extra":{"branch-alias":{"dev-main":"2.x-dev"}},"provide":{"virtual/api":"self.version"}}""")] + [DataRow("""{"require":{"vendor/app":"*"},"provide":{"virtual/api":"self.version"}}""")] + public async Task Manifest_SelfVersionClaimsNeverGuessAnInstalledProviderAsync(string manifest) + { + this.DetectorTestUtility.WithFile("composer.json", manifest); + const string installed = """ + {"packages":[ + {"name":"vendor/app","version":"1","require":{"virtual/api":"^2"}}, + {"name":"vendor/provider","version":"2","provide":{"virtual/api":"2"}} + ]} + """; + this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), installed); + var (_, recorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")).Should().BeEmpty(); + } + + [TestMethod] + [DataRow("{}")] + [DataRow("""{"packages":[]}""")] + [DataRow("""{"packages-dev":[]}""")] + [DataRow("""{"packages":[],"packages-dev":[]}""")] + public async Task MissingOrEmptySections_AreValidAsync(string content) + { + var (result, recorder) = await this.DetectorTestUtility.WithFile("composer.lock", content).ExecuteDetectorAsync(); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow("{")] + [DataRow("null")] + [DataRow("[]")] + [DataRow("""{"packages":null}""")] + [DataRow("""{"packages":{}}""")] + public async Task MalformedDocumentsOrSections_ReportParseFailuresAsync(string content) + { + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.lock", content).ExecuteDetectorAsync(); + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().NotBeEmpty(); + } + + [TestMethod] + public async Task MalformedEntries_ReportFailuresAndRetainValidPackagesAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[null,{},{"name":"vendor/no-version"},{"name":"vendor/bad","version":42}, + {"name":"not-namespaced","version":"1"},{"name":"vendor/empty","version":" "}, + {"name":"vendor/valid","version":"1","require":{"vendor/child":false}}, + {"name":"vendor/valid2","version":"2","provide":[]}]} + """); + + recorder.GetDetectedComponents().Should().HaveCount(2); + recorder.GetSkippedComponents().Should().HaveCount(8); + } + + [TestMethod] + public async Task PackageNamesOutsideLegacySchema_AreDetectedAndLinkedAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[ + {"name":"vendor-/package","version":"1"}, + {"name":"vendor/package.","version":"1"}, + {"name":"vendor/package---name","version":"1"}, + {"name":"vendor--name/package","version":"1"}, + {"name":" Vendor/Package--Name ","version":" v1.2.3 "}, + {"name":"vendor/root","version":"2","require":{"vendor/package--name":"*","vendor/package---name":"*"}} + ]} + """); + + recorder.GetDetectedComponents().Should().HaveCount(6); + recorder.GetSkippedComponents().Should().BeEmpty(); + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/root", "2")) + .Should().BeEquivalentTo([Id(" Vendor/Package--Name ", " v1.2.3 "), Id("vendor/package---name", "1")]); + } + + [TestMethod] + public async Task MalformedSiblingManifest_ReportsFailureAndFallsBackToLockedGraphRootsAsync() + { + this.WithManifest("{"); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.lock", """{"packages":[{"name":"vendor/a","version":"1"}]}""").ExecuteDetectorAsync(); + recorder.GetSkippedComponents().Should().ContainSingle(); + recorder.GetDependencyGraphsByLocation().Values.Single().GetAllExplicitlyReferencedComponents().Should().Equal(Id("vendor/a", "1")); + } + + [TestMethod] + public async Task DifferentLockedVersions_AreRetainedWithoutAmbiguousNameEdgesAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[{"name":"vendor/app","version":"1","require":{"vendor/shared":"*"}},{"name":"vendor/shared","version":"1"}], + "packages-dev":[{"name":"vendor/shared","version":"2"}]} + """); + recorder.GetDetectedComponents().Should().HaveCount(3); + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")).Should().BeEmpty(); + } + + [TestMethod] + public async Task MultipleLockfiles_KeepDependencyGraphsIsolatedAsync() + { + var first = Path.Combine(Path.GetTempPath(), "first", "composer.lock"); + var second = Path.Combine(Path.GetTempPath(), "second", "composer.lock"); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.lock", """{"packages":[{"name":"vendor/app","version":"1","require":{"vendor/child":"*"}},{"name":"vendor/child","version":"1"}]}""", fileLocation: first) + .WithFile("composer.lock", """{"packages":[{"name":"vendor/app","version":"1"},{"name":"vendor/child","version":"2"}]}""", fileLocation: second) + .ExecuteDetectorAsync(); + + var graphs = recorder.GetDependencyGraphsByLocation(); + graphs.Should().HaveCount(2); + graphs[first].GetDependenciesForComponent(Id("vendor/app", "1")).Should().Equal(Id("vendor/child", "1")); + graphs[second].GetDependenciesForComponent(Id("vendor/app", "1")).Should().BeEmpty(); + graphs[second].GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo([Id("vendor/app", "1"), Id("vendor/child", "2")]); + } + + [TestMethod] + public async Task LocalFixture_ProducesExpectedOfflineGraphAsync() + { + var directory = Path.Combine(AppContext.BaseDirectory, "TestFiles", "Composer"); + this.WithManifest(await File.ReadAllTextAsync(Path.Combine(directory, "composer.json"))); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.lock", await File.ReadAllTextAsync(Path.Combine(directory, "composer.lock"))).ExecuteDetectorAsync(); + recorder.GetDetectedComponents().Should().HaveCount(5); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo([Id("example/application-library", "v1.2.0"), Id("example/test-runner", "dev-main")]); + graph.GetDependenciesForComponent(Id("example/application-library", "v1.2.0")) + .Should().BeEquivalentTo([Id("example/logger", "3.1.0"), Id("example/replacement", "1.4.0"), Id("composer/installers", "v2.3.0")]); + graph.IsDevelopmentDependency(Id("example/test-runner", "dev-main")).Should().BeTrue(); + graph.GetAdditionalRelatedFiles().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + private static string CreateLongFileLocation(int pathLength, string fileName) + { + var path = new StringBuilder(pathLength).Append(Path.GetPathRoot(Path.GetTempPath())); + var directoryLength = pathLength - fileName.Length - 1; + while (path.Length < directoryLength) + { + var remaining = directoryLength - path.Length; + if (remaining > 101) + { + path.Append('d', 100).Append(Path.DirectorySeparatorChar); + } + else + { + path.Append('d', remaining); + } + } + + return path.Append(Path.DirectorySeparatorChar).Append(fileName).ToString(); + } + + private static string Id(string name, string version) => new ComposerComponent(name, version).Id; + + private Mock WithInstalledFile(string vendorDirectory, string content) + { + var location = Path.Combine(vendorDirectory, "composer", "installed.json"); + var files = new Mock(); + files.Setup(value => value.Exists(location)).Returns(true); + files.Setup(value => value.MakeFileStream(location)).Returns(() => new MemoryStream(Encoding.UTF8.GetBytes(content))); + this.DetectorTestUtility.AddServiceMock(files); + return files; + } + + private Task<(IndividualDetectorScanResult ScanResult, IComponentRecorder ComponentRecorder)> DetectAsync(string content) => + this.DetectorTestUtility.WithFile("composer.lock", content).ExecuteDetectorAsync(); + + private Mock WithManifest(string content, string fileName = "composer.json") + { + var factory = new Mock(); + var file = new Mock(); + file.SetupGet(value => value.Location).Returns(Path.Combine(Path.GetTempPath(), fileName)); + file.SetupGet(value => value.Stream).Returns(() => new MemoryStream(Encoding.UTF8.GetBytes(content))); + IEnumerable files = [file.Object]; + factory.Setup(value => value.GetComponentStreams(It.Is(directory => directory.FullName == Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar)), It.Is>(patterns => patterns.SequenceEqual(new[] { "composer.json" })), It.IsAny(), false)) + .Returns(files); + this.DetectorTestUtility.AddServiceMock(factory); + return factory; + } +} diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs new file mode 100644 index 000000000..17a4e5d86 --- /dev/null +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs @@ -0,0 +1,367 @@ +#nullable disable +namespace Microsoft.ComponentDetection.Detectors.Tests; + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using AwesomeAssertions; +using Microsoft.ComponentDetection.Contracts; +using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.ComponentDetection.Detectors.Composer; +using Microsoft.ComponentDetection.TestsUtilities; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +[TestClass] +[TestCategory("Governance/All")] +[TestCategory("Governance/ComponentDetection")] +public class ComposerPlatformTests : BaseDetectorTest +{ + private Mock commands; + private Mock> logger; + + [TestInitialize] + public void Initialize() + { + this.commands = new Mock(MockBehavior.Strict); + this.commands.Setup(value => value.IsCommandLineExecution()).Returns(true); + this.logger = new Mock>(); + this.DetectorTestUtility.AddServiceMock(new Mock()).AddServiceMock(this.commands).AddServiceMock(this.logger); + } + + [TestMethod] + public async Task ComposerFiles_RequestPlatformInventoryPerNonVendorDirectoryWithoutChangingPackageGraphsAsync() + { + this.WithOutput(""" + {"platform":[ + {"name":"php","version":"8.4.27","direct-dependency":true}, + {"name":"ext-openssl","version":"8.4.27","direct-dependency":false}, + {"name":"lib-openssl","version":"3.5.0"}, + {"name":"composer","version":"2.11.1"}, + {"name":"hhvm","version":"4.172.0"}, + {"name":"php-64bit","version":"8.4.27"}, + {"name":"composer-plugin-api","version":"2.9.0"}, + {"name":"composer-runtime-api","version":"2.2.2"}, + {"name":"vendor/not-platform","version":"1.0"} + ]} + """); + var rootLocation = Path.Combine(Path.GetTempPath(), "composer.lock"); + var childLocation = Path.Combine(Path.GetTempPath(), "child", "composer.json"); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"vendor/child":"1.2.3"}}""", fileLocation: childLocation) + .WithFile("composer.json", """{"require":{"vendor/noise":"9.0"}}""", fileLocation: Path.Combine(Path.GetTempPath(), "vendor", "package", "composer.json")) + .WithFile("composer.json", """{"require":{"vendor/app":"^1","php":"^8"}}""") + .WithFile("composer.lock", """{"packages":[{"name":"vendor/app","version":"1.0.0"}]}""", fileLocation: rootLocation) + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo( + ["php 8.4.27 - PhpSdk", "ext-openssl 8.4.27 - PhpSdk", "lib-openssl 3.5.0 - PhpSdk", "composer 2.11.1 - PhpSdk", "hhvm 4.172.0 - PhpSdk", "vendor/app 1.0.0 - Composer", "vendor/child 1.2.3 - Composer"]); + var graphs = recorder.GetDependencyGraphsByLocation(); + graphs[rootLocation].GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo(["php 8.4.27 - PhpSdk", "vendor/app 1.0.0 - Composer"]); + recorder.GetDetectedComponents().Where(component => component.Component is PhpSdkComponent).Should() + .OnlyContain(component => graphs[rootLocation].IsDevelopmentDependency(component.Component.Id) == true); + graphs[rootLocation].IsDevelopmentDependency("vendor/app 1.0.0 - Composer").Should().BeFalse(); + graphs[rootLocation].GetDependenciesForComponent("vendor/app 1.0.0 - Composer").Should().BeEmpty(); + graphs[childLocation].GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo(["php 8.4.27 - PhpSdk", "vendor/child 1.2.3 - Composer"]); + graphs[childLocation].IsDevelopmentDependency("php 8.4.27 - PhpSdk").Should().BeTrue(); + graphs[childLocation].IsDevelopmentDependency("vendor/child 1.2.3 - Composer").Should().BeFalse(); + recorder.GetSkippedComponents().Should().BeEmpty(); + string[] expectedCandidates = ["composer.cmd", "composer.bat"]; + string[] expectedArguments = ["--no-plugins", "--no-scripts", "--no-interaction", "--no-ansi", "show", "--platform", "--format=json"]; + foreach (var projectDirectory in new[] { Path.GetDirectoryName(rootLocation), Path.GetDirectoryName(childLocation) }) + { + this.commands.Verify( + value => value.ExecuteCommandAsync( + "composer", + It.Is>(candidates => candidates.SequenceEqual(expectedCandidates)), + It.Is(directory => directory.FullName == projectDirectory), + It.Is(token => token.CanBeCanceled), + It.Is(arguments => arguments.SequenceEqual(expectedArguments))), + Times.Once); + } + + this.commands.Verify(value => value.IsCommandLineExecution(), Times.Exactly(2)); + this.commands.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task LockfileWithoutManifest_InfersPackageRootsWithoutPromotingPlatformEntriesAsync() + { + this.WithOutput(""" + {"platform":[ + {"name":"php","version":"8.4.27","direct-dependency":true}, + {"name":"ext-json","version":"8.4.27","direct-dependency":false} + ]} + """); + const string lockContent = """ + {"packages":[ + {"name":"vendor/app","version":"1.0.0","require":{"vendor/child":"^2"}}, + {"name":"vendor/child","version":"2.0.0"} + ]} + """; + var (result, recorder) = await this.DetectorTestUtility.WithFile("composer.lock", lockContent).ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo( + ["php 8.4.27 - PhpSdk", "vendor/app 1.0.0 - Composer"]); + graph.GetDependenciesForComponent("vendor/app 1.0.0 - Composer").Should().Equal("vendor/child 2.0.0 - Composer"); + graph.GetDependenciesForComponent("ext-json 8.4.27 - PhpSdk").Should().BeEmpty(); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + public async Task Projects_RecordDifferentPlatformVersionsAndDirectReferencesAsync() + { + this.WithOutput("""{"platform":[{"name":"php","version":"8.4.27","direct-dependency":true},{"name":"ext-json","version":"8.4.27","direct-dependency":false}]}"""); + var rootLocation = Path.Combine(Path.GetTempPath(), "composer.json"); + var childLocation = Path.Combine(Path.GetTempPath(), "child", "composer.json"); + this.commands.Setup(value => value.ExecuteCommandAsync( + "composer", + It.IsAny>(), + It.Is(directory => directory.FullName == Path.GetDirectoryName(childLocation)), + It.IsAny(), + It.IsAny())) + .ReturnsAsync(new CommandLineExecutionResult + { + ExitCode = 0, + StdOut = """{"platform":[{"name":"php","version":"8.3.15","direct-dependency":false},{"name":"ext-json","version":"8.4.27","direct-dependency":true}]}""", + }); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", "{}", fileLocation: childLocation) + .WithFile("composer.json", "{}", fileLocation: rootLocation) + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should() + .BeEquivalentTo(["php 8.4.27 - PhpSdk", "php 8.3.15 - PhpSdk", "ext-json 8.4.27 - PhpSdk"]); + var graphs = recorder.GetDependencyGraphsByLocation(); + graphs[rootLocation].GetAllExplicitlyReferencedComponents().Should().Equal("php 8.4.27 - PhpSdk"); + graphs[childLocation].GetAllExplicitlyReferencedComponents().Should().Equal("ext-json 8.4.27 - PhpSdk"); + graphs[rootLocation].IsDevelopmentDependency("php 8.4.27 - PhpSdk").Should().BeTrue(); + graphs[childLocation].IsDevelopmentDependency("php 8.3.15 - PhpSdk").Should().BeTrue(); + graphs[rootLocation].IsDevelopmentDependency("ext-json 8.4.27 - PhpSdk").Should().BeTrue(); + graphs[childLocation].IsDevelopmentDependency("ext-json 8.4.27 - PhpSdk").Should().BeTrue(); + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); + } + + [TestMethod] + [DataRow("vendor", false)] + [DataRow("dependencies", false)] + [DataRow("environment-vendor", true)] + public async Task VendorDirectories_DoNotQueryPlatformWhenParentInventoryIsMissingAsync(string vendorDirectory, bool fromEnvironment) + { + this.WithOutput("""{"platform":[{"name":"php","version":"8.4.27"}]}"""); + var environment = new Mock(); + if (fromEnvironment) + { + environment.Setup(value => value.GetEnvironmentVariable("COMPOSER_VENDOR_DIR")).Returns(vendorDirectory); + } + + this.DetectorTestUtility.AddServiceMock(environment); + var configuredVendorDirectory = fromEnvironment ? "ignored-vendor" : vendorDirectory; + var rootLocation = Path.Combine(Path.GetTempPath(), "composer.json"); + var vendorLocation = Path.Combine(Path.GetTempPath(), vendorDirectory, "package", "composer.json"); + var independentLocation = Path.Combine(Path.GetTempPath(), vendorDirectory + "-project", "composer.json"); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"vendor/nested":"2.0"}}""", fileLocation: vendorLocation) + .WithFile("composer.json", """{"require":{"vendor/independent":"3.0"}}""", fileLocation: independentLocation) + .WithFile("composer.json", $$$"""{"config":{"vendor-dir":"{{{configuredVendorDirectory}}}"},"require":{"vendor/app":"1.0"}}""", fileLocation: rootLocation) + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should() + .BeEquivalentTo(["php 8.4.27 - PhpSdk", "vendor/app 1.0 - Composer", "vendor/nested 2.0 - Composer", "vendor/independent 3.0 - Composer"]); + recorder.GetDependencyGraphsByLocation()[vendorLocation].GetAllExplicitlyReferencedComponents().Should().Equal("vendor/nested 2.0 - Composer"); + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); + this.commands.Verify( + value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.Is(directory => directory.FullName == Path.GetDirectoryName(vendorLocation)), It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + [DataRow("vendor")] + [DataRow("VeNdOr")] + public async Task VendorOnlyInput_DoesNotQueryPlatformWithoutAParentProjectAsync(string vendorDirectory) + { + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"vendor/package":"1.0"}}""", fileLocation: Path.Combine(Path.GetTempPath(), vendorDirectory, "package", "composer.json")) + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("vendor/package 1.0 - Composer"); + this.commands.VerifyNoOtherCalls(); + } + + [TestMethod] + [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":true}""", true, false)] + [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":false}""", false, false)] + [DataRow("""{"name":"php","version":"8.4.27"}""", false, false)] + [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":"true"}""", false, true)] + [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":null}""", false, true)] + [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":1}""", false, true)] + public async Task PlatformDirectDependency_UsesComposerMetadataWithoutDroppingInventoryAsync(string entry, bool explicitlyReferenced, bool invalidMetadata) + { + this.WithOutput($$"""{"platform":[{{entry}}]}"""); + var location = Path.Combine(Path.GetTempPath(), "composer.json"); + var (result, recorder) = await this.DetectorTestUtility.WithFile("composer.json", "{}", fileLocation: location).ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("php 8.4.27 - PhpSdk"); + var graph = recorder.GetDependencyGraphsByLocation()[location]; + string[] expectedExplicitReferences = explicitlyReferenced ? ["php 8.4.27 - PhpSdk"] : []; + graph.GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo(expectedExplicitReferences); + graph.IsDevelopmentDependency("php 8.4.27 - PhpSdk").Should().BeTrue(); + recorder.GetSkippedComponents().Should().BeEmpty(); + this.VerifyWarning("invalid direct-dependency", invalidMetadata ? Times.Once() : Times.Never()); + } + + [TestMethod] + public async Task NoComposerFile_DoesNotQueryTheEnvironmentAsync() + { + var (_, recorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Should().BeEmpty(); + this.commands.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task LibraryHost_DoesNotQueryTheEnvironmentAsync() + { + this.commands.Setup(value => value.IsCommandLineExecution()).Returns(false); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/app":"1.0"}}""").ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("vendor/app 1.0 - Composer"); + this.commands.Verify(value => value.IsCommandLineExecution(), Times.Once); + this.commands.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task InvalidProjectJson_DoesNotQueryTheEnvironmentAsync() + { + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", "{").ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().ContainSingle(); + this.commands.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task PlatformOverrides_AreNotReportedAsInstalledVersionsAsync() + { + this.WithOutput(""" + {"platform":[ + {"name":"php","version":"7.4.0","description":"Package overridden via config.platform, actual: 8.4.27"}, + {"name":"ext-json","version":"8.4.27","description":"The json PHP extension. Package disabled via config.platform"}, + {"name":"composer","version":"2.11.1"} + ]} + """); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", """{"config":{"platform":{"php":"7.4.0"}},"require":{"php":"^7"}}""").ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("composer 2.11.1 - PhpSdk"); + this.VerifyWarning("config.platform", Times.Never()); + } + + [TestMethod] + [DataRow("")] + [DataRow("{")] + [DataRow("[]")] + [DataRow("{}")] + [DataRow("{\"platform\":{}}")] + public async Task InvalidOutput_WarnsAndPreservesPackageDetectionAsync(string output) + { + this.WithOutput(output); + var (result, recorder) = await this.DetectorTestUtility.WithFile("composer.lock", """{"packages":[{"name":"vendor/app","version":"1.0"}]}""").ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("vendor/app 1.0 - Composer"); + recorder.GetSkippedComponents().Should().BeEmpty(); + this.VerifyWarning("Composer platform inventory", Times.Once()); + } + + [TestMethod] + public async Task InvalidEntries_WarnAndRetainValidEnvironmentComponentsAsync() + { + this.WithOutput("""{"platform":[null,{}, {"name":"php","version":8}, {"name":"ext-json","version":" "}, {"name":"php","version":"8.4.27"}]}"""); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", "{}").ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("php 8.4.27 - PhpSdk"); + this.VerifyWarning("invalid package identity", Times.Exactly(4)); + } + + [TestMethod] + public async Task MissingComposer_WarnsForEachNonVendorProjectAsync() + { + this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) + .ThrowsAsync(new Win32Exception(2)); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"vendor/a":"1.0"}}""") + .WithFile("composer.json", """{"require":{"vendor/b":"2.0"}}""", fileLocation: Path.Combine(Path.GetTempPath(), "child", "composer.json")) + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo(["vendor/a 1.0 - Composer", "vendor/b 2.0 - Composer"]); + this.VerifyWarning("Unable to run Composer platform inventory", Times.Exactly(2)); + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); + } + + [TestMethod] + public async Task NonzeroExit_WarnsWithoutReportingPartialOutputAsync() + { + this.WithOutput("""{"platform":[{"name":"php","version":"8.4.27"}]}""", exitCode: 1); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/app":"1.0"}}""").ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("vendor/app 1.0 - Composer"); + this.VerifyWarning("exit code 1", Times.Once()); + } + + [TestMethod] + public async Task HungCommand_TimesOutWithoutFailingPackageDetectionAsync() + { + this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(async (string _, IEnumerable _, DirectoryInfo _, CancellationToken token, string[] _) => + { + await Task.Delay(Timeout.Infinite, token); + return new CommandLineExecutionResult(); + }); + var stopwatch = Stopwatch.StartNew(); + var (result, recorder) = await this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/app":"1.0"}}""").ExecuteDetectorAsync(); + + stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(12)); + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("vendor/app 1.0 - Composer"); + this.VerifyWarning("10-second limit", Times.Once()); + } + + [TestMethod] + public async Task CallerCancellation_IsNotSwallowedAsAnInventoryTimeoutAsync() + { + using var cancellation = new CancellationTokenSource(); + this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(async (string _, IEnumerable _, DirectoryInfo _, CancellationToken token, string[] _) => + { + await cancellation.CancelAsync(); + return await Task.FromCanceled(token); + }); + Func action = async () => await this.DetectorTestUtility.WithFile("composer.json", "{}").ExecuteDetectorAsync(cancellation.Token); + + await action.Should().ThrowAsync(); + this.VerifyWarning("10-second limit", Times.Never()); + } + + private void WithOutput(string output, int exitCode = 0) => + this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new CommandLineExecutionResult { StdOut = output, StdErr = "test error", ExitCode = exitCode }); + + private void VerifyWarning(string message, Times times) => + this.logger.Verify( + value => value.Log( + LogLevel.Warning, + It.IsAny(), + It.Is((state, _) => state.ToString().Contains(message)), + It.IsAny(), + It.IsAny>()), + times); +} diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerVersionConstraintTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerVersionConstraintTests.cs new file mode 100644 index 000000000..312f246b2 --- /dev/null +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerVersionConstraintTests.cs @@ -0,0 +1,141 @@ +namespace Microsoft.ComponentDetection.Detectors.Tests; + +using AwesomeAssertions; +using Microsoft.ComponentDetection.Detectors.Composer; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +[TestCategory("Governance/All")] +[TestCategory("Governance/ComponentDetection")] +public class ComposerVersionConstraintTests +{ + [TestMethod] + [DataRow("1.2.3", "1.2.3")] + [DataRow(" v1.2.3 ", "v1.2.3")] + [DataRow("= 1.2.3", "1.2.3")] + [DataRow("==1.2.3-beta2", "1.2.3-beta2")] + [DataRow("1.2", "1.2")] + [DataRow("1.2.3.4", "1.2.3.4")] + public void ExactManifestVersion_PreservesPinnedIdentity(string constraint, string expected) + { + ComposerVersionConstraint.TryGetExactVersion(constraint, out var version).Should().BeTrue(); + version.Should().Be(expected); + } + + [TestMethod] + [DataRow("^1.0", "1.2.3", true)] + [DataRow("^1.0", "^2.0", false)] + [DataRow("^2.0", "1.0", false)] + [DataRow("~1.2", "1.9.0", true)] + [DataRow("~1.2", "2.0.0", false)] + [DataRow("~1.2.3", "1.3.0", false)] + [DataRow("1.2", "1.2.0", true)] + [DataRow("1.2", "1.2.1", false)] + [DataRow("1.*", "1.9.0", true)] + [DataRow(">=1.0, <2.0", "1.4.0", true)] + [DataRow(">= 1.0 < 2.0", "1.4.0", true)] + [DataRow("^1 | ^3", "3.1.0", true)] + [DataRow("^1 || ^3", "2.1.0", false)] + [DataRow("^1||^3", "3.1.0", true)] + [DataRow("^1|^3", "2.1.0", false)] + [DataRow("^1\t||\r\n^3", "3.1.0", true)] + [DataRow("^1\u00a0|\u2003^3", "3.1.0", true)] + [DataRow("^2.0@dev", "2.x-dev", true)] + [DataRow("dev-main as 2.x-dev", "^2", false)] + [DataRow("dev-main#123", "dev-main", true)] + [DataRow("dev-main", "dev-next", false)] + [DataRow("*", "dev-main", true)] + [DataRow("dev-main", "*", true)] + [DataRow("v1.2.3", "1.2.3", true)] + [DataRow("nonsense", "*", false)] + [DataRow("nonsense", "nonsense", false)] + [DataRow("~9999999999999999999999.1", "1.0", false)] + [DataRow("<=1.2", "1.2.1", false)] + [DataRow(">1.2", "1.2.1", true)] + [DataRow(">=1.2 <2", "1.2.0-beta2", true)] + [DataRow("!=1.2.3", "1.2.3", false)] + [DataRow("!=1.2.3", "1.2.4", true)] + [DataRow("^1 !=1.2.3", "1.2.3", false)] + [DataRow("^1 !=1.2.3", "1.2.4", true)] + [DataRow(">=1 <2 !=1.2.3", ">=1.2.3-stable <=1.2.3", false)] + [DataRow(">=1 <2 !=1.2.3", ">=1.2.3 <=1.2.3", true)] + [DataRow("^1 !=1.2.3 || ^3", "3.0.0", true)] + [DataRow("1.2.3.4", "1.2.3.4", true)] + [DataRow("1.2.3.4", "1.2.3.5", false)] + [DataRow("~1.2.3.4", "1.2.3.9", true)] + [DataRow("~1.2.3.4", "1.2.4", false)] + [DataRow("^0.0.3.4", "0.0.3.9", true)] + [DataRow("^0.0.3.4", "0.0.4", false)] + [DataRow("1.0 - 2.0", "2.0.9", true)] + [DataRow("1.0 - 2.0", "2.1.0", false)] + [DataRow("1.0.0 - 2.0.0", "2.0.1", false)] + [DataRow("1.2.3beta2", "1.2.3-beta.2", true)] + [DataRow(">1.2.3-RC1 <1.2.3-stable", "1.2.3-rc2", true)] + [DataRow(">1.2.3-RC1 <1.2.3", "1.2.3-rc2", false)] + [DataRow(">1.2.3", "1.2.3-p1", true)] + [DataRow("<0.0.0-dev", "*", false)] + [DataRow("!=dev-main", "dev-main", false)] + [DataRow("!=dev-main", "dev-next", true)] + [DataRow("!=dev-main", "1.0", true)] + [DataRow("!=1.0", "dev-main", true)] + [DataRow("1.2.x-dev", "1.2.9", true)] + [DataRow("1.2.x-dev", "1.3.0", false)] + [DataRow("", "*", false)] + [DataRow("~9223372036854775807", "1.0", false)] + public void VirtualCompatibility_RespectsComposerConstraintSemantics(string required, string provided, bool expected) => + ComposerVersionConstraint.Intersects(required, provided).Should().Be(expected); + + [TestMethod] + [DataRow("dev-main as 1.0.0", "dev-main", true)] + [DataRow("dev-main as 1.0.0", "1.0.0", false)] + [DataRow("dev-main as 1.0.0", "dev-other", false)] + [DataRow(" dev-main as 1.0.0 ", "dev-main", true)] + [DataRow("dev-main#reference as 1.0.0", "dev-main", true)] + [DataRow("1.0.0 as 2.0.0", "1.0.0", true)] + [DataRow("1.0.0 as 2.0.0", "2.0.0", false)] + [DataRow("dev-main as 1.0.0 || ^2", "2.1.0", true)] + [DataRow("^2 || dev-main as 1.0.0", "2.1.0", true)] + [DataRow("^2 || dev-main as 1.0.0", "1.0.0", false)] + [DataRow("dev-main as 1.0.0, !=dev-other", "dev-main", true)] + [DataRow("dev-main as 1.0.0, !=dev-main", "dev-main", false)] + public void InlineAliases_CompareNativeSourceConstraints(string required, string provided, bool expected) + { + ComposerVersionConstraint.TryIntersects(required, provided, out var intersects).Should().BeTrue(); + intersects.Should().Be(expected); + ComposerVersionConstraint.TryIntersects(provided, required, out var reverse).Should().BeTrue(); + reverse.Should().Be(expected); + } + + [TestMethod] + [DataRow("1.2.3", "1.2.3.0", true)] + [DataRow(" v1.2.3 ", "1.2.3.0", true)] + [DataRow(" dev-main ", "dev-main", true)] + [DataRow(" release-next#revision ", "release-next#revision", true)] + [DataRow("v1.2.3-beta2", "1.2.3.0-beta.2", true)] + [DataRow("1.2.3", "1.2.3.1", false)] + [DataRow("dev-main", "dev-next", false)] + [DataRow("1.x-dev", "1.9999999.9999999.9999999-dev", true)] + [DataRow("1.2.x-dev", "1.2.9999999.9999999-dev", true)] + public void LockAliasVersionMatching_UsesComposerNumericNormalization(string left, string right, bool expected) => + ComposerVersionConstraint.VersionsEqual(left, right).Should().Be(expected); + + [TestMethod] + [DataRow("|^1")] + [DataRow("^1|")] + [DataRow("||^1")] + [DataRow("^1||")] + [DataRow("^1|||^3")] + [DataRow("^1||||^3")] + [DataRow("^1| |^3")] + public void EmptyAlternatives_AreRejected(string constraint) => + ComposerVersionConstraint.TryIntersects(constraint, "*", out _).Should().BeFalse(); + + [TestMethod] + public void UnsupportedConstraint_IsDistinctFromDisjointRanges() + { + ComposerVersionConstraint.TryIntersects("^1", "^2", out var disjoint).Should().BeTrue(); + disjoint.Should().BeFalse(); + ComposerVersionConstraint.TryIntersects("^1", "unsupported", out _).Should().BeFalse(); + ComposerVersionConstraint.TryIntersects("unsupported as 1.0.0", "1.0.0", out _).Should().BeFalse(); + } +} diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj b/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj index 45a66cfd5..bcae8f33d 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj @@ -71,6 +71,12 @@ Always + + Always + + + Always + diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/TestFiles/Composer/composer.json b/test/Microsoft.ComponentDetection.Detectors.Tests/TestFiles/Composer/composer.json new file mode 100644 index 000000000..a35c2ef13 --- /dev/null +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/TestFiles/Composer/composer.json @@ -0,0 +1,5 @@ +{ + "name": "example/root", + "require": {"example/application-library": "^1.2"}, + "require-dev": {"example/test-runner": "dev-main as 2.x-dev"} +} diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/TestFiles/Composer/composer.lock b/test/Microsoft.ComponentDetection.Detectors.Tests/TestFiles/Composer/composer.lock new file mode 100644 index 000000000..599b05bab --- /dev/null +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/TestFiles/Composer/composer.lock @@ -0,0 +1,45 @@ +{ + "_readme": ["Offline Composer detector unit test fixture."], + "packages": [ + { + "name": "example/application-library", + "version": "v1.2.0", + "require": { + "php": "^8.1", + "ext-json": "*", + "psr/log-implementation": "^3.0", + "example/replaced": "^1.0", + "composer/installers": "^2.0" + } + }, + { + "name": "example/logger", + "version": "3.1.0", + "provide": {"psr/log-implementation": "3.0"} + }, + { + "name": "example/replacement", + "version": "1.4.0", + "replace": {"example/replaced": "self.version"} + }, + { + "name": "composer/installers", + "version": "v2.3.0", + "require": {"composer-plugin-api": "^2.0"} + } + ], + "packages-dev": [ + { + "name": "example/test-runner", + "version": "dev-main", + "require": {"example/application-library": "^1.2", "lib-pcre": "*"}, + "extra": {"branch-alias": {"dev-main": "2.x-dev"}} + } + ], + "aliases": [ + {"package": "example/test-runner", "version": "dev-main", "alias": "2.x-dev", "alias_normalized": "2.9999999.9999999.9999999-dev"} + ], + "platform": {"php": "^8.1"}, + "platform-dev": [], + "plugin-api-version": "2.6.0" +} diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentConfigTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentConfigTests.cs index ada741fe5..4a3529ed8 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentConfigTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentConfigTests.cs @@ -6,6 +6,7 @@ namespace Microsoft.ComponentDetection.Orchestrator.Tests.Experiments; using System.Threading.Tasks; using AwesomeAssertions; using Microsoft.ComponentDetection.Contracts; +using Microsoft.ComponentDetection.Detectors.Composer; using Microsoft.ComponentDetection.Detectors.CondaLock; using Microsoft.ComponentDetection.Detectors.Swift; using Microsoft.ComponentDetection.Orchestrator.Experiments.Configs; @@ -53,6 +54,38 @@ public void ExperimentConfig_CondaLockDetectorIsNotInExperimentGroup() this.configs.Should().OnlyContain(config => !config.IsInExperimentGroup(condaLockDetector)); } + [TestMethod] + public void ExperimentConfig_ComposerDetectorIsOnlyInComposerExperiment() + { + var detector = new ComposerComponentDetector(null, null, null, null, null, null); + var config = this.configs.Should().ContainSingle(config => config.IsInExperimentGroup(detector)).Which; + + config.Should().BeOfType().Which.Name.Should().Be("Composer"); + this.configs.Should().OnlyContain(config => !config.IsInControlGroup(detector)); + } + + [TestMethod] + public void ExperimentConfig_ComposerExperimentExcludesOtherDetectors() + { + var config = this.configs.OfType().Single(); + var detector = Mock.Of(); + + config.IsInControlGroup(detector).Should().BeFalse(); + config.IsInExperimentGroup(detector).Should().BeFalse(); + } + + [TestMethod] + [DataRow(0)] + [DataRow(1)] + public void ExperimentConfig_ComposerExperimentDoesNotFilterDetectorRuns(int numComponents) + { + var config = this.configs.OfType().Single(); + var detector = new ComposerComponentDetector(null, null, null, null, null, null); + + config.ShouldRecord(detector, numComponents).Should().BeTrue(); + config.ShouldRecord(Mock.Of(), numComponents).Should().BeTrue(); + } + [TestMethod] public async Task ExperimentConfig_InitShouldNotThrowAsync() { diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentServiceTests.cs index ee369f242..d6e423535 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentServiceTests.cs @@ -9,6 +9,8 @@ namespace Microsoft.ComponentDetection.Orchestrator.Tests.Experiments; using Microsoft.ComponentDetection.Common.DependencyGraph; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.ComponentDetection.Detectors.Composer; using Microsoft.ComponentDetection.Detectors.NuGet; using Microsoft.ComponentDetection.Orchestrator.Commands; using Microsoft.ComponentDetection.Orchestrator.Experiments; @@ -88,6 +90,43 @@ public void RecordDetectorRun_AddsComponentsToControlAndExperimentGroup() Times.Once()); } + [TestMethod] + public async Task RecordDetectorRun_ComposerExperimentReportsPackagesAndSdkAsync() + { + var config = new ComposerExperiment(); + var detector = new ComposerComponentDetector(null, null, null, null, null, null); + List components = + [ + new() { Component = new ComposerComponent("vendor/package", "1.0"), IsDevelopmentDependency = false }, + new() { Component = new PhpSdkComponent("php", "8.4.27"), IsDevelopmentDependency = true }, + ]; + this.SetupGraphMock(components); + ExperimentDiff processedDiff = null; + this.experimentProcessorMock + .Setup(processor => processor.ProcessExperimentAsync(config, It.IsAny())) + .Callback((_, diff) => processedDiff = diff) + .Returns(Task.CompletedTask); + var service = new ExperimentService( + [config], + [this.experimentProcessorMock.Object], + this.graphTranslationServiceMock.Object, + this.loggerMock.Object); + + service.RecordDetectorRun(detector, this.componentRecorder, this.scanSettingsMock.Object); + await service.FinishAsync(); + + this.experimentProcessorMock.Verify( + processor => processor.ProcessExperimentAsync(config, It.IsAny()), + Times.Once()); + processedDiff.AddedIds.Should().BeEquivalentTo(["vendor/package 1.0 - Composer", "php 8.4.27 - PhpSdk"]); + processedDiff.RemovedIds.Should().BeEmpty(); + processedDiff.ControlDetectors.Should().BeEmpty(); + processedDiff.ExperimentalDetectors.Should().ContainSingle(); + var developmentChange = processedDiff.DevelopmentDependencyChanges.Should().ContainSingle().Which; + developmentChange.Id.Should().Be("php 8.4.27 - PhpSdk"); + developmentChange.NewValue.Should().BeTrue(); + } + [TestMethod] public async Task RecordDetectorRun_FiltersExperimentsAsync() { diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Microsoft.ComponentDetection.Orchestrator.Tests.csproj b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Microsoft.ComponentDetection.Orchestrator.Tests.csproj index 72d0de8c7..6abbb1243 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Microsoft.ComponentDetection.Orchestrator.Tests.csproj +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Microsoft.ComponentDetection.Orchestrator.Tests.csproj @@ -11,6 +11,7 @@ + diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/ComposerProcessingTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/ComposerProcessingTests.cs new file mode 100644 index 000000000..de292e689 --- /dev/null +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/ComposerProcessingTests.cs @@ -0,0 +1,132 @@ +#nullable disable +namespace Microsoft.ComponentDetection.Orchestrator.Tests.Services; + +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reactive.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using AwesomeAssertions; +using Microsoft.ComponentDetection.Common.DependencyGraph; +using Microsoft.ComponentDetection.Contracts; +using Microsoft.ComponentDetection.Contracts.Internal; +using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.ComponentDetection.Detectors.Composer; +using Microsoft.ComponentDetection.Orchestrator.Commands; +using Microsoft.ComponentDetection.Orchestrator.Experiments; +using Microsoft.ComponentDetection.Orchestrator.Services; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; +using Spectre.Console; + +[TestClass] +[TestCategory("Governance/All")] +[TestCategory("Governance/ComponentDetection")] +public class ComposerProcessingTests +{ + [TestMethod] + [DataRow(false, false, false, false)] + [DataRow(true, false, false, false)] + [DataRow(false, true, false, false)] + [DataRow(true, true, false, false)] + [DataRow(false, true, true, false)] + [DataRow(true, true, true, false)] + [DataRow(false, false, false, true)] + [DataRow(true, false, false, true)] + [DataRow(false, true, false, true)] + [DataRow(true, true, false, true)] + [DataRow(false, true, true, true)] + [DataRow(true, true, true, true)] + public async Task ExperimentalComposer_AlwaysExecutesButOnlyIncludesResultsWhenEnabledAsync(bool enabled, bool manifestOnly, bool unresolved, bool platform) + { + var walker = new Mock(); + var location = Path.Combine(Path.GetTempPath(), manifestOnly ? "composer.json" : "composer.lock"); + var childLocation = Path.Combine(Path.GetTempPath(), "child", manifestOnly ? "composer.json" : "composer.lock"); + var manifest = unresolved + ? """{"require":{"vendor/package":"^v1.0.0"}}""" + : """{"require":{"vendor/package":"v1.0.0"}}"""; + var content = manifestOnly + ? manifest + : """{"packages":[{"name":"vendor/package","version":"v1.0.0"}]}"""; + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)); + using var childStream = new MemoryStream(Encoding.UTF8.GetBytes(content)); + walker.Setup(value => value.GetFilteredComponentStreamObservable(It.IsAny(), It.IsAny>(), It.IsAny())) + .Returns, IComponentRecorder>((_, _, recorder) => + { + var requests = new List(); + (string Location, Stream Stream)[] files = [(location, stream), (childLocation, childStream)]; + foreach (var (fileLocation, fileStream) in files) + { + var file = new Mock(); + file.SetupGet(value => value.Location).Returns(fileLocation); + file.SetupGet(value => value.Stream).Returns(fileStream); + requests.Add(new ProcessRequest { ComponentStream = file.Object, SingleFileComponentRecorder = recorder.CreateSingleFileComponentRecorder(fileLocation) }); + } + + return requests.ToObservable(); + }); + var experiments = new Mock(); + var processor = new DetectorProcessingService(walker.Object, experiments.Object, NullLogger.Instance, Mock.Of()); + var commands = new Mock(); + commands.Setup(value => value.IsCommandLineExecution()).Returns(platform); + commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync((string _, IEnumerable _, DirectoryInfo directory, CancellationToken _, string[] _) => new CommandLineExecutionResult + { + ExitCode = 0, + StdOut = directory.FullName == Path.GetDirectoryName(location) + ? """{"platform":[{"name":"php","version":"8.4.27","direct-dependency":true},{"name":"ext-json","version":"8.4.27","direct-dependency":false}]}""" + : """{"platform":[{"name":"php","version":"8.3.15","direct-dependency":false},{"name":"ext-json","version":"8.4.27","direct-dependency":true}]}""", + }); + var detector = new ComposerComponentDetector(Mock.Of(), walker.Object, Mock.Of(), Mock.Of(), commands.Object, NullLogger.Instance); + var settings = new ScanSettings { SourceDirectory = new DirectoryInfo(Path.GetTempPath()), DetectorArgs = new Dictionary(), NoSummary = true }; + var restrictions = new DetectorRestrictions { ExplicitlyEnabledDetectorIds = enabled ? ["Composer"] : [] }; + + var expectedCount = (unresolved ? 0 : 1) + (platform ? 3 : 0); + for (var scan = 0; scan < 2; scan++) + { + stream.Position = 0; + childStream.Position = 0; + var result = await processor.ProcessDetectorsAsync(settings, [detector], restrictions); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + var components = result.ComponentRecorders.SelectMany(value => value.Recorder.GetDetectedComponents()).Select(value => value.Component).ToList(); + components.Should().HaveCount(enabled ? expectedCount : 0); + if (enabled && !unresolved) + { + components.OfType().Should().ContainSingle().Which.Version.Should().Be("v1.0.0"); + result.ComponentRecorders.Single().Recorder.GetDependencyGraphsByLocation()[location] + .IsDevelopmentDependency("vendor/package v1.0.0 - Composer").Should().BeFalse(); + } + + if (enabled && platform) + { + components.OfType().Select(component => component.Id).Should() + .BeEquivalentTo(["php 8.4.27 - PhpSdk", "php 8.3.15 - PhpSdk", "ext-json 8.4.27 - PhpSdk"]); + var graphs = result.ComponentRecorders.Single().Recorder.GetDependencyGraphsByLocation(); + graphs[location].GetAllExplicitlyReferencedComponents().Where(id => id.EndsWith(" - PhpSdk")).Should().Equal("php 8.4.27 - PhpSdk"); + graphs[childLocation].GetAllExplicitlyReferencedComponents().Where(id => id.EndsWith(" - PhpSdk")).Should().Equal("ext-json 8.4.27 - PhpSdk"); + graphs[location].IsDevelopmentDependency("php 8.4.27 - PhpSdk").Should().BeTrue(); + graphs[childLocation].IsDevelopmentDependency("php 8.3.15 - PhpSdk").Should().BeTrue(); + graphs[location].IsDevelopmentDependency("ext-json 8.4.27 - PhpSdk").Should().BeTrue(); + graphs[childLocation].IsDevelopmentDependency("ext-json 8.4.27 - PhpSdk").Should().BeTrue(); + } + } + + experiments.Verify( + value => value.RecordDetectorRun( + detector, + It.Is(recorder => recorder.GetDetectedComponents().Count() == expectedCount), + settings, + It.Is(run => run.ComponentsFoundCount == expectedCount && run.IsExperimental == !enabled)), + Times.Exactly(2)); + foreach (var projectDirectory in new[] { Path.GetDirectoryName(location), Path.GetDirectoryName(childLocation) }) + { + commands.Verify( + value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.Is(directory => directory.FullName == projectDirectory), It.IsAny(), It.IsAny()), + platform ? Times.Exactly(2) : Times.Never()); + } + } +} diff --git a/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtilityBuilder.cs b/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtilityBuilder.cs index 9781ecb13..619e965ec 100644 --- a/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtilityBuilder.cs +++ b/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtilityBuilder.cs @@ -6,6 +6,7 @@ namespace Microsoft.ComponentDetection.TestsUtilities; using System.IO; using System.Linq; using System.Reactive.Linq; +using System.Threading; using System.Threading.Tasks; using Microsoft.ComponentDetection.Common; using Microsoft.ComponentDetection.Common.DependencyGraph; @@ -86,7 +87,7 @@ public DetectorTestUtilityBuilder WithScanRequest(ScanRequest scanRequest) return this; } - public async Task<(IndividualDetectorScanResult ScanResult, IComponentRecorder ComponentRecorder)> ExecuteDetectorAsync() + public async Task<(IndividualDetectorScanResult ScanResult, IComponentRecorder ComponentRecorder)> ExecuteDetectorAsync(CancellationToken cancellationToken = default) { if (this.scanRequest is null) { @@ -109,7 +110,7 @@ public DetectorTestUtilityBuilder WithScanRequest(ScanRequest scanRequest) this.InitializeFileMocks(); - var result = await this.detector.ExecuteDetectorAsync(this.scanRequest); + var result = await this.detector.ExecuteDetectorAsync(this.scanRequest, cancellationToken); return (result, this.componentRecorder); } diff --git a/test/Microsoft.ComponentDetection.VerificationTests/resources/composer/composer.json b/test/Microsoft.ComponentDetection.VerificationTests/resources/composer/composer.json new file mode 100644 index 000000000..a35c2ef13 --- /dev/null +++ b/test/Microsoft.ComponentDetection.VerificationTests/resources/composer/composer.json @@ -0,0 +1,5 @@ +{ + "name": "example/root", + "require": {"example/application-library": "^1.2"}, + "require-dev": {"example/test-runner": "dev-main as 2.x-dev"} +} diff --git a/test/Microsoft.ComponentDetection.VerificationTests/resources/composer/composer.lock b/test/Microsoft.ComponentDetection.VerificationTests/resources/composer/composer.lock new file mode 100644 index 000000000..f1523cb5f --- /dev/null +++ b/test/Microsoft.ComponentDetection.VerificationTests/resources/composer/composer.lock @@ -0,0 +1,45 @@ +{ + "_readme": ["Offline Composer detector verification fixture."], + "packages": [ + { + "name": "example/application-library", + "version": "v1.2.0", + "require": { + "php": "^8.1", + "ext-json": "*", + "psr/log-implementation": "^3.0", + "example/replaced": "^1.0", + "composer/installers": "^2.0" + } + }, + { + "name": "example/logger", + "version": "3.1.0", + "provide": {"psr/log-implementation": "3.0"} + }, + { + "name": "example/replacement", + "version": "1.4.0", + "replace": {"example/replaced": "self.version"} + }, + { + "name": "composer/installers", + "version": "v2.3.0", + "require": {"composer-plugin-api": "^2.0"} + } + ], + "packages-dev": [ + { + "name": "example/test-runner", + "version": "dev-main", + "require": {"example/application-library": "^1.2", "lib-pcre": "*"}, + "extra": {"branch-alias": {"dev-main": "2.x-dev"}} + } + ], + "aliases": [ + {"package": "example/test-runner", "version": "dev-main", "alias": "2.x-dev", "alias_normalized": "2.9999999.9999999.9999999-dev"} + ], + "platform": {"php": "^8.1"}, + "platform-dev": [], + "plugin-api-version": "2.6.0" +} From c8bca9365a5555b7cc6650cbf592489e26edb929 Mon Sep 17 00:00:00 2001 From: Greg Villicana Date: Wed, 11 Nov 2026 13:56:59 -0800 Subject: [PATCH 2/5] PR comment --- .../composer/ComposerComponentDetector.cs | 202 ++++++++++++-- .../ComposerDetectorTests.cs | 82 ++++++ .../ComposerPlatformTests.cs | 254 +++++++++++++++++- .../Services/ComposerProcessingTests.cs | 10 +- 4 files changed, 508 insertions(+), 40 deletions(-) diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs index 1093148d8..aa54a9838 100644 --- a/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs @@ -1,6 +1,7 @@ namespace Microsoft.ComponentDetection.Detectors.Composer; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; @@ -41,6 +42,7 @@ public sealed class ComposerComponentDetector : FileComponentDetector, IExperime private readonly ICommandLineInvocationService commandLineInvocationService; private readonly ConcurrentHashSet coveredVendorDirectories = []; private readonly ConcurrentHashSet knownPlatformVendorDirectories = []; + private readonly ConcurrentDictionary preparedProjects = []; public ComposerComponentDetector( IComponentStreamEnumerableFactory componentStreamEnumerableFactory, @@ -77,14 +79,46 @@ protected override async Task> OnPrepareDetectionAsy { this.coveredVendorDirectories.Clear(); this.knownPlatformVendorDirectories.Clear(); + this.preparedProjects.Clear(); var files = await processRequests.ToList(); cancellationToken.ThrowIfCancellationRequested(); - // Process projects before their installed packages, regardless of discovery order. Return only the lockfiles when both a manifest and lockfile are present in the same directory. - return files.GroupBy(request => Path.GetDirectoryName(request.ComponentStream.Location)) - .OrderBy(group => group.Key!.Length) - .Select(group => group.FirstOrDefault(request => Path.GetFileName(request.ComponentStream.Location).Equals(ComposerLockFileName, StringComparison.OrdinalIgnoreCase)) ?? group.First()) - .ToObservable(); + foreach (var group in files.GroupBy(request => Path.GetDirectoryName(request.ComponentStream.Location)!)) + { + cancellationToken.ThrowIfCancellationRequested(); + ProcessRequest? lockfile = null; + IComponentStream? manifest = null; + foreach (var file in group) + { + var fileName = Path.GetFileName(file.ComponentStream.Location); + if (fileName.Equals(ComposerLockFileName, StringComparison.OrdinalIgnoreCase)) + { + lockfile ??= file; + } + else if (fileName.Equals(ComposerManifestFileName, StringComparison.OrdinalIgnoreCase)) + { + manifest ??= file.ComponentStream; + } + + if (lockfile is not null && manifest is not null) + { + break; + } + } + + var request = lockfile ?? group.First(); + var project = await this.PrepareProjectAsync(request.ComponentStream.Location, manifest, cancellationToken); + this.preparedProjects[request] = project; + this.knownPlatformVendorDirectories.Add(project.VendorDirectory); + } + + return this.OrderProjects(cancellationToken).ToObservable(); + } + + protected override Task OnDetectionFinishedAsync() + { + this.preparedProjects.Clear(); + return Task.CompletedTask; } protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary detectorArgs, CancellationToken cancellationToken = default) @@ -104,17 +138,32 @@ protected override async Task OnFileFoundAsync(ProcessRequest processRequest, ID var recorder = processRequest.SingleFileComponentRecorder; this.Logger.LogDebug("Reading Composer file {Location}", file.Location); - using var document = await this.ReadDocumentAsync(file.Stream, file.Location, recorder, cancellationToken); - if (document is null) + var isManifest = Path.GetFileName(file.Location).Equals(ComposerManifestFileName, StringComparison.OrdinalIgnoreCase); + using var document = isManifest ? null : await this.ReadDocumentAsync(file.Stream, file.Location, recorder, cancellationToken); + if (!isManifest && document is null) { return; } - var isManifest = Path.GetFileName(file.Location).Equals(ComposerManifestFileName, StringComparison.OrdinalIgnoreCase); - using var manifest = isManifest ? null : await this.ReadManifestAsync(file.Location, recorder, cancellationToken); - var manifestRoot = isManifest ? document.RootElement : manifest?.RootElement; - var vendorDirectory = this.GetVendorDirectory(file.Location, manifestRoot); - this.knownPlatformVendorDirectories.Add(vendorDirectory); + var project = this.preparedProjects[processRequest]; + var manifestRoot = project.Manifest; + if (project.ManifestError is not null) + { + this.Logger.LogError(project.ManifestError, "Invalid Composer JSON in {Location}", project.ManifestLocation); + recorder.RegisterPackageParseFailure(project.ManifestLocation); + } + else if (manifestRoot is not null && manifestRoot.Value.ValueKind != JsonValueKind.Object) + { + this.ReportFailure(recorder, project.ManifestLocation, "Expected a JSON object."); + manifestRoot = null; + } + + if (isManifest && manifestRoot is null) + { + return; + } + + var vendorDirectory = project.VendorDirectory; await this.RegisterPlatformInventoryAsync(file.Location, recorder, cancellationToken); var packages = new Dictionary(); @@ -125,13 +174,13 @@ protected override async Task OnFileFoundAsync(ProcessRequest processRequest, ID this.Logger.LogWarning( $"Composer manifest {{Location}} without a sibling {ComposerLockFileName} or usable {InstalledPackagesFileName}. Provide either to improve accuracy; otherwise only exact versions are detected.", file.Location); - this.ReadManifestRequirements(document.RootElement, recorder, file.Location, cancellationToken); + this.ReadManifestRequirements(manifestRoot!.Value, recorder, file.Location, cancellationToken); return; } } else { - this.ReadPackages(document.RootElement, PackagesPropertyName, false, packages, recorder, cancellationToken); + this.ReadPackages(document!.RootElement, PackagesPropertyName, false, packages, recorder, cancellationToken); this.ReadPackages(document.RootElement, "packages-dev", true, packages, recorder, cancellationToken); this.ReadLockAliases(document.RootElement, packages, recorder, cancellationToken); } @@ -250,9 +299,19 @@ private async Task RegisterPlatformInventoryAsync(string location, ISingleFileCo CommandLineExecutionResult result; try { - string[] arguments = ["--no-plugins", "--no-scripts", "--no-interaction", "--no-ansi", "show", "--platform", "--format=json"]; + var projectDirectory = Path.GetDirectoryName(location)!; + if (projectDirectory.IndexOfAny(['"', '\r', '\n']) >= 0 || + (OperatingSystem.IsWindows() && projectDirectory.IndexOfAny(['%', '!']) >= 0)) + { + this.Logger.LogWarning("Composer platform inventory cannot safely pass project directory {Directory} to the command line; continuing with package files only.", projectDirectory); + return; + } + + // Avoid a trailing backslash escaping the argument's closing quote for filesystem roots. + projectDirectory = Path.EndsInDirectorySeparator(projectDirectory) ? $"{projectDirectory}." : projectDirectory; + string[] arguments = ["--no-plugins", "--no-scripts", "--no-interaction", "--no-ansi", $"--working-dir=\"{projectDirectory}\"", "show", "--platform", "--format=json"]; result = await this.commandLineInvocationService.ExecuteCommandAsync( - ComposerName, [$"{ComposerName}.cmd", $"{ComposerName}.bat"], new DirectoryInfo(Path.GetDirectoryName(location)!), timeout.Token, arguments); + ComposerName, [$"{ComposerName}.cmd", $"{ComposerName}.bat"], workingDirectory: null, cancellationToken: timeout.Token, parameters: arguments); timeout.Token.ThrowIfCancellationRequested(); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) @@ -400,8 +459,20 @@ private async Task ReadInstalledPackagesAsync(string vendorDirectory, Dict return false; } - using var stream = this.fileUtilityService.MakeFileStream(location); - using var document = await this.ReadDocumentAsync(stream, location, recorder, cancellationToken, allowPackageArray: true); + JsonDocument? inventory; + try + { + using var stream = this.fileUtilityService.MakeFileStream(location); + inventory = await this.ReadDocumentAsync(stream, location, recorder, cancellationToken, allowPackageArray: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + this.Logger.LogWarning(exception, "Unable to read Composer installed inventory at {Location}; falling back to manifest requirements.", location); + recorder.RegisterPackageParseFailure(location); + return false; + } + + using var document = inventory; if (document is null) { return false; @@ -468,17 +539,98 @@ private async Task ReadInstalledPackagesAsync(string vendorDirectory, Dict return null; } - private async Task ReadManifestAsync(string lockLocation, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + private async Task PrepareProjectAsync(string location, IComponentStream? manifest, CancellationToken cancellationToken) + { + var directory = new DirectoryInfo(Path.GetDirectoryName(location)!); + manifest ??= this.ComponentStreamEnumerableFactory.GetComponentStreams( + directory, [ComposerManifestFileName], null, recursivelyScanDirectories: false).FirstOrDefault(); + JsonElement? root = null; + JsonException? error = null; + if (manifest is not null) + { + try + { + using var document = await JsonDocument.ParseAsync(manifest.Stream, LenientJsonDocumentOptions, cancellationToken); + root = document.RootElement.Clone(); + } + catch (JsonException exception) + { + // Report invalid manifests only if their project is processed, not when covered by an owner's inventory. + error = exception; + } + } + + var vendorDirectory = this.GetVendorDirectory(location, root is { ValueKind: JsonValueKind.Object } ? root : null); + return new PreparedProject(vendorDirectory, manifest?.Location ?? Path.Combine(directory.FullName, ComposerManifestFileName), root, error); + } + + private List OrderProjects(CancellationToken cancellationToken) { - var directory = new DirectoryInfo(Path.GetDirectoryName(lockLocation)!); - foreach (var file in this.ComponentStreamEnumerableFactory.GetComponentStreams( - directory, [ComposerManifestFileName], null, recursivelyScanDirectories: false)) + var projectDirectories = this.preparedProjects.Keys.ToDictionary(request => request, request => Path.GetDirectoryName(request.ComponentStream.Location)!); + var ownersByVendorDirectory = this.GetVendorOwnersByDirectory(projectDirectories); + var dependents = projectDirectories.Keys.ToDictionary(request => request, _ => new List()); + var remainingOwners = new Dictionary(projectDirectories.Count); + foreach (var (request, projectDirectory) in projectDirectories) { cancellationToken.ThrowIfCancellationRequested(); - return await this.ReadDocumentAsync(file.Stream, file.Location, recorder, cancellationToken); + var ownerCount = 0; + for (var directory = projectDirectory; directory is not null; directory = Path.GetDirectoryName(directory)) + { + if (ownersByVendorDirectory.TryGetValue(directory, out var matches)) + { + // Each owner has one vendor directory, so it can only match once along this path. + foreach (var owner in matches) + { + if (owner != request) + { + dependents[owner].Add(request); + ownerCount++; + } + } + } + } + + remainingOwners.Add(request, ownerCount); } - return null; + var ready = new Queue(remainingOwners.Where(entry => entry.Value == 0).Select(entry => entry.Key)); + var ordered = new List(projectDirectories.Count); + while (ready.TryDequeue(out var request)) + { + cancellationToken.ThrowIfCancellationRequested(); + ordered.Add(request); + foreach (var dependent in dependents[request]) + { + if (--remainingOwners[dependent] == 0) + { + ready.Enqueue(dependent); + } + } + } + + if (ordered.Count != projectDirectories.Count) + { + this.Logger.LogWarning("Composer vendor directory ownership contains a cycle; some projects cannot be processed before their vendor inputs."); + ordered.AddRange(remainingOwners.Where(entry => entry.Value > 0).Select(entry => entry.Key)); + } + + return ordered; + } + + private Dictionary> GetVendorOwnersByDirectory(Dictionary projectDirectories) + { + var ownersByVendorDirectory = new Dictionary>(StringComparer.Ordinal); + foreach (var group in this.preparedProjects.GroupBy(project => project.Value.VendorDirectory)) + { + var vendorPrefix = Path.EndsInDirectorySeparator(group.Key) ? group.Key : $"{group.Key}{Path.DirectorySeparatorChar}"; + + // An absolute COMPOSER_VENDOR_DIR also applies to package manifests inside that directory; they are not additional owners. + var externalOwners = group.Where(project => !projectDirectories[project.Key].StartsWith(vendorPrefix, StringComparison.Ordinal)) + .Select(project => project.Key).ToList(); + ownersByVendorDirectory.Add(group.Key, externalOwners.Count > 0 ? externalOwners : group.Select(project => project.Key).ToList()); + } + + return ownersByVendorDirectory; } private void ReadPackages(JsonElement root, string section, bool isDevelopment, Dictionary packages, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) @@ -804,6 +956,8 @@ private void ReportFailure(ISingleFileComponentRecorder recorder, string locatio recorder.RegisterPackageParseFailure(location); } + private sealed record PreparedProject(string VendorDirectory, string ManifestLocation, JsonElement? Manifest, JsonException? ManifestError); + private sealed class LockedPackage( ComposerComponent component, bool isDevelopment, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs index d79840d93..c71fdf92a 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs @@ -6,6 +6,7 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System.IO; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; using AwesomeAssertions; using Microsoft.ComponentDetection.Contracts; @@ -241,6 +242,60 @@ public async Task MalformedInstalledInventory_ReportsFailureAndFallsBackToExactD recorder.GetSkippedComponents().Should().ContainSingle(); } + [TestMethod] + [DataRow("permission", false)] + [DataRow("missing-file", false)] + [DataRow("missing-directory", false)] + [DataRow("io", false)] + [DataRow("permission", true)] + [DataRow("io", true)] + public async Task UnreadableInstalledInventory_ReportsFailureAndContinuesWithFallbackAndOtherProjectsAsync(string failure, bool duringRead) + { + Exception exception = failure switch + { + "permission" => new UnauthorizedAccessException("Inventory access denied."), + "missing-file" => new FileNotFoundException("Inventory was removed."), + "missing-directory" => new DirectoryNotFoundException("Inventory directory was removed."), + "io" => new IOException("Inventory could not be read."), + _ => throw new ArgumentOutOfRangeException(nameof(failure)), + }; + var location = Path.Combine(Path.GetTempPath(), "vendor", "composer", "installed.json"); + var files = this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), "{}"); + if (duringRead) + { + var stream = new Mock(); + stream.SetupGet(value => value.CanRead).Returns(true); + stream.Setup(value => value.ReadAsync(It.IsAny>(), It.IsAny())) + .Returns(() => ValueTask.FromException(exception)); + files.Setup(value => value.MakeFileStream(location)).Returns(stream.Object); + } + else + { + files.Setup(value => value.MakeFileStream(location)).Throws(exception); + } + + var logger = new Mock>(); + var (result, recorder) = await this.DetectorTestUtility.AddServiceMock(logger) + .WithFile("composer.json", """{"require":{"vendor/pinned":"1.2.3","vendor/ranged":"^2"}}""") + .WithFile("composer.json", """{"require":{"vendor/nested":"3.0"}}""", fileLocation: Path.Combine(Path.GetTempPath(), "vendor", "acme", "lib", "composer.json")) + .WithFile("composer.lock", """{"packages":[{"name":"vendor/later","version":"4.0"}]}""", fileLocation: Path.Combine(Path.GetTempPath(), "next-project", "composer.lock")) + .ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should() + .BeEquivalentTo([Id("vendor/pinned", "1.2.3"), Id("vendor/nested", "3.0"), Id("vendor/later", "4.0")]); + recorder.GetSkippedComponents().Should().Equal(location); + files.Verify(value => value.MakeFileStream(location), Times.Once()); + logger.Verify( + value => value.Log( + LogLevel.Warning, + It.IsAny(), + It.Is((state, _) => state.ToString().Contains(location)), + exception, + It.IsAny>()), + Times.Once()); + } + [TestMethod] [DataRow("{\"config\":false}")] [DataRow("{\"config\":null}")] @@ -537,6 +592,33 @@ public async Task ManifestAndLock_AlwaysUseLockedVersionsRegardlessOfDiscoveryOr Times.Never); } + [TestMethod] + public async Task InterleavedProjectFiles_UseEachSiblingManifestWithItsLockfileAsync() + { + var firstDirectory = Path.Combine(Path.GetTempPath(), "first"); + var secondDirectory = Path.Combine(Path.GetTempPath(), "second"); + var firstLock = Path.Combine(firstDirectory, "composer.lock"); + var secondLock = Path.Combine(secondDirectory, "composer.lock"); + const string locked = """{"packages":[{"name":"vendor/app","version":"1.0.0"},{"name":"vendor/child","version":"2.0.0"}]}"""; + var factory = new Mock(MockBehavior.Strict); + var (result, recorder) = await this.DetectorTestUtility.AddServiceMock(factory) + .WithFile("composer.json", """{"require":{"vendor/app":"^1"}}""", fileLocation: Path.Combine(firstDirectory, "composer.json")) + .WithFile("composer.lock", locked, fileLocation: secondLock) + .WithFile("composer.lock", locked, fileLocation: firstLock) + .WithFile("composer.json", """{"require":{"vendor/child":"^2"}}""", fileLocation: Path.Combine(secondDirectory, "composer.json")) + .ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should() + .BeEquivalentTo([Id("vendor/app", "1.0.0"), Id("vendor/child", "2.0.0")]); + var graphs = recorder.GetDependencyGraphsByLocation(); + graphs.Keys.Should().BeEquivalentTo([firstLock, secondLock]); + graphs[firstLock].GetAllExplicitlyReferencedComponents().Should().Equal(Id("vendor/app", "1.0.0")); + graphs[secondLock].GetAllExplicitlyReferencedComponents().Should().Equal(Id("vendor/child", "2.0.0")); + recorder.GetSkippedComponents().Should().BeEmpty(); + factory.VerifyNoOtherCalls(); + } + [TestMethod] public async Task DirectoryGrouping_DistinguishesPathsByCaseAsync() { diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs index 17a4e5d86..393abd780 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs @@ -73,14 +73,14 @@ public async Task ComposerFiles_RequestPlatformInventoryPerNonVendorDirectoryWit graphs[childLocation].IsDevelopmentDependency("vendor/child 1.2.3 - Composer").Should().BeFalse(); recorder.GetSkippedComponents().Should().BeEmpty(); string[] expectedCandidates = ["composer.cmd", "composer.bat"]; - string[] expectedArguments = ["--no-plugins", "--no-scripts", "--no-interaction", "--no-ansi", "show", "--platform", "--format=json"]; foreach (var projectDirectory in new[] { Path.GetDirectoryName(rootLocation), Path.GetDirectoryName(childLocation) }) { + string[] expectedArguments = ["--no-plugins", "--no-scripts", "--no-interaction", "--no-ansi", $"--working-dir=\"{projectDirectory}\"", "show", "--platform", "--format=json"]; this.commands.Verify( value => value.ExecuteCommandAsync( "composer", It.Is>(candidates => candidates.SequenceEqual(expectedCandidates)), - It.Is(directory => directory.FullName == projectDirectory), + null, It.Is(token => token.CanBeCanceled), It.Is(arguments => arguments.SequenceEqual(expectedArguments))), Times.Once); @@ -122,12 +122,13 @@ public async Task Projects_RecordDifferentPlatformVersionsAndDirectReferencesAsy this.WithOutput("""{"platform":[{"name":"php","version":"8.4.27","direct-dependency":true},{"name":"ext-json","version":"8.4.27","direct-dependency":false}]}"""); var rootLocation = Path.Combine(Path.GetTempPath(), "composer.json"); var childLocation = Path.Combine(Path.GetTempPath(), "child", "composer.json"); + var childArgument = $"--working-dir=\"{Path.GetDirectoryName(childLocation)}\""; this.commands.Setup(value => value.ExecuteCommandAsync( "composer", It.IsAny>(), - It.Is(directory => directory.FullName == Path.GetDirectoryName(childLocation)), + null, It.IsAny(), - It.IsAny())) + It.Is(arguments => arguments.Contains(childArgument)))) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, @@ -147,7 +148,7 @@ public async Task Projects_RecordDifferentPlatformVersionsAndDirectReferencesAsy graphs[childLocation].IsDevelopmentDependency("php 8.3.15 - PhpSdk").Should().BeTrue(); graphs[rootLocation].IsDevelopmentDependency("ext-json 8.4.27 - PhpSdk").Should().BeTrue(); graphs[childLocation].IsDevelopmentDependency("ext-json 8.4.27 - PhpSdk").Should().BeTrue(); - this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny()), Times.Exactly(2)); } [TestMethod] @@ -177,12 +178,198 @@ public async Task VendorDirectories_DoNotQueryPlatformWhenParentInventoryIsMissi recorder.GetDetectedComponents().Select(component => component.Component.Id).Should() .BeEquivalentTo(["php 8.4.27 - PhpSdk", "vendor/app 1.0 - Composer", "vendor/nested 2.0 - Composer", "vendor/independent 3.0 - Composer"]); recorder.GetDependencyGraphsByLocation()[vendorLocation].GetAllExplicitlyReferencedComponents().Should().Equal("vendor/nested 2.0 - Composer"); - this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny()), Times.Exactly(2)); + var vendorArgument = $"--working-dir=\"{Path.GetDirectoryName(vendorLocation)}\""; this.commands.Verify( - value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.Is(directory => directory.FullName == Path.GetDirectoryName(vendorLocation)), It.IsAny(), It.IsAny()), + value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.Is(arguments => arguments.Contains(vendorArgument))), Times.Never); } + [TestMethod] + [DataRow("lock", "relative", false)] + [DataRow("installed", "relative", false)] + [DataRow("missing", "relative", false)] + [DataRow("lock", "absolute", false)] + [DataRow("installed", "absolute", false)] + [DataRow("missing", "absolute", false)] + [DataRow("lock", "environment", false)] + [DataRow("installed", "environment", false)] + [DataRow("missing", "environment", false)] + [DataRow("lock", "relative", true)] + [DataRow("installed", "absolute", true)] + [DataRow("missing", "environment", true)] + public async Task ExternalVendorDirectory_ProcessesOwnerBeforeShorterVendorPathAsync(string inventory, string vendorSetting, bool ownerFirst) + { + this.WithOutput("""{"platform":[{"name":"php","version":"8.4.27"}]}"""); + var root = Path.Combine(Path.GetTempPath(), "composer-external"); + var ownerDirectory = Path.Combine(root, "applications", "long-application"); + var vendorDirectory = Path.Combine(root, "v"); + var ownerLocation = Path.Combine(ownerDirectory, "composer.json"); + var vendorLocation = Path.Combine(vendorDirectory, "acme", "lib", "composer.json"); + var independentLocation = Path.Combine(root, "v-project", "composer.json"); + var environment = new Mock(); + if (vendorSetting == "environment") + { + environment.Setup(value => value.GetEnvironmentVariable("COMPOSER_VENDOR_DIR")).Returns(vendorDirectory); + } + + this.DetectorTestUtility.AddServiceMock(environment); + var configuredDirectory = vendorSetting == "relative" ? Path.GetRelativePath(ownerDirectory, vendorDirectory) : vendorDirectory; + var manifest = System.Text.Json.JsonSerializer.Serialize(new { config = new Dictionary { ["vendor-dir"] = configuredDirectory } }); + if (inventory == "installed") + { + var installedLocation = Path.Combine(vendorDirectory, "composer", "installed.json"); + var files = new Mock(); + files.Setup(value => value.Exists(installedLocation)).Returns(true); + files.Setup(value => value.MakeFileStream(installedLocation)).Returns(() => """{"packages":[{"name":"acme/lib","version":"1.0"}]}""".ToStream()); + this.DetectorTestUtility.AddServiceMock(files); + } + + if (ownerFirst) + { + this.DetectorTestUtility.WithFile("composer.json", manifest, fileLocation: ownerLocation); + } + + this.DetectorTestUtility.WithFile("composer.json", """{"require":{"acme/uninstalled":"9.0"}}""", fileLocation: vendorLocation); + this.DetectorTestUtility.WithFile("composer.json", """{"require":{"acme/uninstalled":"9.0"}}""", fileLocation: Path.Combine(vendorDirectory, "acme", "other", "composer.json")); + if (!ownerFirst) + { + this.DetectorTestUtility.WithFile("composer.json", manifest, fileLocation: ownerLocation); + } + + if (inventory == "lock") + { + this.DetectorTestUtility.WithFile("composer.lock", """{"packages":[{"name":"acme/lib","version":"1.0"}]}""", fileLocation: Path.Combine(ownerDirectory, "composer.lock")); + } + + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", "{}", fileLocation: independentLocation).ExecuteDetectorAsync(); + + var expectedPackage = inventory == "missing" ? "acme/uninstalled 9.0 - Composer" : "acme/lib 1.0 - Composer"; + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo(["php 8.4.27 - PhpSdk", expectedPackage]); + recorder.GetSkippedComponents().Should().BeEmpty(); + if (inventory != "missing") + { + recorder.GetDependencyGraphsByLocation().Keys.Should().NotContain(vendorLocation); + } + + foreach (var directory in new[] { ownerDirectory, Path.GetDirectoryName(independentLocation) }) + { + var argument = $"--working-dir=\"{directory}\""; + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.Is(arguments => arguments.Contains(argument))), Times.Once()); + } + + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny()), Times.Exactly(2)); + this.VerifyWarning("vendor directory ownership contains a cycle", Times.Never()); + } + + [TestMethod] + public async Task ExternalVendorOwnershipChain_ProcessesEachOwnerBeforeItsVendorInputsAsync() + { + this.WithOutput("""{"platform":[{"name":"php","version":"8.4.27"}]}"""); + var root = Path.Combine(Path.GetTempPath(), "composer-chain"); + var ownerDirectory = Path.Combine(root, "applications", "long-application"); + var nestedDirectory = Path.Combine(root, "v", "lib"); + var externalDirectory = Path.Combine(root, "w", "lib"); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"require":{"acme/uninstalled":"9.0"}}""", fileLocation: Path.Combine(externalDirectory, "composer.json")) + .WithFile("composer.lock", """{"packages":[{"name":"acme/locked","version":"1.0"}]}""", fileLocation: Path.Combine(nestedDirectory, "composer.lock")) + .WithFile("composer.json", """{"config":{"vendor-dir":"../../w"}}""", fileLocation: Path.Combine(nestedDirectory, "composer.json")) + .WithFile("composer.json", """{"config":{"vendor-dir":"../../v"}}""", fileLocation: Path.Combine(ownerDirectory, "composer.json")) + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo(["php 8.4.27 - PhpSdk", "acme/locked 1.0 - Composer"]); + recorder.GetDependencyGraphsByLocation().Keys.Should().NotContain(Path.Combine(externalDirectory, "composer.json")); + recorder.GetSkippedComponents().Should().BeEmpty(); + var argument = $"--working-dir=\"{ownerDirectory}\""; + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.Is(arguments => arguments.Contains(argument))), Times.Once()); + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny()), Times.Once()); + } + + [TestMethod] + [DataRow("{")] + [DataRow("[]")] + [DataRow("null")] + public async Task CoveredExternalVendorManifest_DoesNotReportPreparationParseFailuresAsync(string manifest) + { + this.WithOutput("""{"platform":[]}"""); + var root = Path.Combine(Path.GetTempPath(), "composer-malformed-vendor"); + var vendorLocation = Path.Combine(root, "v", "lib", "composer.json"); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", manifest, fileLocation: vendorLocation) + .WithFile("composer.json", """{"config":{"vendor-dir":"../../v"}}""", fileLocation: Path.Combine(root, "applications", "long-application", "composer.json")) + .WithFile("composer.lock", """{"packages":[{"name":"acme/locked","version":"1.0"}]}""", fileLocation: Path.Combine(root, "applications", "long-application", "composer.lock")) + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("acme/locked 1.0 - Composer"); + recorder.GetSkippedComponents().Should().BeEmpty(); + recorder.GetDependencyGraphsByLocation().Keys.Should().NotContain(vendorLocation); + } + + [TestMethod] + public async Task SharedVendorDirectory_ProcessesAllOwnersBeforeVendorInputsAsync() + { + this.WithOutput("""{"platform":[]}"""); + var root = Path.Combine(Path.GetTempPath(), "composer-shared-vendor"); + var vendorDirectory = Path.Combine(root, "v"); + var firstLocation = Path.Combine(root, "first", "composer.lock"); + var secondLocation = Path.Combine(root, "second", "composer.lock"); + var vendorLocation = Path.Combine(vendorDirectory, "acme", "lib", "composer.json"); + var environment = new Mock(); + environment.Setup(value => value.GetEnvironmentVariable("COMPOSER_VENDOR_DIR")).Returns(vendorDirectory); + var (result, recorder) = await this.DetectorTestUtility.AddServiceMock(environment) + .WithFile("composer.json", """{"require":{"acme/uninstalled":"9.0"}}""", fileLocation: vendorLocation) + .WithFile("composer.lock", """{"packages":[{"name":"acme/first","version":"1.0"}]}""", fileLocation: firstLocation) + .WithFile("composer.lock", """{"packages":[{"name":"acme/second","version":"2.0"}]}""", fileLocation: secondLocation) + .ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should() + .BeEquivalentTo(["acme/first 1.0 - Composer", "acme/second 2.0 - Composer"]); + recorder.GetDependencyGraphsByLocation().Keys.Should().BeEquivalentTo([firstLocation, secondLocation]); + recorder.GetSkippedComponents().Should().BeEmpty(); + foreach (var location in new[] { firstLocation, secondLocation }) + { + var argument = $"--working-dir=\"{Path.GetDirectoryName(location)}\""; + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.Is(arguments => arguments.Contains(argument))), Times.Once()); + } + + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny()), Times.Exactly(2)); + this.VerifyWarning("vendor directory ownership contains a cycle", Times.Never()); + } + + [TestMethod] + public async Task ProjectAsItsOwnVendorDirectory_DoesNotCreateOwnershipCycleAsync() + { + var root = Path.Combine(Path.GetTempPath(), "composer-self-vendor"); + var location = Path.Combine(root, "composer.lock"); + var (result, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"config":{"vendor-dir":"."}}""", fileLocation: Path.Combine(root, "composer.json")) + .WithFile("composer.lock", """{"packages":[{"name":"acme/locked","version":"1.0"}]}""", fileLocation: location) + .ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("acme/locked 1.0 - Composer"); + recorder.GetDependencyGraphsByLocation().Keys.Should().Equal(location); + recorder.GetSkippedComponents().Should().BeEmpty(); + this.VerifyWarning("vendor directory ownership contains a cycle", Times.Never()); + this.commands.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task CyclicVendorOwnership_WarnsAndPreservesManifestFallbackWithoutPlatformQueriesAsync() + { + var root = Path.Combine(Path.GetTempPath(), "composer-cycle"); + var (_, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", """{"config":{"vendor-dir":"../b"},"require":{"acme/first":"1.0"}}""", fileLocation: Path.Combine(root, "a", "composer.json")) + .WithFile("composer.json", """{"config":{"vendor-dir":"../a"},"require":{"acme/second":"2.0"}}""", fileLocation: Path.Combine(root, "b", "composer.json")) + .ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo(["acme/first 1.0 - Composer", "acme/second 2.0 - Composer"]); + recorder.GetSkippedComponents().Should().BeEmpty(); + this.VerifyWarning("vendor directory ownership contains a cycle", Times.Once()); + this.commands.VerifyNoOtherCalls(); + } + [TestMethod] [DataRow("vendor")] [DataRow("VeNdOr")] @@ -295,7 +482,7 @@ public async Task InvalidEntries_WarnAndRetainValidEnvironmentComponentsAsync() [TestMethod] public async Task MissingComposer_WarnsForEachNonVendorProjectAsync() { - this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) + this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny())) .ThrowsAsync(new Win32Exception(2)); var (_, recorder) = await this.DetectorTestUtility .WithFile("composer.json", """{"require":{"vendor/a":"1.0"}}""") @@ -304,7 +491,50 @@ public async Task MissingComposer_WarnsForEachNonVendorProjectAsync() recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo(["vendor/a 1.0 - Composer", "vendor/b 2.0 - Composer"]); this.VerifyWarning("Unable to run Composer platform inventory", Times.Exactly(2)); - this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); + this.commands.Verify(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny()), Times.Exactly(2)); + } + + [TestMethod] + public async Task ProjectPathWithSpaces_IsPassedAsAnOptionWithoutChangingProcessDirectoryAsync() + { + this.WithOutput("""{"platform":[]}"""); + var projectDirectory = Path.Combine(Path.GetTempPath(), "project with spaces & symbols"); + var argument = $"--working-dir=\"{projectDirectory}\""; + + await this.DetectorTestUtility.WithFile("composer.lock", "{}", fileLocation: Path.Combine(projectDirectory, "composer.lock")).ExecuteDetectorAsync(); + + this.commands.Verify( + value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.Is(arguments => arguments.Contains(argument))), + Times.Once()); + } + + [TestMethod] + public async Task FilesystemRoot_IsPassedWithoutEscapingTheClosingQuoteAsync() + { + this.WithOutput("""{"platform":[]}"""); + var root = Path.GetPathRoot(Path.GetTempPath()); + var argument = $"--working-dir=\"{root}.\""; + + await this.DetectorTestUtility.WithFile("composer.lock", "{}", fileLocation: Path.Combine(root, "composer.lock")).ExecuteDetectorAsync(); + + this.commands.Verify( + value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.Is(arguments => arguments.Contains(argument))), + Times.Once()); + } + + [TestMethod] + [DataRow("project%PATH%")] + [DataRow("project!PATH!")] + [OSCondition(OperatingSystems.Windows)] + public async Task ShellExpandedProjectPaths_WarnWithoutRunningInventoryAsync(string directory) + { + var location = Path.Combine(Path.GetTempPath(), directory, "composer.lock"); + var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.lock", """{"packages":[{"name":"vendor/app","version":"1"}]}""", fileLocation: location).ExecuteDetectorAsync(); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("vendor/app 1 - Composer"); + this.VerifyWarning("cannot safely pass project directory", Times.Once()); + this.commands.Verify(value => value.IsCommandLineExecution(), Times.Once()); + this.commands.VerifyNoOtherCalls(); } [TestMethod] @@ -320,7 +550,7 @@ public async Task NonzeroExit_WarnsWithoutReportingPartialOutputAsync() [TestMethod] public async Task HungCommand_TimesOutWithoutFailingPackageDetectionAsync() { - this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) + this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny())) .Returns(async (string _, IEnumerable _, DirectoryInfo _, CancellationToken token, string[] _) => { await Task.Delay(Timeout.Infinite, token); @@ -339,7 +569,7 @@ public async Task HungCommand_TimesOutWithoutFailingPackageDetectionAsync() public async Task CallerCancellation_IsNotSwallowedAsAnInventoryTimeoutAsync() { using var cancellation = new CancellationTokenSource(); - this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) + this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny())) .Returns(async (string _, IEnumerable _, DirectoryInfo _, CancellationToken token, string[] _) => { await cancellation.CancelAsync(); @@ -352,7 +582,7 @@ public async Task CallerCancellation_IsNotSwallowedAsAnInventoryTimeoutAsync() } private void WithOutput(string output, int exitCode = 0) => - this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) + this.commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny())) .ReturnsAsync(new CommandLineExecutionResult { StdOut = output, StdErr = "test error", ExitCode = exitCode }); private void VerifyWarning(string message, Times times) => diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/ComposerProcessingTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/ComposerProcessingTests.cs index de292e689..2607f6901 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/ComposerProcessingTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/ComposerProcessingTests.cs @@ -71,12 +71,13 @@ public async Task ExperimentalComposer_AlwaysExecutesButOnlyIncludesResultsWhenE var experiments = new Mock(); var processor = new DetectorProcessingService(walker.Object, experiments.Object, NullLogger.Instance, Mock.Of()); var commands = new Mock(); + var rootArgument = $"--working-dir=\"{Path.GetDirectoryName(location)}\""; commands.Setup(value => value.IsCommandLineExecution()).Returns(platform); - commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())) - .ReturnsAsync((string _, IEnumerable _, DirectoryInfo directory, CancellationToken _, string[] _) => new CommandLineExecutionResult + commands.Setup(value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.IsAny())) + .ReturnsAsync((string _, IEnumerable _, DirectoryInfo _, CancellationToken _, string[] arguments) => new CommandLineExecutionResult { ExitCode = 0, - StdOut = directory.FullName == Path.GetDirectoryName(location) + StdOut = arguments.Contains(rootArgument) ? """{"platform":[{"name":"php","version":"8.4.27","direct-dependency":true},{"name":"ext-json","version":"8.4.27","direct-dependency":false}]}""" : """{"platform":[{"name":"php","version":"8.3.15","direct-dependency":false},{"name":"ext-json","version":"8.4.27","direct-dependency":true}]}""", }); @@ -124,8 +125,9 @@ public async Task ExperimentalComposer_AlwaysExecutesButOnlyIncludesResultsWhenE Times.Exactly(2)); foreach (var projectDirectory in new[] { Path.GetDirectoryName(location), Path.GetDirectoryName(childLocation) }) { + var argument = $"--working-dir=\"{projectDirectory}\""; commands.Verify( - value => value.ExecuteCommandAsync("composer", It.IsAny>(), It.Is(directory => directory.FullName == projectDirectory), It.IsAny(), It.IsAny()), + value => value.ExecuteCommandAsync("composer", It.IsAny>(), null, It.IsAny(), It.Is(arguments => arguments.Contains(argument))), platform ? Times.Exactly(2) : Times.Never()); } } From 671cab5e7d03a52f72a58991a7deb1e0a855f3ec Mon Sep 17 00:00:00 2001 From: Greg Villicana Date: Wed, 11 Nov 2026 14:23:55 -0800 Subject: [PATCH 3/5] PR review --- .../composer/ComposerComponentDetector.cs | 12 +++++-- .../ComposerDetectorTests.cs | 35 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs index aa54a9838..24135b3e8 100644 --- a/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs @@ -542,8 +542,16 @@ private async Task ReadInstalledPackagesAsync(string vendorDirectory, Dict private async Task PrepareProjectAsync(string location, IComponentStream? manifest, CancellationToken cancellationToken) { var directory = new DirectoryInfo(Path.GetDirectoryName(location)!); - manifest ??= this.ComponentStreamEnumerableFactory.GetComponentStreams( - directory, [ComposerManifestFileName], null, recursivelyScanDirectories: false).FirstOrDefault(); + + // The factory owns its streams, so keep the enumerator alive until the manifest has been parsed and cloned. + using var manifests = manifest is null + ? this.ComponentStreamEnumerableFactory.GetComponentStreams(directory, [ComposerManifestFileName], null, recursivelyScanDirectories: false).GetEnumerator() + : null; + if (manifests?.MoveNext() == true) + { + manifest = manifests.Current; + } + JsonElement? root = null; JsonException? error = null; if (manifest is not null) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs index c71fdf92a..3ba939454 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs @@ -80,6 +80,41 @@ public async Task Lockfile_ReadsSiblingManifestForDirectRootsWithoutAdditionalLo files.VerifyNoOtherCalls(); } + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task Lockfile_SiblingManifestStreamRemainsOpenDuringPreparationAndIsDisposedAfterwardAsync(bool malformed) + { + using var manifestStream = new MemoryStream(Encoding.UTF8.GetBytes(malformed ? "{" : """{"require":{"vendor/child":"^2"}}""")); + var factory = new Mock(); + factory.Setup(value => value.GetComponentStreams(It.IsAny(), It.IsAny>(), It.IsAny(), false)) + .Returns(GetManifestStreams); + + var (result, recorder) = await this.DetectorTestUtility.AddServiceMock(factory) + .WithFile("composer.lock", """{"packages":[{"name":"vendor/app","version":"1.2.3","require":{"vendor/child":"^2"}},{"name":"vendor/child","version":"2.1.0"}]}""") + .ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + manifestStream.CanRead.Should().BeFalse(); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should() + .BeEquivalentTo([Id("vendor/app", "1.2.3"), Id("vendor/child", "2.1.0")]); + var graph = recorder.GetDependencyGraphsByLocation().Values.Single(); + graph.GetAllExplicitlyReferencedComponents().Should().Equal(malformed ? Id("vendor/app", "1.2.3") : Id("vendor/child", "2.1.0")); + graph.GetDependenciesForComponent(Id("vendor/app", "1.2.3")).Should().Equal(Id("vendor/child", "2.1.0")); + recorder.GetSkippedComponents().Should().HaveCount(malformed ? 1 : 0); + + IEnumerable GetManifestStreams() + { + using (manifestStream) + { + var file = new Mock(); + file.SetupGet(value => value.Location).Returns(Path.Combine(Path.GetTempPath(), "composer.json")); + file.SetupGet(value => value.Stream).Returns(manifestStream); + yield return file.Object; + } + } + } + [TestMethod] [DataRow("{/* Installed inventory */\"packages\":[{\"name\":\"vendor/package\",\"version\":\"v1.2.3\",},],}")] [DataRow("[/* Legacy installed inventory */{\"name\":\"vendor/package\",\"version\":\"v1.2.3\",},]")] From e4545cb967bcc6b6cd79a9274e227b9b94276017 Mon Sep 17 00:00:00 2001 From: Greg Villicana Date: Wed, 11 Nov 2026 17:09:28 -0800 Subject: [PATCH 4/5] Parser refactoring --- .../FileComponentDetector.cs | 6 +- .../TypedComponent/ComposerComponent.cs | 6 + .../composer/ComposerComponentDetector.cs | 713 +----------------- .../composer/Contracts/ComposerAlias.cs | 15 + .../composer/Contracts/ComposerConfig.cs | 9 + .../composer/Contracts/ComposerExtra.cs | 10 + .../Contracts/ComposerInstalledPackages.cs | 13 + .../composer/Contracts/ComposerLockFile.cs | 16 + .../composer/Contracts/ComposerManifest.cs | 13 + .../composer/Contracts/ComposerPackage.cs | 25 + .../Contracts/ComposerPlatformInventory.cs | 10 + .../Contracts/ComposerPlatformPackage.cs | 18 + .../Parsers/ComposerManifestParser.cs | 200 +++++ .../composer/Parsers/ComposerPackageParser.cs | 395 ++++++++++ .../Parsers/ComposerPlatformParser.cs | 58 ++ .../ComposerComponentTests.cs | 19 + .../ComposerDetectorTests.cs | 160 +++- .../ComposerJsonSerializerTests.cs | 148 ++++ .../ComposerPlatformTests.cs | 37 +- 19 files changed, 1151 insertions(+), 720 deletions(-) create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerAlias.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerConfig.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerExtra.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerInstalledPackages.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerLockFile.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerManifest.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPackage.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPlatformInventory.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPlatformPackage.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerManifestParser.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerPackageParser.cs create mode 100644 src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerPlatformParser.cs create mode 100644 test/Microsoft.ComponentDetection.Detectors.Tests/ComposerJsonSerializerTests.cs diff --git a/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs b/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs index ecf060350..9bee3a262 100644 --- a/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs @@ -19,11 +19,11 @@ namespace Microsoft.ComponentDetection.Contracts; public abstract class FileComponentDetector : IComponentDetector { /// - /// Gets opt-in JSON parsing options that skip comments and allow trailing commas. + /// Gets opt-in JSON deserialization options that skip comments and allow trailing commas. /// - protected static readonly JsonDocumentOptions LenientJsonDocumentOptions = new() + protected static readonly JsonSerializerOptions LenientJsonSerializerOptions = new() { - CommentHandling = JsonCommentHandling.Skip, + ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, }; diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComposerComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComposerComponent.cs index 9960959d6..648751f42 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComposerComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComposerComponent.cs @@ -1,6 +1,7 @@ #nullable disable namespace Microsoft.ComponentDetection.Contracts.TypedComponent; +using System; using System.Text.Json.Serialization; using PackageUrl; @@ -33,6 +34,11 @@ public override PackageURL PackageUrl get { var separator = this.Name.IndexOf('/'); + if (separator <= 0 || separator == this.Name.Length - 1 || separator != this.Name.LastIndexOf('/')) + { + throw new InvalidOperationException("Composer package names must contain exactly one '/' separating a nonempty vendor and package name."); + } + return new PackageURL("composer", this.Name.Substring(0, separator), this.Name.Substring(separator + 1), this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs index 24135b3e8..e84897a74 100644 --- a/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/composer/ComposerComponentDetector.cs @@ -3,7 +3,6 @@ namespace Microsoft.ComponentDetection.Detectors.Composer; using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reactive.Linq; @@ -13,6 +12,8 @@ namespace Microsoft.ComponentDetection.Detectors.Composer; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.Internal; using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.ComponentDetection.Detectors.Composer.Contracts; +using Microsoft.ComponentDetection.Detectors.Composer.Parsers; using Microsoft.Extensions.Logging; /// Reads Composer package files and optionally inventories the local PHP environment through Composer. @@ -23,23 +24,12 @@ public sealed class ComposerComponentDetector : FileComponentDetector, IExperime private const string InstalledPackagesFileName = "installed.json"; private const string ComposerName = "composer"; private const string DefaultVendorDirectoryName = "vendor"; - private const string PackagesPropertyName = "packages"; - private const string DevPackageNamesPropertyName = "dev-package-names"; - private const string NamePropertyName = "name"; - private const string VersionPropertyName = "version"; - private const string RequirePropertyName = "require"; - private const string RequireDevPropertyName = "require-dev"; - private const string ProvidePropertyName = "provide"; - private const string ReplacePropertyName = "replace"; - private const string ExtraPropertyName = "extra"; - private const string BranchAliasPropertyName = "branch-alias"; - private const string AliasesPropertyName = "aliases"; - private const string SelfVersionConstraint = "self.version"; private static readonly TimeSpan PlatformInventoryTimeout = TimeSpan.FromSeconds(10); - private readonly IEnvironmentVariableService environmentVariableService; - private readonly IFileUtilityService fileUtilityService; private readonly ICommandLineInvocationService commandLineInvocationService; + private readonly ComposerManifestParser manifestParser; + private readonly ComposerPackageParser packageParser; + private readonly ComposerPlatformParser platformParser; private readonly ConcurrentHashSet coveredVendorDirectories = []; private readonly ConcurrentHashSet knownPlatformVendorDirectories = []; private readonly ConcurrentDictionary preparedProjects = []; @@ -54,10 +44,11 @@ public ComposerComponentDetector( { this.ComponentStreamEnumerableFactory = componentStreamEnumerableFactory; this.Scanner = walkerFactory; - this.environmentVariableService = environmentVariableService; - this.fileUtilityService = fileUtilityService; this.commandLineInvocationService = commandLineInvocationService; this.Logger = logger; + this.manifestParser = new ComposerManifestParser(environmentVariableService, LenientJsonSerializerOptions, logger); + this.packageParser = new ComposerPackageParser(fileUtilityService, this.manifestParser, LenientJsonSerializerOptions, logger); + this.platformParser = new ComposerPlatformParser(LenientJsonSerializerOptions, logger); } public override string Id => "Composer"; @@ -139,8 +130,8 @@ protected override async Task OnFileFoundAsync(ProcessRequest processRequest, ID var recorder = processRequest.SingleFileComponentRecorder; this.Logger.LogDebug("Reading Composer file {Location}", file.Location); var isManifest = Path.GetFileName(file.Location).Equals(ComposerManifestFileName, StringComparison.OrdinalIgnoreCase); - using var document = isManifest ? null : await this.ReadDocumentAsync(file.Stream, file.Location, recorder, cancellationToken); - if (!isManifest && document is null) + var lockFile = isManifest ? null : await this.packageParser.ReadLockFileAsync(file.Stream, file.Location, recorder, cancellationToken); + if (!isManifest && lockFile is null) { return; } @@ -152,11 +143,6 @@ protected override async Task OnFileFoundAsync(ProcessRequest processRequest, ID this.Logger.LogError(project.ManifestError, "Invalid Composer JSON in {Location}", project.ManifestLocation); recorder.RegisterPackageParseFailure(project.ManifestLocation); } - else if (manifestRoot is not null && manifestRoot.Value.ValueKind != JsonValueKind.Object) - { - this.ReportFailure(recorder, project.ManifestLocation, "Expected a JSON object."); - manifestRoot = null; - } if (isManifest && manifestRoot is null) { @@ -166,115 +152,20 @@ protected override async Task OnFileFoundAsync(ProcessRequest processRequest, ID var vendorDirectory = project.VendorDirectory; await this.RegisterPlatformInventoryAsync(file.Location, recorder, cancellationToken); - var packages = new Dictionary(); - if (isManifest) - { - if (!await this.ReadInstalledPackagesAsync(vendorDirectory, packages, recorder, cancellationToken)) - { - this.Logger.LogWarning( - $"Composer manifest {{Location}} without a sibling {ComposerLockFileName} or usable {InstalledPackagesFileName}. Provide either to improve accuracy; otherwise only exact versions are detected.", - file.Location); - this.ReadManifestRequirements(manifestRoot!.Value, recorder, file.Location, cancellationToken); - return; - } - } - else + var packages = isManifest + ? await this.packageParser.ReadInstalledPackagesAsync(vendorDirectory, recorder, cancellationToken) + : this.packageParser.ReadLockFile(lockFile!, recorder, cancellationToken); + if (packages is null) { - this.ReadPackages(document!.RootElement, PackagesPropertyName, false, packages, recorder, cancellationToken); - this.ReadPackages(document.RootElement, "packages-dev", true, packages, recorder, cancellationToken); - this.ReadLockAliases(document.RootElement, packages, recorder, cancellationToken); + this.Logger.LogWarning( + $"Composer manifest {{Location}} without a sibling {ComposerLockFileName} or usable {InstalledPackagesFileName}. Provide either to improve accuracy; otherwise only exact versions are detected.", + file.Location); + this.manifestParser.RegisterRequirements(manifestRoot!, recorder, file.Location, cancellationToken); + return; } this.coveredVendorDirectories.Add(vendorDirectory); - this.RegisterPackages(packages, manifestRoot, recorder, cancellationToken); - } - - private static Dictionary> CreateProviderLookup(Dictionary packages) - { - var providers = new Dictionary>(StringComparer.Ordinal); - foreach (var package in packages.Values) - { - foreach (var (name, constraint) in package.Provides.Concat(package.Replaces)) - { - if (!providers.TryGetValue(name, out var claims)) - { - providers[name] = claims = []; - } - - if (constraint == SelfVersionConstraint) - { - claims.Add((package, package.Component.Version)); - foreach (var alias in package.Aliases) - { - claims.Add((package, alias)); - } - } - else - { - claims.Add((package, constraint)); - } - } - } - - return providers; - } - - private static bool TryGetNonEmptyString(JsonElement entry, string propertyName, [NotNullWhen(true)] out string? value) - { - value = entry.ValueKind == JsonValueKind.Object && entry.TryGetProperty(propertyName, out var property) && property.ValueKind == JsonValueKind.String - ? property.GetString() - : null; - return !string.IsNullOrWhiteSpace(value); - } - - private void RegisterPackages( - Dictionary packages, - JsonElement? manifestRoot, - ISingleFileComponentRecorder recorder, - CancellationToken cancellationToken) - { - // Names and aliases are lookup keys, never additional detected components. - var names = packages.Values.GroupBy(package => package.Component.Name.Trim(), StringComparer.OrdinalIgnoreCase) - .ToDictionary(group => group.Key, group => group.ToList(), StringComparer.OrdinalIgnoreCase); - var providers = CreateProviderLookup(packages); - var rootClaims = manifestRoot is null - ? [] - : this.ReadRootClaims(manifestRoot.Value, recorder); - var roots = manifestRoot is null - ? [] - : this.ReadLinks(manifestRoot.Value, RequirePropertyName, recorder, ComposerManifestFileName) - .Concat(this.ReadLinks(manifestRoot.Value, RequireDevPropertyName, recorder, ComposerManifestFileName)) - .Select(pair => this.Resolve(pair.Key, pair.Value, names, providers, rootClaims)?.Component.Id) - .OfType().ToHashSet(); - - foreach (var package in packages.Values) - { - cancellationToken.ThrowIfCancellationRequested(); - recorder.RegisterUsage(new DetectedComponent(package.Component), isExplicitReferencedDependency: roots.Contains(package.Component.Id), isDevelopmentDependency: package.IsDevelopment); - } - - foreach (var package in packages.Values) - { - foreach (var (name, constraint) in package.Requires) - { - cancellationToken.ThrowIfCancellationRequested(); - var dependency = this.Resolve(name, constraint, names, providers, rootClaims); - if (dependency is not null && dependency.Component.Id != package.Component.Id) - { - recorder.RegisterUsage(new DetectedComponent(dependency.Component), parentComponentId: package.Component.Id, isDevelopmentDependency: dependency.IsDevelopment); - } - } - } - - if (manifestRoot is null) - { - foreach (var root in ComposerGraph.FindRoots(recorder.DependencyGraph, packages.Keys, cancellationToken)) - { - cancellationToken.ThrowIfCancellationRequested(); - var package = packages[root]; - recorder.RegisterUsage(new DetectedComponent(package.Component), isExplicitReferencedDependency: true, isDevelopmentDependency: package.IsDevelopment); - } - } + this.packageParser.RegisterPackages(packages, manifestRoot, recorder, cancellationToken); } private async Task RegisterPlatformInventoryAsync(string location, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) @@ -331,219 +222,14 @@ private async Task RegisterPlatformInventoryAsync(string location, ISingleFileCo return; } - this.RegisterPlatformComponents(result.StdOut, recorder, cancellationToken); - } - - private void RegisterPlatformComponents(string output, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) - { - try - { - using var document = JsonDocument.Parse(output); - if (document.RootElement.ValueKind != JsonValueKind.Object || - !document.RootElement.TryGetProperty("platform", out var entries) || entries.ValueKind != JsonValueKind.Array) - { - this.Logger.LogWarning("Composer platform inventory did not contain a platform array; no environment components will be reported."); - return; - } - - foreach (var entry in entries.EnumerateArray()) - { - cancellationToken.ThrowIfCancellationRequested(); - if (!TryGetNonEmptyString(entry, NamePropertyName, out var packageName) || - !TryGetNonEmptyString(entry, VersionPropertyName, out var version)) - { - this.Logger.LogWarning("Composer platform inventory contained an invalid package identity; the entry is omitted."); - continue; - } - - if (packageName.Contains('/', StringComparison.Ordinal) || - (packageName is not ("php" or "hhvm" or ComposerName) && - !packageName.StartsWith("ext-", StringComparison.Ordinal) && !packageName.StartsWith("lib-", StringComparison.Ordinal))) - { - continue; - } - - if (entry.TryGetProperty("description", out var description) && description.ValueKind == JsonValueKind.String && - description.GetString()!.Contains("via config.platform", StringComparison.Ordinal)) - { - this.Logger.LogDebug("Composer platform entry {Name} is simulated or disabled by config.platform; its configured version is not reported as installed.", packageName); - continue; - } - - var hasDirectDependency = entry.TryGetProperty("direct-dependency", out var directDependency); - if (hasDirectDependency && directDependency.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) - { - this.Logger.LogWarning("Composer platform entry {Name} has invalid direct-dependency metadata; it is not marked explicitly referenced.", packageName); - } - - recorder.RegisterUsage( - new DetectedComponent(new PhpSdkComponent(packageName, version)), - isExplicitReferencedDependency: hasDirectDependency && directDependency.ValueKind == JsonValueKind.True, - isDevelopmentDependency: true); - } - } - catch (JsonException exception) - { - this.Logger.LogWarning(exception, "Composer platform inventory was not valid JSON; no environment components will be reported."); - } - } - - private void MergeLinks(Dictionary target, Dictionary source, HashSet conflicts, string section, ISingleFileComponentRecorder recorder, string location) - { - foreach (var (name, constraint) in source) - { - var key = $"{section}.{name}"; - if (conflicts.Contains(key)) - { - continue; - } - - if (target.TryGetValue(name, out var existing) && existing != constraint) - { - this.ReportFailure(recorder, $"{location}.{key}", "Duplicate locked identity declares conflicting constraints; this dependency declaration is omitted."); - target.Remove(name); - conflicts.Add(key); - } - else - { - target.TryAdd(name, constraint); - } - } - } - - private string GetVendorDirectory(string location, JsonElement? manifest) - { - var projectDirectory = Path.GetDirectoryName(location)!; - var defaultVendorDirectory = Path.Combine(projectDirectory, DefaultVendorDirectoryName); - var vendorDirectory = this.environmentVariableService.GetEnvironmentVariable("COMPOSER_VENDOR_DIR"); - if (string.IsNullOrWhiteSpace(vendorDirectory)) - { - vendorDirectory = DefaultVendorDirectoryName; - if (manifest is not null && manifest.Value.TryGetProperty("config", out var config)) - { - if (config.ValueKind != JsonValueKind.Object) - { - this.Logger.LogWarning("Invalid Composer config at {Location}; using the default vendor directory.", location); - return defaultVendorDirectory; - } - - if (config.TryGetProperty("vendor-dir", out var configuredDirectory)) - { - if (configuredDirectory.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(configuredDirectory.GetString())) - { - this.Logger.LogWarning("Invalid Composer config.vendor-dir at {Location}; using the default vendor directory.", location); - return defaultVendorDirectory; - } - - vendorDirectory = configuredDirectory.GetString()!; - } - } - } - - try - { - return Path.TrimEndingDirectorySeparator(Path.GetFullPath(vendorDirectory, projectDirectory)); - } - catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) - { - this.Logger.LogWarning(exception, "Invalid Composer vendor directory at {Location}; using the default vendor directory.", location); - return defaultVendorDirectory; - } - } - - private async Task ReadInstalledPackagesAsync(string vendorDirectory, Dictionary packages, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) - { - var location = Path.Combine(vendorDirectory, ComposerName, InstalledPackagesFileName); - if (!this.fileUtilityService.Exists(location)) - { - return false; - } - - JsonDocument? inventory; - try - { - using var stream = this.fileUtilityService.MakeFileStream(location); - inventory = await this.ReadDocumentAsync(stream, location, recorder, cancellationToken, allowPackageArray: true); - } - catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) - { - this.Logger.LogWarning(exception, "Unable to read Composer installed inventory at {Location}; falling back to manifest requirements.", location); - recorder.RegisterPackageParseFailure(location); - return false; - } - - using var document = inventory; - if (document is null) - { - return false; - } - - var root = document.RootElement; - if (root.ValueKind == JsonValueKind.Object && (!root.TryGetProperty(PackagesPropertyName, out var entries) || entries.ValueKind != JsonValueKind.Array)) - { - this.ReportFailure(recorder, location, $"Expected an installed package array in {PackagesPropertyName}."); - return false; - } - - this.ReadPackages(root, PackagesPropertyName, false, packages, recorder, cancellationToken); - if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty(DevPackageNamesPropertyName, out var devNames)) - { - return true; - } - - if (devNames.ValueKind != JsonValueKind.Array) - { - this.ReportFailure(recorder, $"{location}.{DevPackageNamesPropertyName}", "Expected an array of development package names."); - return true; - } - - var developmentPackages = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var name in devNames.EnumerateArray()) - { - if (name.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(name.GetString())) - { - this.ReportFailure(recorder, $"{location}.{DevPackageNamesPropertyName}", "Expected a nonempty development package name."); - continue; - } - - developmentPackages.Add(name.GetString()!.Trim()); - } - - foreach (var package in packages.Values) - { - package.IsDevelopment = developmentPackages.Contains(package.Component.Name.Trim()); - } - - return true; - } - - private async Task ReadDocumentAsync(Stream stream, string location, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken, bool allowPackageArray = false) - { - try - { - var document = await JsonDocument.ParseAsync(stream, LenientJsonDocumentOptions, cancellationToken); - if (document.RootElement.ValueKind == JsonValueKind.Object || (allowPackageArray && document.RootElement.ValueKind == JsonValueKind.Array)) - { - return document; - } - - document.Dispose(); - this.ReportFailure(recorder, location, allowPackageArray ? "Expected a JSON object or installed package array." : "Expected a JSON object."); - } - catch (JsonException exception) - { - this.Logger.LogError(exception, "Invalid Composer JSON in {Location}", location); - recorder.RegisterPackageParseFailure(location); - } - - return null; + this.platformParser.RegisterComponents(result.StdOut, recorder, cancellationToken); } private async Task PrepareProjectAsync(string location, IComponentStream? manifest, CancellationToken cancellationToken) { var directory = new DirectoryInfo(Path.GetDirectoryName(location)!); - // The factory owns its streams, so keep the enumerator alive until the manifest has been parsed and cloned. + // The factory owns its streams, so keep the enumerator alive until deserialization finishes. using var manifests = manifest is null ? this.ComponentStreamEnumerableFactory.GetComponentStreams(directory, [ComposerManifestFileName], null, recursivelyScanDirectories: false).GetEnumerator() : null; @@ -552,14 +238,13 @@ private async Task PrepareProjectAsync(string location, ICompon manifest = manifests.Current; } - JsonElement? root = null; + ComposerManifest? root = null; JsonException? error = null; if (manifest is not null) { try { - using var document = await JsonDocument.ParseAsync(manifest.Stream, LenientJsonDocumentOptions, cancellationToken); - root = document.RootElement.Clone(); + root = await this.manifestParser.ReadAsync(manifest.Stream, cancellationToken); } catch (JsonException exception) { @@ -568,7 +253,7 @@ private async Task PrepareProjectAsync(string location, ICompon } } - var vendorDirectory = this.GetVendorDirectory(location, root is { ValueKind: JsonValueKind.Object } ? root : null); + var vendorDirectory = this.manifestParser.GetVendorDirectory(location, root); return new PreparedProject(vendorDirectory, manifest?.Location ?? Path.Combine(directory.FullName, ComposerManifestFileName), root, error); } @@ -641,351 +326,5 @@ private Dictionary> GetVendorOwnersByDirectory(Dict return ownersByVendorDirectory; } - private void ReadPackages(JsonElement root, string section, bool isDevelopment, Dictionary packages, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) - { - var entries = root; - if (root.ValueKind != JsonValueKind.Array && !root.TryGetProperty(section, out entries)) - { - return; - } - - if (entries.ValueKind != JsonValueKind.Array) - { - this.ReportFailure(recorder, section, "Expected a package array."); - return; - } - - var index = 0; - foreach (var entry in entries.EnumerateArray()) - { - cancellationToken.ThrowIfCancellationRequested(); - var location = $"{section}[{index++}]"; - if (!TryGetNonEmptyString(entry, NamePropertyName, out var name) || - !TryGetNonEmptyString(entry, VersionPropertyName, out var version)) - { - this.ReportFailure(recorder, location, "Expected a package with nonempty string name and version."); - continue; - } - - var packageName = name.Trim(); - var separator = packageName.IndexOf('/'); - if (separator <= 0 || separator == packageName.Length - 1) - { - this.ReportFailure(recorder, location, "Expected a nonempty vendor and package name for a Composer package URL."); - continue; - } - - var component = new ComposerComponent(name, version); - var package = new LockedPackage( - component, - isDevelopment, - this.ReadLinks(entry, RequirePropertyName, recorder, location), - this.ReadLinks(entry, ProvidePropertyName, recorder, location), - this.ReadLinks(entry, ReplacePropertyName, recorder, location), - this.ReadBranchAliases(entry, component.Version.Trim(), recorder, location)); - if (packages.TryGetValue(component.Id, out var existing)) - { - // A package needed in production is never development-only, irrespective of entry order. - existing.IsDevelopment &= isDevelopment; - this.MergeLinks(existing.Requires, package.Requires, existing.Conflicts, RequirePropertyName, recorder, location); - this.MergeLinks(existing.Provides, package.Provides, existing.Conflicts, ProvidePropertyName, recorder, location); - this.MergeLinks(existing.Replaces, package.Replaces, existing.Conflicts, ReplacePropertyName, recorder, location); - existing.Aliases.UnionWith(package.Aliases); - } - else - { - packages.Add(component.Id, package); - } - } - } - - private HashSet ReadBranchAliases(JsonElement entry, string version, ISingleFileComponentRecorder recorder, string location) - { - if (!entry.TryGetProperty(ExtraPropertyName, out var extra) || extra.ValueKind != JsonValueKind.Object || - !extra.TryGetProperty(BranchAliasPropertyName, out var aliases)) - { - return []; - } - - var aliasLocation = $"{location}.{ExtraPropertyName}.{BranchAliasPropertyName}"; - if (aliases.ValueKind != JsonValueKind.Object) - { - this.ReportFailure(recorder, aliasLocation, "Expected a branch alias object."); - return []; - } - - if (aliases.TryGetProperty(version, out var alias)) - { - var aliasValue = alias.ValueKind == JsonValueKind.String ? alias.GetString() : null; - if (!string.IsNullOrWhiteSpace(aliasValue)) - { - return [aliasValue.Trim()]; - } - - this.ReportFailure(recorder, $"{aliasLocation}.{version}", "Expected a nonempty branch alias."); - } - - return []; - } - - private void ReadLockAliases(JsonElement root, Dictionary packages, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) - { - if (!root.TryGetProperty(AliasesPropertyName, out var aliases)) - { - return; - } - - if (aliases.ValueKind != JsonValueKind.Array) - { - this.ReportFailure(recorder, AliasesPropertyName, "Expected an alias array."); - return; - } - - var packagesByName = packages.Values.ToLookup(package => package.Component.Name.Trim(), StringComparer.OrdinalIgnoreCase); - var index = 0; - foreach (var entry in aliases.EnumerateArray()) - { - cancellationToken.ThrowIfCancellationRequested(); - var location = $"{AliasesPropertyName}[{index++}]"; - if (!TryGetNonEmptyString(entry, "package", out var name) || - !TryGetNonEmptyString(entry, VersionPropertyName, out var version) || - !TryGetNonEmptyString(entry, "alias", out var alias)) - { - this.ReportFailure(recorder, location, "Expected nonempty string package, version and alias fields."); - continue; - } - - var matching = packagesByName[name.Trim()] - .Where(package => ComposerVersionConstraint.VersionsEqual(package.Component.Version, version)).ToList(); - if (matching.Count == 1) - { - matching[0].Aliases.Add(alias.Trim()); - } - else - { - this.Logger.LogWarning("Composer alias at {Location} does not uniquely identify an installed package.", location); - } - } - } - - [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Composer package lookup names require lowercase.")] - private Dictionary ReadLinks(JsonElement entry, string section, ISingleFileComponentRecorder recorder, string location) - { - var links = new Dictionary(StringComparer.Ordinal); - var conflicts = new HashSet(StringComparer.Ordinal); - if (!entry.TryGetProperty(section, out var value)) - { - return links; - } - - if (value.ValueKind != JsonValueKind.Object) - { - this.ReportFailure(recorder, $"{location}.{section}", "Expected a dependency object."); - return links; - } - - foreach (var property in value.EnumerateObject()) - { - var name = property.Name.Trim().ToLowerInvariant(); - if (property.Value.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(property.Value.GetString())) - { - this.ReportFailure(recorder, $"{location}.{section}.{name}", "Expected a nonempty version constraint."); - continue; - } - - // php, ext-*, lib-* and composer-* platform requirements do not have a vendor namespace. - // Names such as composer/installers and ext-vendor/package are real packages, not platforms. - if (!name.Contains('/', StringComparison.Ordinal)) - { - this.Logger.LogDebug( - "Skipping Composer dependency {Name} at {Location} without a vendor namespace; it may be a platform requirement.", - name, - $"{location}.{section}"); - continue; - } - - if (name.StartsWith('/') || name.EndsWith('/')) - { - this.ReportFailure(recorder, $"{location}.{section}.{name}", "Expected a nonempty vendor and package name for a Composer package URL."); - continue; - } - - var constraint = property.Value.GetString()!.Trim(); - if (conflicts.Contains(name)) - { - continue; - } - - if (links.TryGetValue(name, out var previous) && previous != constraint) - { - this.ReportFailure(recorder, $"{location}.{section}.{name}", "Duplicate dependency name declares conflicting constraints; the declaration is omitted."); - links.Remove(name); - conflicts.Add(name); - } - else - { - links[name] = constraint; - } - } - - return links; - } - - [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Composer package lookup names require lowercase.")] - private void ReadManifestRequirements(JsonElement root, ISingleFileComponentRecorder recorder, string location, CancellationToken cancellationToken) - { - foreach (var (section, isDevelopment) in new[] { (RequirePropertyName, false), (RequireDevPropertyName, true) }) - { - var requirements = this.ReadLinks(root, section, recorder, location); - if (requirements.Count == 0) - { - continue; - } - - foreach (var property in root.GetProperty(section).EnumerateObject()) - { - cancellationToken.ThrowIfCancellationRequested(); - var name = property.Name; - if (!requirements.Remove(name.Trim().ToLowerInvariant(), out var constraint)) - { - continue; - } - - if (!ComposerVersionConstraint.TryGetExactVersion(constraint, out var version)) - { - this.Logger.LogWarning( - $"Composer dependency {{Name}} at {{Location}} has unresolved constraint {{Constraint}}; this declaration is omitted. Provide {ComposerLockFileName}, {InstalledPackagesFileName}, or an exact version to improve accuracy.", - name, - location, - constraint); - continue; - } - - recorder.RegisterUsage( - new DetectedComponent(new ComposerComponent(name, version)), - isExplicitReferencedDependency: true, - isDevelopmentDependency: isDevelopment); - } - } - } - - private Dictionary> ReadRootClaims(JsonElement root, ISingleFileComponentRecorder recorder) - { - var claims = this.ReadLinks(root, ProvidePropertyName, recorder, ComposerManifestFileName) - .Concat(this.ReadLinks(root, ReplacePropertyName, recorder, ComposerManifestFileName)) - .GroupBy(pair => pair.Key).ToDictionary(group => group.Key, group => group.Select(pair => pair.Value).ToList()); - if (claims.Values.Any(constraints => constraints.Contains(SelfVersionConstraint)) && - TryGetNonEmptyString(root, VersionPropertyName, out var version)) - { - var rootVersion = version.Trim(); - var versions = this.ReadBranchAliases(root, rootVersion, recorder, ComposerManifestFileName); - versions.Add(rootVersion); - foreach (var name in claims.Keys.ToList()) - { - claims[name] = claims[name].SelectMany(constraint => constraint == SelfVersionConstraint ? versions : [constraint]).ToList(); - } - } - - // Without a declared root version, self.version cannot be inferred offline from Git. - // Leave it unresolved so Resolve declines to guess an edge to an installed provider. - return claims; - } - - private LockedPackage? Resolve( - string name, - string constraint, - Dictionary> names, - Dictionary> providers, - Dictionary> rootClaims) - { - if (names.TryGetValue(name, out var actual)) - { - if (actual.Count == 1) - { - // Resolved identities are authoritative, including branch aliases and references. - return actual[0]; - } - - this.Logger.LogWarning("Composer dependency {Name} has multiple resolved versions; no edge can be inferred.", name); - return null; - } - - if (rootClaims.TryGetValue(name, out var rootConstraints)) - { - foreach (var rootConstraint in rootConstraints) - { - if (!ComposerVersionConstraint.TryIntersects(constraint, rootConstraint, out var compatible)) - { - this.Logger.LogWarning("Composer root virtual dependency {Name} has an unresolved constraint; no edge can be inferred offline.", name); - return null; - } - - if (compatible) - { - // Root-provided virtual dependencies are not components of the locked package graph. - return null; - } - } - } - - if (!providers.TryGetValue(name, out var claims)) - { - this.Logger.LogWarning("Composer dependency {Name} is not present in the resolved package inventory.", name); - return null; - } - - var candidates = new HashSet(); - foreach (var (package, declaredConstraint) in claims) - { - if (!ComposerVersionConstraint.TryIntersects(constraint, declaredConstraint, out var compatible)) - { - this.Logger.LogWarning("Composer virtual dependency {Name} has an unsupported constraint; provider uniqueness cannot be established.", name); - return null; - } - - if (compatible) - { - candidates.Add(package); - } - } - - if (candidates.Count == 1) - { - return candidates.Single(); - } - - this.Logger.LogWarning("Composer virtual dependency {Name} has {Count} compatible installed providers; no edge can be inferred.", name, candidates.Count); - return null; - } - - private void ReportFailure(ISingleFileComponentRecorder recorder, string location, string reason) - { - this.Logger.LogError("Malformed Composer data at {Location}: {Reason}", location, reason); - recorder.RegisterPackageParseFailure(location); - } - - private sealed record PreparedProject(string VendorDirectory, string ManifestLocation, JsonElement? Manifest, JsonException? ManifestError); - - private sealed class LockedPackage( - ComposerComponent component, - bool isDevelopment, - Dictionary requires, - Dictionary provides, - Dictionary replaces, - HashSet aliases) - { - internal ComposerComponent Component { get; } = component; - - internal bool IsDevelopment { get; set; } = isDevelopment; - - internal Dictionary Requires { get; } = requires; - - internal Dictionary Provides { get; } = provides; - - internal Dictionary Replaces { get; } = replaces; - - internal HashSet Aliases { get; } = aliases; - - internal HashSet Conflicts { get; } = []; - } + private sealed record PreparedProject(string VendorDirectory, string ManifestLocation, ComposerManifest? Manifest, JsonException? ManifestError); } diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerAlias.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerAlias.cs new file mode 100644 index 000000000..b123917ed --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerAlias.cs @@ -0,0 +1,15 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Contracts; + +using System.Text.Json.Serialization; + +internal class ComposerAlias +{ + [JsonPropertyName("package")] + public string? Package { get; set; } + + [JsonPropertyName("version")] + public string? Version { get; set; } + + [JsonPropertyName("alias")] + public string? Alias { get; set; } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerConfig.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerConfig.cs new file mode 100644 index 000000000..ae67145ce --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerConfig.cs @@ -0,0 +1,9 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Contracts; + +using System.Text.Json.Serialization; + +internal class ComposerConfig +{ + [JsonPropertyName("vendor-dir")] + public string? VendorDirectory { get; set; } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerExtra.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerExtra.cs new file mode 100644 index 000000000..d478aadbc --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerExtra.cs @@ -0,0 +1,10 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Contracts; + +using System.Collections.Generic; +using System.Text.Json.Serialization; + +internal class ComposerExtra +{ + [JsonPropertyName("branch-alias")] + public Dictionary? BranchAliases { get; set; } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerInstalledPackages.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerInstalledPackages.cs new file mode 100644 index 000000000..19a8d5933 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerInstalledPackages.cs @@ -0,0 +1,13 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Contracts; + +using System.Collections.Generic; +using System.Text.Json.Serialization; + +internal class ComposerInstalledPackages +{ + [JsonPropertyName("packages")] + public IReadOnlyList? Packages { get; set; } + + [JsonPropertyName("dev-package-names")] + public IEnumerable? DevelopmentPackageNames { get; set; } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerLockFile.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerLockFile.cs new file mode 100644 index 000000000..21b116634 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerLockFile.cs @@ -0,0 +1,16 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Contracts; + +using System.Collections.Generic; +using System.Text.Json.Serialization; + +internal class ComposerLockFile +{ + [JsonPropertyName("packages")] + public IReadOnlyList? Packages { get; set; } + + [JsonPropertyName("packages-dev")] + public IReadOnlyList? DevelopmentPackages { get; set; } + + [JsonPropertyName("aliases")] + public IReadOnlyList? Aliases { get; set; } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerManifest.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerManifest.cs new file mode 100644 index 000000000..9ddbe4a54 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerManifest.cs @@ -0,0 +1,13 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Contracts; + +using System.Collections.Generic; +using System.Text.Json.Serialization; + +internal class ComposerManifest : ComposerPackage +{ + [JsonPropertyName("require-dev")] + public Dictionary? DevelopmentRequirements { get; set; } + + [JsonPropertyName("config")] + public ComposerConfig? Config { get; set; } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPackage.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPackage.cs new file mode 100644 index 000000000..533b5bfa2 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPackage.cs @@ -0,0 +1,25 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Contracts; + +using System.Collections.Generic; +using System.Text.Json.Serialization; + +internal class ComposerPackage +{ + [JsonPropertyName("name")] + public string? Name { get; set; } + + [JsonPropertyName("version")] + public string? Version { get; set; } + + [JsonPropertyName("require")] + public Dictionary? Require { get; set; } + + [JsonPropertyName("provide")] + public Dictionary? Provide { get; set; } + + [JsonPropertyName("replace")] + public Dictionary? Replace { get; set; } + + [JsonPropertyName("extra")] + public ComposerExtra? Extra { get; set; } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPlatformInventory.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPlatformInventory.cs new file mode 100644 index 000000000..9cc37b834 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPlatformInventory.cs @@ -0,0 +1,10 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Contracts; + +using System.Collections.Generic; +using System.Text.Json.Serialization; + +internal class ComposerPlatformInventory +{ + [JsonPropertyName("platform")] + public IEnumerable? Packages { get; set; } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPlatformPackage.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPlatformPackage.cs new file mode 100644 index 000000000..2f18c9a86 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Contracts/ComposerPlatformPackage.cs @@ -0,0 +1,18 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Contracts; + +using System.Text.Json.Serialization; + +internal class ComposerPlatformPackage +{ + [JsonPropertyName("name")] + public string? Name { get; set; } + + [JsonPropertyName("version")] + public string? Version { get; set; } + + [JsonPropertyName("description")] + public string? Description { get; set; } + + [JsonPropertyName("direct-dependency")] + public bool? DirectDependency { get; set; } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerManifestParser.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerManifestParser.cs new file mode 100644 index 000000000..7fedebc23 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerManifestParser.cs @@ -0,0 +1,200 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Parsers; + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.ComponentDetection.Contracts; +using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.ComponentDetection.Detectors.Composer.Contracts; +using Microsoft.Extensions.Logging; + +internal class ComposerManifestParser( + IEnvironmentVariableService environmentVariableService, + JsonSerializerOptions serializerOptions, + ILogger logger) +{ + internal async Task ReadAsync(Stream stream, CancellationToken cancellationToken) => + await JsonSerializer.DeserializeAsync(stream, serializerOptions, cancellationToken) + ?? throw new JsonException("Expected a JSON object."); + + internal string GetVendorDirectory(string location, ComposerManifest? manifest) + { + var projectDirectory = Path.GetDirectoryName(location)!; + var defaultVendorDirectory = Path.Combine(projectDirectory, "vendor"); + var vendorDirectory = environmentVariableService.GetEnvironmentVariable("COMPOSER_VENDOR_DIR"); + if (string.IsNullOrWhiteSpace(vendorDirectory)) + { + vendorDirectory = "vendor"; + var configuredDirectory = manifest?.Config?.VendorDirectory; + if (configuredDirectory is not null) + { + if (string.IsNullOrWhiteSpace(configuredDirectory)) + { + logger.LogWarning("Invalid Composer config.vendor-dir at {Location}; using the default vendor directory.", location); + return defaultVendorDirectory; + } + + vendorDirectory = configuredDirectory; + } + } + + try + { + return Path.TrimEndingDirectorySeparator(Path.GetFullPath(vendorDirectory, projectDirectory)); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) + { + logger.LogWarning(exception, "Invalid Composer vendor directory at {Location}; using the default vendor directory.", location); + return defaultVendorDirectory; + } + } + + [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Composer package lookup names require lowercase.")] + internal void RegisterRequirements(ComposerManifest root, ISingleFileComponentRecorder recorder, string location, CancellationToken cancellationToken) + { + foreach (var (declarations, section, isDevelopment) in new[] { (root.Require, "require", false), (root.DevelopmentRequirements, "require-dev", true) }) + { + var requirements = this.ReadLinks(declarations, section, recorder, location); + if (requirements.Count == 0) + { + continue; + } + + foreach (var (name, _) in declarations!) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!requirements.Remove(name.Trim().ToLowerInvariant(), out var constraint)) + { + continue; + } + + if (!ComposerVersionConstraint.TryGetExactVersion(constraint, out var version)) + { + logger.LogWarning( + "Composer dependency {Name} at {Location} has unresolved constraint {Constraint}; this declaration is omitted. Provide composer.lock, installed.json, or an exact version to improve accuracy.", + name, + location, + constraint); + continue; + } + + recorder.RegisterUsage( + new DetectedComponent(new ComposerComponent(name, version)), + isExplicitReferencedDependency: true, + isDevelopmentDependency: isDevelopment); + } + } + } + + internal Dictionary> ReadRootClaims(ComposerManifest root, ISingleFileComponentRecorder recorder) + { + var claims = this.ReadLinks(root.Provide, "provide", recorder, "composer.json") + .Concat(this.ReadLinks(root.Replace, "replace", recorder, "composer.json")) + .GroupBy(pair => pair.Key).ToDictionary(group => group.Key, group => group.Select(pair => pair.Value).ToList()); + if (claims.Values.Any(constraints => constraints.Contains("self.version")) && + !string.IsNullOrWhiteSpace(root.Version)) + { + var rootVersion = root.Version.Trim(); + var versions = this.ReadBranchAliases(root, rootVersion, recorder, "composer.json"); + versions.Add(rootVersion); + foreach (var name in claims.Keys.ToList()) + { + claims[name] = claims[name].SelectMany(constraint => constraint == "self.version" ? versions : [constraint]).ToList(); + } + } + + // Without a declared root version, self.version cannot be inferred offline from Git. + // Leave it unresolved so resolution declines to guess an edge to an installed provider. + return claims; + } + + internal HashSet ReadBranchAliases(ComposerPackage entry, string version, ISingleFileComponentRecorder recorder, string location) + { + var declarations = entry.Extra?.BranchAliases; + if (declarations is null) + { + return []; + } + + var aliasLocation = $"{location}.extra.branch-alias"; + if (declarations.TryGetValue(version, out var aliasValue)) + { + if (!string.IsNullOrWhiteSpace(aliasValue)) + { + return [aliasValue.Trim()]; + } + + this.ReportFailure(recorder, $"{aliasLocation}.{version}", "Expected a nonempty branch alias."); + } + + return []; + } + + [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Composer package lookup names require lowercase.")] + internal Dictionary ReadLinks(Dictionary? declarations, string section, ISingleFileComponentRecorder recorder, string location) + { + var links = new Dictionary(StringComparer.Ordinal); + var conflicts = new HashSet(StringComparer.Ordinal); + if (declarations is null) + { + return links; + } + + foreach (var (rawName, rawConstraint) in declarations) + { + var name = rawName.Trim().ToLowerInvariant(); + if (string.IsNullOrWhiteSpace(rawConstraint)) + { + this.ReportFailure(recorder, $"{location}.{section}.{name}", "Expected a nonempty version constraint."); + continue; + } + + // php, ext-*, lib-* and composer-* platform requirements do not have a vendor namespace. + // Names such as composer/installers and ext-vendor/package are real packages, not platforms. + if (!name.Contains('/', StringComparison.Ordinal)) + { + logger.LogDebug( + "Skipping Composer dependency {Name} at {Location} without a vendor namespace; it may be a platform requirement.", + name, + $"{location}.{section}"); + continue; + } + + if (name.StartsWith('/') || name.EndsWith('/') || name.IndexOf('/') != name.LastIndexOf('/')) + { + this.ReportFailure(recorder, $"{location}.{section}.{name}", "Expected a nonempty vendor and package name for a Composer package URL."); + continue; + } + + var constraint = rawConstraint.Trim(); + if (conflicts.Contains(name)) + { + continue; + } + + if (links.TryGetValue(name, out var previous) && previous != constraint) + { + this.ReportFailure(recorder, $"{location}.{section}.{name}", "Duplicate dependency name declares conflicting constraints; the declaration is omitted."); + links.Remove(name); + conflicts.Add(name); + } + else + { + links[name] = constraint; + } + } + + return links; + } + + internal void ReportFailure(ISingleFileComponentRecorder recorder, string location, string reason) + { + logger.LogError("Malformed Composer data at {Location}: {Reason}", location, reason); + recorder.RegisterPackageParseFailure(location); + } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerPackageParser.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerPackageParser.cs new file mode 100644 index 000000000..f61d23d9b --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerPackageParser.cs @@ -0,0 +1,395 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Parsers; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.ComponentDetection.Contracts; +using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.ComponentDetection.Detectors.Composer.Contracts; +using Microsoft.Extensions.Logging; + +internal class ComposerPackageParser( + IFileUtilityService fileUtilityService, + ComposerManifestParser manifestParser, + JsonSerializerOptions serializerOptions, + ILogger logger) +{ + internal async Task ReadLockFileAsync(Stream stream, string location, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + try + { + var value = await JsonSerializer.DeserializeAsync(stream, serializerOptions, cancellationToken); + if (value is not null) + { + return value; + } + + manifestParser.ReportFailure(recorder, location, "Expected a JSON object."); + } + catch (JsonException exception) + { + logger.LogError(exception, "Invalid Composer JSON in {Location}", location); + recorder.RegisterPackageParseFailure(location); + } + + return null; + } + + internal Dictionary ReadLockFile(ComposerLockFile lockFile, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + var packages = new Dictionary(); + this.ReadPackages(lockFile.Packages, false, packages, recorder, cancellationToken); + this.ReadPackages(lockFile.DevelopmentPackages, true, packages, recorder, cancellationToken); + this.ReadLockAliases(lockFile.Aliases, packages, recorder, cancellationToken); + return packages; + } + + internal async Task?> ReadInstalledPackagesAsync(string vendorDirectory, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + var location = Path.Combine(vendorDirectory, "composer", "installed.json"); + if (!fileUtilityService.Exists(location)) + { + return null; + } + + ComposerInstalledPackages? inventory; + try + { + using var stream = fileUtilityService.MakeFileStream(location); + var root = await JsonSerializer.DeserializeAsync(stream, serializerOptions, cancellationToken); + inventory = root.ValueKind == JsonValueKind.Array + ? new ComposerInstalledPackages { Packages = root.Deserialize>(serializerOptions) } + : root.Deserialize(serializerOptions); + } + catch (JsonException exception) + { + logger.LogError(exception, "Invalid Composer JSON in {Location}", location); + recorder.RegisterPackageParseFailure(location); + return null; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + logger.LogWarning(exception, "Unable to read Composer installed inventory at {Location}; falling back to manifest requirements.", location); + recorder.RegisterPackageParseFailure(location); + return null; + } + + if (inventory is null) + { + manifestParser.ReportFailure(recorder, location, "Expected a JSON object or installed package array."); + return null; + } + + if (inventory.Packages is null) + { + manifestParser.ReportFailure(recorder, location, "Expected an installed package array in packages."); + return null; + } + + var packages = new Dictionary(); + this.ReadPackages(inventory.Packages, false, packages, recorder, cancellationToken); + if (inventory.DevelopmentPackageNames is not { } names) + { + return packages; + } + + var developmentPackages = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var name in names) + { + if (string.IsNullOrWhiteSpace(name)) + { + manifestParser.ReportFailure(recorder, $"{location}.dev-package-names", "Expected a nonempty development package name."); + continue; + } + + developmentPackages.Add(name.Trim()); + } + + foreach (var package in packages.Values) + { + package.IsDevelopment = developmentPackages.Contains(package.Component.Name.Trim()); + } + + return packages; + } + + internal void RegisterPackages( + Dictionary packages, + ComposerManifest? manifestRoot, + ISingleFileComponentRecorder recorder, + CancellationToken cancellationToken) + { + // Names and aliases are lookup keys, never additional detected components. + var names = packages.Values.GroupBy(package => package.Component.Name.Trim(), StringComparer.OrdinalIgnoreCase) + .ToDictionary(group => group.Key, group => group.ToList(), StringComparer.OrdinalIgnoreCase); + var providers = CreateProviderLookup(packages); + var rootClaims = manifestRoot is null + ? [] + : manifestParser.ReadRootClaims(manifestRoot, recorder); + var roots = manifestRoot is null + ? [] + : manifestParser.ReadLinks(manifestRoot.Require, "require", recorder, "composer.json") + .Concat(manifestParser.ReadLinks(manifestRoot.DevelopmentRequirements, "require-dev", recorder, "composer.json")) + .Select(pair => this.Resolve(pair.Key, pair.Value, names, providers, rootClaims)?.Component.Id) + .OfType().ToHashSet(); + + foreach (var package in packages.Values) + { + cancellationToken.ThrowIfCancellationRequested(); + recorder.RegisterUsage(new DetectedComponent(package.Component), isExplicitReferencedDependency: roots.Contains(package.Component.Id), isDevelopmentDependency: package.IsDevelopment); + } + + foreach (var package in packages.Values) + { + foreach (var (name, constraint) in package.Requires) + { + cancellationToken.ThrowIfCancellationRequested(); + var dependency = this.Resolve(name, constraint, names, providers, rootClaims); + if (dependency is not null && dependency.Component.Id != package.Component.Id) + { + recorder.RegisterUsage(new DetectedComponent(dependency.Component), parentComponentId: package.Component.Id, isDevelopmentDependency: dependency.IsDevelopment); + } + } + } + + if (manifestRoot is null) + { + foreach (var root in ComposerGraph.FindRoots(recorder.DependencyGraph, packages.Keys, cancellationToken)) + { + cancellationToken.ThrowIfCancellationRequested(); + var package = packages[root]; + recorder.RegisterUsage(new DetectedComponent(package.Component), isExplicitReferencedDependency: true, isDevelopmentDependency: package.IsDevelopment); + } + } + } + + private static Dictionary> CreateProviderLookup(Dictionary packages) + { + var providers = new Dictionary>(StringComparer.Ordinal); + foreach (var package in packages.Values) + { + foreach (var (name, constraint) in package.Provides.Concat(package.Replaces)) + { + if (!providers.TryGetValue(name, out var claims)) + { + providers[name] = claims = []; + } + + if (constraint == "self.version") + { + claims.Add((package, package.Component.Version)); + foreach (var alias in package.Aliases) + { + claims.Add((package, alias)); + } + } + else + { + claims.Add((package, constraint)); + } + } + } + + return providers; + } + + private void ReadPackages(IEnumerable? entries, bool isDevelopment, Dictionary packages, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + if (entries is null) + { + return; + } + + var index = 0; + foreach (var entry in entries) + { + cancellationToken.ThrowIfCancellationRequested(); + var location = isDevelopment ? $"packages-dev[{index++}]" : $"packages[{index++}]"; + if (entry is null || string.IsNullOrWhiteSpace(entry.Name) || string.IsNullOrWhiteSpace(entry.Version)) + { + manifestParser.ReportFailure(recorder, location, "Expected a package with nonempty string name and version."); + continue; + } + + var packageName = entry.Name.Trim(); + var separator = packageName.IndexOf('/'); + if (separator <= 0 || separator == packageName.Length - 1 || separator != packageName.LastIndexOf('/')) + { + manifestParser.ReportFailure(recorder, location, "Expected a nonempty vendor and package name for a Composer package URL."); + continue; + } + + var component = new ComposerComponent(entry.Name, entry.Version); + var package = new LockedPackage( + component, + isDevelopment, + manifestParser.ReadLinks(entry.Require, "require", recorder, location), + manifestParser.ReadLinks(entry.Provide, "provide", recorder, location), + manifestParser.ReadLinks(entry.Replace, "replace", recorder, location), + manifestParser.ReadBranchAliases(entry, component.Version.Trim(), recorder, location)); + if (packages.TryGetValue(component.Id, out var existing)) + { + // A package needed in production is never development-only, irrespective of entry order. + existing.IsDevelopment &= isDevelopment; + this.MergeLinks(existing.Requires, package.Requires, existing.Conflicts, "require", recorder, location); + this.MergeLinks(existing.Provides, package.Provides, existing.Conflicts, "provide", recorder, location); + this.MergeLinks(existing.Replaces, package.Replaces, existing.Conflicts, "replace", recorder, location); + existing.Aliases.UnionWith(package.Aliases); + } + else + { + packages.Add(component.Id, package); + } + } + } + + private void ReadLockAliases(IEnumerable? aliases, Dictionary packages, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + if (aliases is null) + { + return; + } + + var packagesByName = packages.Values.ToLookup(package => package.Component.Name.Trim(), StringComparer.OrdinalIgnoreCase); + var index = 0; + foreach (var entry in aliases) + { + cancellationToken.ThrowIfCancellationRequested(); + var location = $"aliases[{index++}]"; + if (entry is null || string.IsNullOrWhiteSpace(entry.Package) || + string.IsNullOrWhiteSpace(entry.Version) || string.IsNullOrWhiteSpace(entry.Alias)) + { + manifestParser.ReportFailure(recorder, location, "Expected nonempty string package, version and alias fields."); + continue; + } + + var matching = packagesByName[entry.Package.Trim()] + .Where(package => ComposerVersionConstraint.VersionsEqual(package.Component.Version, entry.Version)).ToList(); + if (matching.Count == 1) + { + matching[0].Aliases.Add(entry.Alias.Trim()); + } + else + { + logger.LogWarning("Composer alias at {Location} does not uniquely identify an installed package.", location); + } + } + } + + private void MergeLinks(Dictionary target, Dictionary source, HashSet conflicts, string section, ISingleFileComponentRecorder recorder, string location) + { + foreach (var (name, constraint) in source) + { + var key = $"{section}.{name}"; + if (conflicts.Contains(key)) + { + continue; + } + + if (target.TryGetValue(name, out var existing) && existing != constraint) + { + manifestParser.ReportFailure(recorder, $"{location}.{key}", "Duplicate locked identity declares conflicting constraints; this dependency declaration is omitted."); + target.Remove(name); + conflicts.Add(key); + } + else + { + target.TryAdd(name, constraint); + } + } + } + + private LockedPackage? Resolve( + string name, + string constraint, + Dictionary> names, + Dictionary> providers, + Dictionary> rootClaims) + { + if (names.TryGetValue(name, out var actual)) + { + if (actual.Count == 1) + { + // Resolved identities are authoritative, including branch aliases and references. + return actual[0]; + } + + logger.LogWarning("Composer dependency {Name} has multiple resolved versions; no edge can be inferred.", name); + return null; + } + + if (rootClaims.TryGetValue(name, out var rootConstraints)) + { + foreach (var rootConstraint in rootConstraints) + { + if (!ComposerVersionConstraint.TryIntersects(constraint, rootConstraint, out var compatible)) + { + logger.LogWarning("Composer root virtual dependency {Name} has an unresolved constraint; no edge can be inferred offline.", name); + return null; + } + + if (compatible) + { + // Root-provided virtual dependencies are not components of the locked package graph. + return null; + } + } + } + + if (!providers.TryGetValue(name, out var claims)) + { + logger.LogWarning("Composer dependency {Name} is not present in the resolved package inventory.", name); + return null; + } + + var candidates = new HashSet(); + foreach (var (package, declaredConstraint) in claims) + { + if (!ComposerVersionConstraint.TryIntersects(constraint, declaredConstraint, out var compatible)) + { + logger.LogWarning("Composer virtual dependency {Name} has an unsupported constraint; provider uniqueness cannot be established.", name); + return null; + } + + if (compatible) + { + candidates.Add(package); + } + } + + if (candidates.Count == 1) + { + return candidates.Single(); + } + + logger.LogWarning("Composer virtual dependency {Name} has {Count} compatible installed providers; no edge can be inferred.", name, candidates.Count); + return null; + } + + internal sealed class LockedPackage( + ComposerComponent component, + bool isDevelopment, + Dictionary requires, + Dictionary provides, + Dictionary replaces, + HashSet aliases) + { + internal ComposerComponent Component { get; } = component; + + internal bool IsDevelopment { get; set; } = isDevelopment; + + internal Dictionary Requires { get; } = requires; + + internal Dictionary Provides { get; } = provides; + + internal Dictionary Replaces { get; } = replaces; + + internal HashSet Aliases { get; } = aliases; + + internal HashSet Conflicts { get; } = []; + } +} diff --git a/src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerPlatformParser.cs b/src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerPlatformParser.cs new file mode 100644 index 000000000..f9fdf93c1 --- /dev/null +++ b/src/Microsoft.ComponentDetection.Detectors/composer/Parsers/ComposerPlatformParser.cs @@ -0,0 +1,58 @@ +namespace Microsoft.ComponentDetection.Detectors.Composer.Parsers; + +using System; +using System.Text.Json; +using System.Threading; +using Microsoft.ComponentDetection.Contracts; +using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.ComponentDetection.Detectors.Composer.Contracts; +using Microsoft.Extensions.Logging; + +internal class ComposerPlatformParser(JsonSerializerOptions serializerOptions, ILogger logger) +{ + internal void RegisterComponents(string output, ISingleFileComponentRecorder recorder, CancellationToken cancellationToken) + { + try + { + var inventory = JsonSerializer.Deserialize(output, serializerOptions); + if (inventory?.Packages is not { } entries) + { + logger.LogWarning("Composer platform inventory did not contain a platform array; no environment components will be reported."); + return; + } + + foreach (var entry in entries) + { + cancellationToken.ThrowIfCancellationRequested(); + if (entry is null || string.IsNullOrWhiteSpace(entry.Name) || string.IsNullOrWhiteSpace(entry.Version)) + { + logger.LogWarning("Composer platform inventory contained an invalid package identity; the entry is omitted."); + continue; + } + + var packageName = entry.Name; + if (packageName.Contains('/', StringComparison.Ordinal) || + (packageName is not ("php" or "hhvm" or "composer") && + !packageName.StartsWith("ext-", StringComparison.Ordinal) && !packageName.StartsWith("lib-", StringComparison.Ordinal))) + { + continue; + } + + if (entry.Description?.Contains("via config.platform", StringComparison.Ordinal) == true) + { + logger.LogDebug("Composer platform entry {Name} is simulated or disabled by config.platform; its configured version is not reported as installed.", packageName); + continue; + } + + recorder.RegisterUsage( + new DetectedComponent(new PhpSdkComponent(packageName, entry.Version)), + isExplicitReferencedDependency: entry.DirectDependency == true, + isDevelopmentDependency: true); + } + } + catch (JsonException exception) + { + logger.LogWarning(exception, "Composer platform inventory was not valid JSON; no environment components will be reported."); + } + } +} diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/ComposerComponentTests.cs b/test/Microsoft.ComponentDetection.Contracts.Tests/ComposerComponentTests.cs index 5be463e3b..72c937616 100644 --- a/test/Microsoft.ComponentDetection.Contracts.Tests/ComposerComponentTests.cs +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/ComposerComponentTests.cs @@ -79,6 +79,25 @@ public void Name_IsPreservedInComponentAndBaseId(string name, string expected) component.PackageUrl.ToString().Should().Be($"pkg:composer/{expected}@v1.2.3"); } + [TestMethod] + [DataRow("package")] + [DataRow("/package")] + [DataRow("vendor/")] + [DataRow("vendor/other/package")] + [DataRow("vendor//package")] + [DataRow("vendor///package")] + public void PackageUrl_RejectsMissingOrRepeatedNameSeparators(string name) + { + var component = new ComposerComponent(name, "1.0"); + + component.Name.Should().Be(name); + component.BaseId.Should().Be($"{name} 1.0 - Composer"); + Action action = () => _ = component.PackageUrl; + + action.Should().Throw() + .WithMessage("Composer package names must contain exactly one '/' separating a nonempty vendor and package name."); + } + [TestMethod] public void DifferentRawIdentities_AreNotNormalizedToTheSameBaseId() { diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs index 3ba939454..7741434b3 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerDetectorTests.cs @@ -277,6 +277,21 @@ public async Task MalformedInstalledInventory_ReportsFailureAndFallsBackToExactD recorder.GetSkippedComponents().Should().ContainSingle(); } + [TestMethod] + [DataRow("vendor//package")] + [DataRow("vendor///package")] + [DataRow("vendor/other/package")] + public async Task ManifestRequirementWithMultipleSeparators_ReportsParseFailureAsync(string name) + { + var (result, recorder) = await this.DetectorTestUtility + .WithFile("composer.json", $$$"""{"require":{"{{{name}}}":"1.0"}}""") + .ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().Equal($"{Path.Combine(Path.GetTempPath(), "composer.json")}.require.{name}"); + } + [TestMethod] [DataRow("permission", false)] [DataRow("missing-file", false)] @@ -332,11 +347,6 @@ public async Task UnreadableInstalledInventory_ReportsFailureAndContinuesWithFal } [TestMethod] - [DataRow("{\"config\":false}")] - [DataRow("{\"config\":null}")] - [DataRow("{\"config\":[]}")] - [DataRow("{\"config\":{\"vendor-dir\":42}}")] - [DataRow("{\"config\":{\"vendor-dir\":null}}")] [DataRow("{\"config\":{\"vendor-dir\":\"\"}}")] [DataRow("{\"config\":{\"vendor-dir\":\" \"}}")] [DataRow("{\"config\":{\"vendor-dir\":\"\\u0000\"}}")] @@ -360,6 +370,41 @@ public async Task InvalidVendorConfiguration_WarnsAndReadsDefaultVendorInventory Times.Once); } + [TestMethod] + [DataRow("{}")] + [DataRow("{\"config\":null}")] + [DataRow("{\"config\":{}}")] + [DataRow("{\"config\":{\"vendor-dir\":null}}")] + public async Task MissingOrNullVendorConfiguration_UsesDefaultVendorInventoryWithoutWarningsAsync(string content) + { + var files = this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), """{"packages":[{"name":"vendor/installed","version":"1.2.3"}]}"""); + var logger = new Mock>(); + var (result, recorder) = await this.DetectorTestUtility.AddServiceMock(logger).WithFile("composer.json", content).ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/installed", "1.2.3")); + recorder.GetSkippedComponents().Should().BeEmpty(); + files.Verify(value => value.MakeFileStream(Path.Combine(Path.GetTempPath(), "vendor", "composer", "installed.json")), Times.Once); + logger.Verify( + value => value.Log(LogLevel.Warning, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>()), + Times.Never); + } + + [TestMethod] + [DataRow("{\"config\":false}")] + [DataRow("{\"config\":[]}")] + [DataRow("{\"config\":{\"vendor-dir\":42}}")] + public async Task MalformedVendorConfiguration_ReportsParseFailureWithoutReadingInventoryAsync(string content) + { + var files = this.WithInstalledFile(Path.Combine(Path.GetTempPath(), "vendor"), """{"packages":[]}"""); + var (result, recorder) = await this.DetectorTestUtility.WithFile("composer.json", content).ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().Equal(Path.Combine(Path.GetTempPath(), "composer.json")); + files.VerifyNoOtherCalls(); + } + [TestMethod] public async Task InvalidVendorEnvironmentPath_WarnsAndUsesDefaultRatherThanConfiguredDirectoryAsync() { @@ -711,6 +756,9 @@ public async Task ManifestOnly_MalformedDataReportsParseFailureAsync(string cont [TestMethod] [DataRow("package")] + [DataRow("vendor//package")] + [DataRow("vendor///package")] + [DataRow("vendor/other/package")] [DataRow("vendor/")] [DataRow("/package")] [DataRow(" ")] @@ -1044,12 +1092,9 @@ public async Task LockAliases_RequireUniqueNameAndVersionMatchesAsync(string oth [TestMethod] [DataRow("null")] - [DataRow("[]")] [DataRow("{}")] - [DataRow("""{"package":42,"version":"dev-main","alias":"2.x-dev"}""")] [DataRow("""{"package":" ","version":"dev-main","alias":"2.x-dev"}""")] [DataRow("""{"package":"vendor/branch","version":null,"alias":"2.x-dev"}""")] - [DataRow("""{"package":"vendor/branch","version":"dev-main","alias":false}""")] [DataRow("""{"package":"vendor/branch","version":"dev-main","alias":" "}""")] public async Task MalformedLockAliases_ReportFailureAndRetainValidAliasesAsync(string invalidAlias) { @@ -1068,10 +1113,7 @@ public async Task MalformedLockAliases_ReportFailureAndRetainValidAliasesAsync(s } [TestMethod] - [DataRow("null", "packages[1].extra.branch-alias")] - [DataRow("[]", "packages[1].extra.branch-alias")] [DataRow("""{"dev-main":null}""", "packages[1].extra.branch-alias.dev-main")] - [DataRow("""{"dev-main":42}""", "packages[1].extra.branch-alias.dev-main")] [DataRow("""{"dev-main":" "}""", "packages[1].extra.branch-alias.dev-main")] public async Task MalformedBranchAliases_ReportFailureWithoutDroppingLockedPackagesAsync(string aliases, string failureLocation) { @@ -1090,6 +1132,35 @@ public async Task MalformedBranchAliases_ReportFailureWithoutDroppingLockedPacka recorder.GetSkippedComponents().Should().Equal(failureLocation); } + [TestMethod] + public async Task NullBranchAliases_AreTreatedAsUnavailableAsync() + { + var (_, recorder) = await this.DetectAsync(""" + {"packages":[{"name":"vendor/branch","version":"dev-main","extra":{"branch-alias":null}}]} + """); + + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal(Id("vendor/branch", "dev-main")); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow("[]")] + [DataRow("false")] + [DataRow("42")] + [DataRow("""{"dev-main":42}""")] + public async Task MalformedBranchAliasObject_ReportsInvalidLockfileAsync(string aliases) + { + var (_, recorder) = await this.DetectAsync($$$""" + {"packages":[ + {"name":"vendor/valid","version":"1"}, + {"name":"vendor/branch","version":"dev-main","extra":{"branch-alias":{{{aliases}}}}} + ]} + """); + + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().Equal(Path.Combine(Path.GetTempPath(), "composer.lock")); + } + [TestMethod] public async Task ConflictingDuplicateDeclarations_ReportFailureWithoutFabricatedVirtualEdgesAsync() { @@ -1109,18 +1180,35 @@ public async Task ConflictingDuplicateDeclarations_ReportFailureWithoutFabricate } [TestMethod] - public async Task ConflictingDuplicateDependencyNames_ReportFailuresAsync() + public async Task DuplicateDependencyKeys_UseLastValueAsync() { var (_, recorder) = await this.DetectAsync(""" {"packages":[ {"name":"vendor/app","version":"1","require":{ - "invalid":"*","vendor/bad/name":"*","vendor/api":"1","VENDOR/API":"2","vendor/api":"2"}}, + "invalid":"*","vendor/api":"1","VENDOR/API":"2","vendor/api":"2"}}, + {"name":"vendor/api","version":"2"} + ]} + """); + + recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")).Should().Equal(Id("vendor/api", "2")); + recorder.GetSkippedComponents().Should().BeEmpty(); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task ConflictingCaseVariantDependencyNames_ReportFailuresAsync(bool isDevelopment) + { + var section = isDevelopment ? "packages-dev" : "packages"; + var (_, recorder) = await this.DetectAsync($$$""" + {"{{{section}}}":[ + {"name":"vendor/app","version":"1","require":{"vendor/api":"1","VENDOR/API":"2"}}, {"name":"vendor/api","version":"2"} ]} """); recorder.GetDependencyGraphsByLocation().Values.Single().GetDependenciesForComponent(Id("vendor/app", "1")).Should().BeEmpty(); - recorder.GetSkippedComponents().Should().Equal("packages[0].require.vendor/api"); + recorder.GetSkippedComponents().Should().Equal($"{section}[0].require.vendor/api"); } [TestMethod] @@ -1212,6 +1300,9 @@ public async Task Manifest_SelfVersionClaimsNeverGuessAnInstalledProviderAsync(s [DataRow("""{"packages":[]}""")] [DataRow("""{"packages-dev":[]}""")] [DataRow("""{"packages":[],"packages-dev":[]}""")] + [DataRow("""{"packages":null}""")] + [DataRow("""{"packages-dev":null}""")] + [DataRow("""{"aliases":null}""")] public async Task MissingOrEmptySections_AreValidAsync(string content) { var (result, recorder) = await this.DetectorTestUtility.WithFile("composer.lock", content).ExecuteDetectorAsync(); @@ -1224,7 +1315,6 @@ public async Task MissingOrEmptySections_AreValidAsync(string content) [DataRow("{")] [DataRow("null")] [DataRow("[]")] - [DataRow("""{"packages":null}""")] [DataRow("""{"packages":{}}""")] public async Task MalformedDocumentsOrSections_ReportParseFailuresAsync(string content) { @@ -1234,17 +1324,45 @@ public async Task MalformedDocumentsOrSections_ReportParseFailuresAsync(string c } [TestMethod] - public async Task MalformedEntries_ReportFailuresAndRetainValidPackagesAsync() + [DataRow("[]")] + [DataRow("""{"package":42,"version":"dev-main","alias":"2.x-dev"}""")] + [DataRow("""{"package":"vendor/branch","version":"dev-main","alias":false}""")] + public async Task WrongAliasTypes_ReportLockfileParseFailureAsync(string alias) + { + var (_, recorder) = await this.DetectAsync($$$""" + {"packages":[{"name":"vendor/valid","version":"1"}],"aliases":[{{{alias}}}]} + """); + + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().Equal(Path.Combine(Path.GetTempPath(), "composer.lock")); + } + + [TestMethod] + [DataRow("""{"name":"vendor/bad","version":42}""")] + [DataRow("""{"name":"vendor/bad","version":"1","require":{"vendor/child":false}}""")] + [DataRow("""{"name":"vendor/bad","version":"1","provide":[]}""")] + public async Task WrongPackageTypes_ReportLockfileParseFailureAsync(string entry) + { + var (_, recorder) = await this.DetectAsync($$$""" + {"packages":[{{{entry}}},{"name":"vendor/valid","version":"1"}]} + """); + + recorder.GetDetectedComponents().Should().BeEmpty(); + recorder.GetSkippedComponents().Should().Equal(Path.Combine(Path.GetTempPath(), "composer.lock")); + } + + [TestMethod] + public async Task MissingPackageIdentities_ReportFailuresAndRetainValidPackagesAsync() { var (_, recorder) = await this.DetectAsync(""" - {"packages":[null,{},{"name":"vendor/no-version"},{"name":"vendor/bad","version":42}, + {"packages":[null,{},{"name":"vendor/no-version"},{"name":"vendor/bad","version":null}, {"name":"not-namespaced","version":"1"},{"name":"vendor/empty","version":" "}, - {"name":"vendor/valid","version":"1","require":{"vendor/child":false}}, - {"name":"vendor/valid2","version":"2","provide":[]}]} + {"name":"vendor/valid","version":"1","require":null}, + {"name":"vendor/valid2","version":"2","provide":null}]} """); - recorder.GetDetectedComponents().Should().HaveCount(2); - recorder.GetSkippedComponents().Should().HaveCount(8); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().BeEquivalentTo([Id("vendor/valid", "1"), Id("vendor/valid2", "2")]); + recorder.GetSkippedComponents().Should().HaveCount(6); } [TestMethod] diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerJsonSerializerTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerJsonSerializerTests.cs new file mode 100644 index 000000000..30970afb4 --- /dev/null +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerJsonSerializerTests.cs @@ -0,0 +1,148 @@ +#nullable disable +namespace Microsoft.ComponentDetection.Detectors.Tests; + +using System; +using System.IO; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using AwesomeAssertions; +using Microsoft.ComponentDetection.Detectors.Composer.Contracts; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +[TestCategory("Governance/All")] +[TestCategory("Governance/ComponentDetection")] +public class ComposerJsonSerializerTests +{ + private static readonly JsonSerializerOptions SerializerOptions = new() + { + AllowTrailingCommas = true, + ReadCommentHandling = JsonCommentHandling.Skip, + }; + + [TestMethod] + public void DeserializeLockFile_PreservesTypedMetadataAndUsesLastDuplicateValue() + { + var file = JsonSerializer.Deserialize( + """ + { + "packages":[{ + "name":" Vendor/App ","version":"dev-main", + "require":{"vendor/api":"1","vendor/api":"2"}, + "extra":{"branch-alias":{"dev-main":"2.x-dev"}} + }], + "packages-dev":[{"name":"vendor/tests","version":"3"}], + "aliases":[{"package":"Vendor/App","version":"dev-main","alias":"2.x-dev"}] + } + """, + SerializerOptions); + + var package = file.Packages.Should().ContainSingle().Which; + package.Name.Should().Be(" Vendor/App "); + package.Version.Should().Be("dev-main"); + package.Require.Should().ContainSingle().Which.Key.Should().Be("vendor/api"); + package.Require["vendor/api"].Should().Be("2"); + package.Extra.BranchAliases.Should().ContainSingle().Which.Value.Should().Be("2.x-dev"); + file.DevelopmentPackages.Should().ContainSingle().Which.Name.Should().Be("vendor/tests"); + var alias = file.Aliases.Should().ContainSingle().Which; + alias.Package.Should().Be("Vendor/App"); + alias.Version.Should().Be("dev-main"); + alias.Alias.Should().Be("2.x-dev"); + } + + [TestMethod] + [DataRow("null")] + [DataRow("{}")] + public void DeserializeLockFile_NullOrMissingEntryPropertiesDoNotDiscardFollowingPackages(string invalidEntry) + { + var file = JsonSerializer.Deserialize( + $$$""" + {"packages":[{{{invalidEntry}}},{"name":"vendor/valid","version":"1"}]} + """, + SerializerOptions); + + file.Packages.Should().HaveCount(2); + file.Packages[0]?.Name.Should().BeNull(); + file.Packages[1].Name.Should().Be("vendor/valid"); + file.Packages[1].Version.Should().Be("1"); + } + + [TestMethod] + [DataRow("{}")] + [DataRow("{\"config\":null}")] + public void DeserializeManifest_MissingOrNullConfigIsUnavailable(string json) + { + var manifest = JsonSerializer.Deserialize(json, SerializerOptions); + + manifest.Config.Should().BeNull(); + } + + [TestMethod] + [DataRow("{\"config\":false}")] + [DataRow("{\"config\":[]}")] + public void DeserializeManifest_MalformedConfigReportsJsonError(string json) + { + Action deserialize = () => JsonSerializer.Deserialize(json, SerializerOptions); + + deserialize.Should().Throw(); + } + + [TestMethod] + [DataRow("{\"config\":{}}")] + [DataRow("{\"config\":{\"vendor-dir\":null}}")] + public void DeserializeManifest_MissingOrNullVendorDirectoryIsUnavailable(string json) + { + var manifest = JsonSerializer.Deserialize(json, SerializerOptions); + + manifest.Config.Should().NotBeNull(); + manifest.Config.VendorDirectory.Should().BeNull(); + } + + [TestMethod] + public void DeserializeInstalledPackages_ReadsCurrentInventory() + { + const string packages = """[{"name":"vendor/package","version":"1"}]"""; + var json = $$$"""{"packages":{{{packages}}},"dev-package-names":["vendor/package"]}"""; + var inventory = JsonSerializer.Deserialize(json, SerializerOptions); + + var package = inventory.Packages.Should().ContainSingle().Which; + package.Name.Should().Be("vendor/package"); + package.Version.Should().Be("1"); + inventory.DevelopmentPackageNames.Should().Equal("vendor/package"); + } + + [TestMethod] + [DataRow("{\"packages\":[{\"name\":\"vendor/app\",\"version\":\"1\"}")] + [DataRow("{\"packages\":[false,}")] + [DataRow("{\"packages\":{\"unexpected\":[}")] + [DataRow("{\"packages\":[{\"require\":{\"vendor/child\":[}}]}")] + [DataRow("{\"packages\":[false]}")] + [DataRow("{\"packages\":[42]}")] + [DataRow("{\"packages\":[[]]}")] + [DataRow("{\"packages\":[\"invalid\"]}")] + public void DeserializeLockFile_DoesNotTreatInvalidJsonAsRecoverableSchemaErrors(string json) + { + Action deserialize = () => JsonSerializer.Deserialize(json, SerializerOptions); + + deserialize.Should().Throw(); + } + + [TestMethod] + public async Task DeserializeAsync_ReadsFieldsAcrossSerializerBufferBoundariesAsync() + { + var json = $$$""" + {"ignored":"{{{new string('x', 65536)}}}","packages":[ + {"name":"vendor/app","version":"1","require":{"vendor/child":"^2"}} + ],"packages-dev":[{"name":"vendor/child","version":"2"}]} + """; + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); + + var file = await JsonSerializer.DeserializeAsync(stream, SerializerOptions); + + file.Packages.Should().ContainSingle().Which.Name.Should().Be("vendor/app"); + file.Packages[0].Require.Should().ContainSingle().Which.Value.Should().Be("^2"); + file.DevelopmentPackages.Should().ContainSingle().Which.Name.Should().Be("vendor/child"); + stream.CanRead.Should().BeTrue(); + } +} diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs index 393abd780..243264183 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ComposerPlatformTests.cs @@ -384,13 +384,11 @@ public async Task VendorOnlyInput_DoesNotQueryPlatformWithoutAParentProjectAsync } [TestMethod] - [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":true}""", true, false)] - [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":false}""", false, false)] - [DataRow("""{"name":"php","version":"8.4.27"}""", false, false)] - [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":"true"}""", false, true)] - [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":null}""", false, true)] - [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":1}""", false, true)] - public async Task PlatformDirectDependency_UsesComposerMetadataWithoutDroppingInventoryAsync(string entry, bool explicitlyReferenced, bool invalidMetadata) + [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":true}""", true)] + [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":false}""", false)] + [DataRow("""{"name":"php","version":"8.4.27"}""", false)] + [DataRow("""{"name":"php","version":"8.4.27","direct-dependency":null}""", false)] + public async Task PlatformDirectDependency_UsesNullableComposerMetadataAsync(string entry, bool explicitlyReferenced) { this.WithOutput($$"""{"platform":[{{entry}}]}"""); var location = Path.Combine(Path.GetTempPath(), "composer.json"); @@ -403,7 +401,28 @@ public async Task PlatformDirectDependency_UsesComposerMetadataWithoutDroppingIn graph.GetAllExplicitlyReferencedComponents().Should().BeEquivalentTo(expectedExplicitReferences); graph.IsDevelopmentDependency("php 8.4.27 - PhpSdk").Should().BeTrue(); recorder.GetSkippedComponents().Should().BeEmpty(); - this.VerifyWarning("invalid direct-dependency", invalidMetadata ? Times.Once() : Times.Never()); + this.VerifyWarning("invalid package identity", Times.Never()); + } + + [TestMethod] + [DataRow("\"true\"")] + [DataRow("1")] + [DataRow("[]")] + public async Task MalformedPlatformMetadata_ReportsInvalidInventoryAndPreservesPackageDetectionAsync(string directDependency) + { + this.WithOutput($$$""" + {"platform":[ + {"name":"php","version":"8.4.27","direct-dependency":{{{directDependency}}}}, + {"name":"ext-json","version":"8.4.27","direct-dependency":true} + ]} + """); + var (result, recorder) = await this.DetectorTestUtility.WithFile("composer.json", """{"require":{"vendor/app":"1.0"}}""").ExecuteDetectorAsync(); + + result.ResultCode.Should().Be(ProcessingResultCode.Success); + recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("vendor/app 1.0 - Composer"); + recorder.GetDependencyGraphsByLocation().Values.Single().GetAllExplicitlyReferencedComponents().Should().Equal("vendor/app 1.0 - Composer"); + recorder.GetSkippedComponents().Should().BeEmpty(); + this.VerifyWarning("not valid JSON", Times.Once()); } [TestMethod] @@ -472,7 +491,7 @@ public async Task InvalidOutput_WarnsAndPreservesPackageDetectionAsync(string ou [TestMethod] public async Task InvalidEntries_WarnAndRetainValidEnvironmentComponentsAsync() { - this.WithOutput("""{"platform":[null,{}, {"name":"php","version":8}, {"name":"ext-json","version":" "}, {"name":"php","version":"8.4.27"}]}"""); + this.WithOutput("""{/* Inventory */"platform":[null,{}, {"name":"php","version":null}, {"name":"ext-json","version":" "}, {"name":"php","version":"8.4.27"},],}"""); var (_, recorder) = await this.DetectorTestUtility.WithFile("composer.json", "{}").ExecuteDetectorAsync(); recorder.GetDetectedComponents().Select(component => component.Component.Id).Should().Equal("php 8.4.27 - PhpSdk"); From 5caa8fc5598f9d5b4c6223b7cd7a8cc427ab8464 Mon Sep 17 00:00:00 2001 From: Greg Villicana <58237075+grvillic@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:23:25 -0800 Subject: [PATCH 5/5] Correct lenient JSON options in documentation Updated documentation to reflect changes in lenient JSON options and usage. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- docs/creating-a-new-detector.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/creating-a-new-detector.md b/docs/creating-a-new-detector.md index 49afb4caf..66b8d958e 100644 --- a/docs/creating-a-new-detector.md +++ b/docs/creating-a-new-detector.md @@ -40,10 +40,10 @@ The main parsing logic. Called once per matched file to: - Build the dependency graph via `ComponentRecorder` For JSON formats where comments and trailing commas can be tolerated, derived -detectors can opt in to `FileComponentDetector.LenientJsonDocumentOptions`: +detectors can opt in to `FileComponentDetector.LenientJsonSerializerOptions`: ```csharp -using var document = await JsonDocument.ParseAsync(stream, LenientJsonDocumentOptions, cancellationToken); +var root = await JsonSerializer.DeserializeAsync(stream, LenientJsonSerializerOptions, cancellationToken); ``` These options skip comments and allow trailing commas. They do not relax other