-
Notifications
You must be signed in to change notification settings - Fork 122
Add ability to use syft binary instead of container for Linux detector #1776
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
jasonpaulos
wants to merge
1
commit into
main
Choose a base branch
from
users/jasonpaulos/linux-syft-binary-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
133 changes: 133 additions & 0 deletions
133
src/Microsoft.ComponentDetection.Detectors/linux/BinarySyftRunner.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| namespace Microsoft.ComponentDetection.Detectors.Linux; | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.ComponentDetection.Contracts; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| /// <summary> | ||
| /// Runs Syft by invoking a local Syft binary. | ||
| /// </summary> | ||
| internal class BinarySyftRunner : ISyftRunner | ||
| { | ||
| private static readonly SemaphoreSlim BinarySemaphore = new(2); | ||
|
|
||
| private static readonly int SemaphoreTimeout = Convert.ToInt32( | ||
| TimeSpan.FromHours(1).TotalMilliseconds); | ||
|
|
||
| private readonly string syftBinaryPath; | ||
| private readonly ICommandLineInvocationService commandLineInvocationService; | ||
| private readonly ILogger<BinarySyftRunner> logger; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="BinarySyftRunner"/> class. | ||
| /// </summary> | ||
| /// <param name="syftBinaryPath">The path to the Syft binary.</param> | ||
| /// <param name="commandLineInvocationService">The command line invocation service.</param> | ||
| /// <param name="logger">The logger.</param> | ||
| public BinarySyftRunner( | ||
| string syftBinaryPath, | ||
| ICommandLineInvocationService commandLineInvocationService, | ||
| ILogger<BinarySyftRunner> logger) | ||
| { | ||
| this.syftBinaryPath = syftBinaryPath; | ||
| this.commandLineInvocationService = commandLineInvocationService; | ||
| this.logger = logger; | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public async Task<bool> CanRunAsync(CancellationToken cancellationToken = default) | ||
| { | ||
| var result = await this.commandLineInvocationService.ExecuteCommandAsync( | ||
| this.syftBinaryPath, | ||
| null, | ||
| null, | ||
| cancellationToken, | ||
| "--version"); | ||
|
|
||
| if (result.ExitCode != 0) | ||
| { | ||
| this.logger.LogInformation( | ||
| "Syft binary at {SyftBinaryPath} failed version check with exit code {ExitCode}. Stderr: {StdErr}", | ||
| this.syftBinaryPath, | ||
| result.ExitCode, | ||
| result.StdErr); | ||
| return false; | ||
| } | ||
|
|
||
| this.logger.LogInformation( | ||
| "Using Syft binary at {SyftBinaryPath}: {SyftVersion}", | ||
| this.syftBinaryPath, | ||
| result.StdOut?.Trim()); | ||
| return true; | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public async Task<(string Stdout, string Stderr)> RunSyftAsync( | ||
| ImageReference imageReference, | ||
| IList<string> arguments, | ||
| CancellationToken cancellationToken = default) | ||
| { | ||
| var syftSource = GetSyftSource(imageReference); | ||
| var acquired = false; | ||
|
|
||
| try | ||
| { | ||
| acquired = await BinarySemaphore.WaitAsync(SemaphoreTimeout, cancellationToken); | ||
| if (!acquired) | ||
| { | ||
| this.logger.LogWarning( | ||
| "Failed to enter the binary semaphore for image {ImageReference}", | ||
| imageReference.Reference); | ||
| return (string.Empty, string.Empty); | ||
| } | ||
|
|
||
| var parameters = new[] { syftSource } | ||
| .Concat(arguments) | ||
| .ToArray(); | ||
|
|
||
| var result = await this.commandLineInvocationService.ExecuteCommandAsync( | ||
| this.syftBinaryPath, | ||
| null, | ||
| null, | ||
| cancellationToken, | ||
| parameters); | ||
|
|
||
| if (result.ExitCode != 0) | ||
| { | ||
| this.logger.LogError( | ||
| "Syft binary exited with code {ExitCode}. Stderr: {StdErr}", | ||
| result.ExitCode, | ||
| result.StdErr); | ||
| } | ||
|
|
||
| return (result.StdOut, result.StdErr); | ||
| } | ||
| finally | ||
| { | ||
| if (acquired) | ||
| { | ||
| BinarySemaphore.Release(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Constructs the Syft source argument from an image reference. | ||
| /// For local images, the host path is used directly with the appropriate scheme prefix. | ||
| /// </summary> | ||
| private static string GetSyftSource(ImageReference imageReference) => | ||
| imageReference.Kind switch | ||
| { | ||
| ImageReferenceKind.DockerImage => imageReference.Reference, | ||
| ImageReferenceKind.OciLayout => $"oci-dir:{imageReference.Reference}", | ||
| ImageReferenceKind.OciArchive => $"oci-archive:{imageReference.Reference}", | ||
| ImageReferenceKind.DockerArchive => $"docker-archive:{imageReference.Reference}", | ||
| _ => throw new ArgumentOutOfRangeException( | ||
| nameof(imageReference), | ||
| $"Unsupported image reference kind '{imageReference.Kind}'."), | ||
| }; | ||
| } | ||
33 changes: 33 additions & 0 deletions
33
src/Microsoft.ComponentDetection.Detectors/linux/BinarySyftRunnerFactory.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| namespace Microsoft.ComponentDetection.Detectors.Linux; | ||
|
|
||
| using Microsoft.ComponentDetection.Contracts; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| /// <summary> | ||
| /// Factory for creating <see cref="BinarySyftRunner"/> instances. | ||
| /// </summary> | ||
| internal class BinarySyftRunnerFactory : IBinarySyftRunnerFactory | ||
| { | ||
| private readonly ICommandLineInvocationService commandLineInvocationService; | ||
| private readonly ILoggerFactory loggerFactory; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="BinarySyftRunnerFactory"/> class. | ||
| /// </summary> | ||
| /// <param name="commandLineInvocationService">The command line invocation service.</param> | ||
| /// <param name="loggerFactory">The logger factory.</param> | ||
| public BinarySyftRunnerFactory( | ||
| ICommandLineInvocationService commandLineInvocationService, | ||
| ILoggerFactory loggerFactory) | ||
| { | ||
| this.commandLineInvocationService = commandLineInvocationService; | ||
| this.loggerFactory = loggerFactory; | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public ISyftRunner Create(string binaryPath) => | ||
| new BinarySyftRunner( | ||
| binaryPath, | ||
| this.commandLineInvocationService, | ||
| this.loggerFactory.CreateLogger<BinarySyftRunner>()); | ||
| } |
141 changes: 141 additions & 0 deletions
141
src/Microsoft.ComponentDetection.Detectors/linux/DockerSyftRunner.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| namespace Microsoft.ComponentDetection.Detectors.Linux; | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using System.Runtime.InteropServices; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.ComponentDetection.Common.Telemetry.Records; | ||
| using Microsoft.ComponentDetection.Contracts; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| /// <summary> | ||
| /// Runs Syft by executing a Docker container with the Syft image. | ||
| /// </summary> | ||
| internal class DockerSyftRunner : IDockerSyftRunner | ||
| { | ||
| internal const string ScannerImage = | ||
| "governancecontainerregistry.azurecr.io/syft:v1.37.0@sha256:48d679480c6d272c1801cf30460556959c01d4826795be31d4fd8b53750b7d91"; | ||
|
|
||
| private const string LocalImageMountPoint = "/image"; | ||
|
|
||
| private static readonly SemaphoreSlim ContainerSemaphore = new(2); | ||
|
|
||
| private static readonly int SemaphoreTimeout = Convert.ToInt32( | ||
| TimeSpan.FromHours(1).TotalMilliseconds); | ||
|
|
||
| private readonly IDockerService dockerService; | ||
| private readonly ILogger<DockerSyftRunner> logger; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="DockerSyftRunner"/> class. | ||
| /// </summary> | ||
| /// <param name="dockerService">The docker service.</param> | ||
| /// <param name="logger">The logger.</param> | ||
| public DockerSyftRunner(IDockerService dockerService, ILogger<DockerSyftRunner> logger) | ||
| { | ||
| this.dockerService = dockerService; | ||
| this.logger = logger; | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public async Task<bool> CanRunAsync(CancellationToken cancellationToken = default) | ||
| { | ||
| if (await this.dockerService.CanRunLinuxContainersAsync(cancellationToken)) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| using var record = new LinuxContainerDetectorUnsupportedOs | ||
| { | ||
| Os = RuntimeInformation.OSDescription, | ||
| }; | ||
| this.logger.LogInformation("Linux containers are not available on this host."); | ||
| return false; | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public async Task<(string Stdout, string Stderr)> RunSyftAsync( | ||
| ImageReference imageReference, | ||
| IList<string> arguments, | ||
| CancellationToken cancellationToken = default) | ||
| { | ||
| var (syftSource, additionalBinds) = GetSyftSourceAndBinds(imageReference); | ||
| var acquired = false; | ||
|
|
||
| try | ||
| { | ||
| acquired = await ContainerSemaphore.WaitAsync(SemaphoreTimeout, cancellationToken); | ||
| if (!acquired) | ||
| { | ||
| this.logger.LogWarning( | ||
| "Failed to enter the container semaphore for image {ImageReference}", | ||
| imageReference.Reference); | ||
| return (string.Empty, string.Empty); | ||
| } | ||
|
|
||
| var command = new List<string> { syftSource } | ||
| .Concat(arguments) | ||
| .ToList(); | ||
|
|
||
| return await this.dockerService.CreateAndRunContainerAsync( | ||
| ScannerImage, | ||
| command, | ||
| additionalBinds, | ||
| cancellationToken); | ||
| } | ||
| finally | ||
| { | ||
| if (acquired) | ||
| { | ||
| ContainerSemaphore.Release(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Constructs the Syft source argument and any required Docker bind mounts from an image reference. | ||
| /// For Docker images, no additional binds are needed. For local images (OCI/archives), | ||
| /// the host path is mounted into the container and the source uses the container-relative path. | ||
| /// </summary> | ||
| private static (string SyftSource, IList<string> AdditionalBinds) GetSyftSourceAndBinds(ImageReference imageReference) | ||
| { | ||
| switch (imageReference.Kind) | ||
| { | ||
| case ImageReferenceKind.DockerImage: | ||
| return (imageReference.Reference, []); | ||
|
|
||
| case ImageReferenceKind.OciLayout: | ||
| return ( | ||
| $"oci-dir:{LocalImageMountPoint}", | ||
| [$"{imageReference.Reference}:{LocalImageMountPoint}:ro"]); | ||
|
|
||
| case ImageReferenceKind.OciArchive: | ||
| { | ||
| var dir = Path.GetDirectoryName(imageReference.Reference) | ||
| ?? throw new InvalidOperationException($"Could not determine parent directory for OCI archive path '{imageReference.Reference}'."); | ||
| var fileName = Path.GetFileName(imageReference.Reference); | ||
| return ( | ||
| $"oci-archive:{LocalImageMountPoint}/{fileName}", | ||
| [$"{dir}:{LocalImageMountPoint}:ro"]); | ||
| } | ||
|
|
||
| case ImageReferenceKind.DockerArchive: | ||
| { | ||
| var dir = Path.GetDirectoryName(imageReference.Reference) | ||
| ?? throw new InvalidOperationException($"Could not determine parent directory for Docker archive path '{imageReference.Reference}'."); | ||
| var fileName = Path.GetFileName(imageReference.Reference); | ||
| return ( | ||
| $"docker-archive:{LocalImageMountPoint}/{fileName}", | ||
| [$"{dir}:{LocalImageMountPoint}:ro"]); | ||
| } | ||
|
|
||
| default: | ||
| throw new ArgumentOutOfRangeException( | ||
| nameof(imageReference), | ||
| $"Unsupported image reference kind '{imageReference.Kind}'."); | ||
| } | ||
| } | ||
| } |
14 changes: 14 additions & 0 deletions
14
src/Microsoft.ComponentDetection.Detectors/linux/IBinarySyftRunnerFactory.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| namespace Microsoft.ComponentDetection.Detectors.Linux; | ||
|
|
||
| /// <summary> | ||
| /// Factory for creating binary-based Syft runners. | ||
| /// </summary> | ||
| public interface IBinarySyftRunnerFactory | ||
| { | ||
| /// <summary> | ||
| /// Creates a binary Syft runner configured to use the specified binary path. | ||
| /// </summary> | ||
| /// <param name="binaryPath">The path to the Syft binary.</param> | ||
| /// <returns>An <see cref="ISyftRunner"/> that invokes the specified Syft binary.</returns> | ||
| ISyftRunner Create(string binaryPath); | ||
| } |
9 changes: 9 additions & 0 deletions
9
src/Microsoft.ComponentDetection.Detectors/linux/IDockerSyftRunner.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| namespace Microsoft.ComponentDetection.Detectors.Linux; | ||
|
|
||
| /// <summary> | ||
| /// Marker interface for the Docker-based Syft runner. | ||
| /// Runs Syft by executing a Docker container with the Syft image. | ||
| /// </summary> | ||
| public interface IDockerSyftRunner : ISyftRunner | ||
| { | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
CanRunAsynccallsICommandLineInvocationService.ExecuteCommandAsync, which throws (e.g.,InvalidOperationException) when the command path cannot be located. IfLinux.SyftBinaryPathis missing/invalid, this will bubble up and fail the Linux detector instead of treating the runner as unavailable. Consider catching command-location exceptions (or callingCanCommandBeLocatedAsyncfirst) and returningfalseso the detector can skip cleanly (or fall back to the Docker runner).