|
| 1 | +namespace Microsoft.ComponentDetection.Detectors.Rust; |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.IO; |
| 6 | +using System.Text.RegularExpressions; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using Microsoft.ComponentDetection.Contracts; |
| 10 | +using Microsoft.ComponentDetection.Contracts.Internal; |
| 11 | +using Microsoft.ComponentDetection.Contracts.TypedComponent; |
| 12 | +using Microsoft.ComponentDetection.Detectors.Rust.Sbom.Contracts; |
| 13 | +using Microsoft.Extensions.Logging; |
| 14 | + |
| 15 | +public class RustSbomDetector : FileComponentDetector, IDefaultOffComponentDetector |
| 16 | +{ |
| 17 | + private const string CargoSbomSearchPattern = "*.cargo-sbom.json"; |
| 18 | + private const string CratesIoSource = "registry+https://github.com/rust-lang/crates.io-index"; |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Cargo Package ID: source#name@version |
| 22 | + /// https://rustwiki.org/en/cargo/reference/pkgid-spec.html. |
| 23 | + /// </summary> |
| 24 | + private static readonly Regex CargoPackageIdRegex = new Regex( |
| 25 | + @"^(?<source>[^#]*)#?(?<name>[\w\-]*)[@#]?(?<version>\d[\S]*)?$", |
| 26 | + RegexOptions.Compiled); |
| 27 | + |
| 28 | + public RustSbomDetector( |
| 29 | + IComponentStreamEnumerableFactory componentStreamEnumerableFactory, |
| 30 | + IObservableDirectoryWalkerFactory walkerFactory, |
| 31 | + ILogger<RustSbomDetector> logger) |
| 32 | + { |
| 33 | + this.ComponentStreamEnumerableFactory = componentStreamEnumerableFactory; |
| 34 | + this.Scanner = walkerFactory; |
| 35 | + this.Logger = logger; |
| 36 | + } |
| 37 | + |
| 38 | + public override string Id => "RustSbom"; |
| 39 | + |
| 40 | + public override IList<string> SearchPatterns => [CargoSbomSearchPattern]; |
| 41 | + |
| 42 | + public override IEnumerable<ComponentType> SupportedComponentTypes => [ComponentType.Cargo]; |
| 43 | + |
| 44 | + public override int Version { get; } = 1; |
| 45 | + |
| 46 | + public override IEnumerable<string> Categories => ["Rust"]; |
| 47 | + |
| 48 | + private static bool ParsePackageIdSpec(string dependency, out CargoComponent component) |
| 49 | + { |
| 50 | + var match = CargoPackageIdRegex.Match(dependency); |
| 51 | + var name = match.Groups["name"].Value; |
| 52 | + var version = match.Groups["version"].Value; |
| 53 | + var source = match.Groups["source"].Value; |
| 54 | + |
| 55 | + if (!match.Success) |
| 56 | + { |
| 57 | + component = null; |
| 58 | + return false; |
| 59 | + } |
| 60 | + |
| 61 | + if (string.IsNullOrWhiteSpace(name)) |
| 62 | + { |
| 63 | + name = source[(source.LastIndexOf('/') + 1)..]; |
| 64 | + } |
| 65 | + |
| 66 | + if (string.IsNullOrWhiteSpace(source)) |
| 67 | + { |
| 68 | + source = null; |
| 69 | + } |
| 70 | + |
| 71 | + component = new CargoComponent(name, version, source: source); |
| 72 | + return true; |
| 73 | + } |
| 74 | + |
| 75 | + protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs, CancellationToken cancellationToken = default) |
| 76 | + { |
| 77 | + var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; |
| 78 | + var components = processRequest.ComponentStream; |
| 79 | + var reader = new StreamReader(components.Stream); |
| 80 | + var cargoSbom = CargoSbom.FromJson(await reader.ReadToEndAsync(cancellationToken)); |
| 81 | + this.RecordLockfileVersion(cargoSbom.Version); |
| 82 | + this.ProcessCargoSbom(cargoSbom, singleFileComponentRecorder, components); |
| 83 | + } |
| 84 | + |
| 85 | + private void ProcessDependency(CargoSbom sbom, SbomCrate package, ISingleFileComponentRecorder recorder, IComponentStream components, HashSet<int> visitedNodes, CargoComponent parent = null, int depth = 0) |
| 86 | + { |
| 87 | + foreach (var dependency in package.Dependencies) |
| 88 | + { |
| 89 | + var dep = sbom.Crates[dependency.Index]; |
| 90 | + var parentComponent = parent; |
| 91 | + if (ParsePackageIdSpec(dep.Id, out var component)) |
| 92 | + { |
| 93 | + if (component.Source == CratesIoSource) |
| 94 | + { |
| 95 | + parentComponent = component; |
| 96 | + recorder.RegisterUsage(new DetectedComponent(component), isExplicitReferencedDependency: depth == 0, parent?.Id, isDevelopmentDependency: false); |
| 97 | + } |
| 98 | + } |
| 99 | + else |
| 100 | + { |
| 101 | + this.Logger.LogError(null, "Failed to parse Cargo PackageIdSpec '{Id}' in '{Location}'", dep.Id, components.Location); |
| 102 | + recorder.RegisterPackageParseFailure(dep.Id); |
| 103 | + } |
| 104 | + |
| 105 | + if (visitedNodes.Add(dependency.Index)) |
| 106 | + { |
| 107 | + // Skip processing already processed nodes |
| 108 | + this.ProcessDependency(sbom, dep, recorder, components, visitedNodes, parentComponent, depth + 1); |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + private void ProcessCargoSbom(CargoSbom sbom, ISingleFileComponentRecorder recorder, IComponentStream components) |
| 114 | + { |
| 115 | + try |
| 116 | + { |
| 117 | + var visitedNodes = new HashSet<int>(); |
| 118 | + this.ProcessDependency(sbom, sbom.Crates[sbom.Root], recorder, components, visitedNodes); |
| 119 | + } |
| 120 | + catch (Exception e) |
| 121 | + { |
| 122 | + // If something went wrong, just ignore the file |
| 123 | + this.Logger.LogError(e, "Failed to process Cargo SBOM file '{FileLocation}'", components.Location); |
| 124 | + } |
| 125 | + } |
| 126 | +} |
0 commit comments