Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions src/Microsoft.ComponentDetection.Detectors/linux/BinarySyftRunner.cs
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;
Comment on lines +44 to +65
Copy link

Copilot AI Apr 9, 2026

Choose a reason for hiding this comment

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

CanRunAsync calls ICommandLineInvocationService.ExecuteCommandAsync, which throws (e.g., InvalidOperationException) when the command path cannot be located. If Linux.SyftBinaryPath is missing/invalid, this will bubble up and fail the Linux detector instead of treating the runner as unavailable. Consider catching command-location exceptions (or calling CanCommandBeLocatedAsync first) and returning false so the detector can skip cleanly (or fall back to the Docker runner).

Suggested change
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;
if (string.IsNullOrWhiteSpace(this.syftBinaryPath))
{
this.logger.LogInformation("Syft binary path is not configured.");
return false;
}
try
{
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;
}
catch (InvalidOperationException ex)
{
this.logger.LogInformation(
ex,
"Syft binary at {SyftBinaryPath} could not be located or invoked.",
this.syftBinaryPath);
return false;
}

Copilot uses AI. Check for mistakes.
}

/// <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}'."),
};
}
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 src/Microsoft.ComponentDetection.Detectors/linux/DockerSyftRunner.cs
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}'.");
}
}
}
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);
}
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
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,35 +16,37 @@ public interface ILinuxScanner
/// Scans a Linux container image for components and maps them to their respective layers.
/// Runs Syft and processes the output in a single step.
/// </summary>
/// <param name="imageHash">The hash identifier of the container image to scan.</param>
/// <param name="imageReference">The image reference to scan.</param>
/// <param name="containerLayers">The collection of Docker layers that make up the container image.</param>
/// <param name="baseImageLayerCount">The number of layers that belong to the base image, used to distinguish base image layers from application layers.</param>
/// <param name="enabledComponentTypes">The set of component types to include in the scan results. Only components matching these types will be returned.</param>
/// <param name="scope">The scope for scanning the image. See <see cref="LinuxScannerScope"/> for values.</param>
/// <param name="syftRunner">The Syft runner to use for executing the scan.</param>
/// <param name="cancellationToken">A token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains a collection of <see cref="LayerMappedLinuxComponents"/> representing the components found in the image and their associated layers.</returns>
public Task<IEnumerable<LayerMappedLinuxComponents>> ScanLinuxAsync(
string imageHash,
ImageReference imageReference,
IEnumerable<DockerLayer> containerLayers,
int baseImageLayerCount,
ISet<ComponentType> enabledComponentTypes,
LinuxScannerScope scope,
ISyftRunner syftRunner,
CancellationToken cancellationToken = default
);

/// <summary>
/// Runs the Syft scanner and returns the raw parsed output without processing components.
/// Use this when the caller needs access to the full Syft output (e.g., to extract source metadata for OCI images).
/// </summary>
/// <param name="syftSource">The source argument passed to Syft (e.g., an image hash or "oci-dir:/oci-image").</param>
/// <param name="additionalBinds">Additional volume bind mounts for the Syft container (e.g., for mounting OCI directories).</param>
/// <param name="imageReference">The image reference to scan.</param>
/// <param name="scope">The scope for scanning the image.</param>
/// <param name="syftRunner">The Syft runner to use for executing the scan.</param>
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the parsed <see cref="SyftOutput"/>.</returns>
public Task<SyftOutput> GetSyftOutputAsync(
string syftSource,
IList<string> additionalBinds,
ImageReference imageReference,
LinuxScannerScope scope,
ISyftRunner syftRunner,
CancellationToken cancellationToken = default
);

Expand Down
Loading
Loading