Repository navigation
feat(spdx): add default-off SPDX 3.0 document detection #1903
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
Merged
Ryan Brandenburg (ryanbrandenburg)
merged 7 commits into
microsoft:main
from
sfoslund:sfoslund/spdx3-detector
Oct 23, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ee00a55
feat(spdx): add default-off SPDX 3 document detector
sfoslund 5b8ffac
fix(spdx): restrict SPDX 3 discovery to *.spdx.json
sfoslund a13acb3
refactor(spdx): scope the new detector to SPDX 3.0
sfoslund b7caee8
refactor(spdx): share common detector file processing
sfoslund 7ea065f
Revert "refactor(spdx): share common detector file processing"
sfoslund 1d2d6d6
fix(spdx): handle version mismatches and oversized documents
sfoslund a7e6eb1
refactor(spdx): replace version regex with explicit validation
sfoslund 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
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
216 changes: 216 additions & 0 deletions
216
src/Microsoft.ComponentDetection.Detectors/spdx/Spdx30ComponentDetector.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,216 @@ | ||
| namespace Microsoft.ComponentDetection.Detectors.Spdx; | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using System.Security.Cryptography; | ||
| 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; | ||
|
|
||
| public class Spdx30ComponentDetector : FileComponentDetector, IDefaultOffComponentDetector | ||
| { | ||
| public Spdx30ComponentDetector( | ||
| IComponentStreamEnumerableFactory componentStreamEnumerableFactory, | ||
| IObservableDirectoryWalkerFactory walkerFactory, | ||
| ILogger<Spdx30ComponentDetector> logger) | ||
| { | ||
| this.ComponentStreamEnumerableFactory = componentStreamEnumerableFactory; | ||
| this.Scanner = walkerFactory; | ||
| this.Logger = logger; | ||
| } | ||
|
|
||
| public override string Id => "SPDX30SBOM"; | ||
|
|
||
| public override IEnumerable<string> Categories => [nameof(DetectorClass.Spdx)]; | ||
|
|
||
| public override IEnumerable<ComponentType> SupportedComponentTypes => [ComponentType.Spdx]; | ||
|
|
||
| public override int Version => 1; | ||
|
|
||
| public override IList<string> SearchPatterns => ["*.spdx.json"]; | ||
|
|
||
| protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs, CancellationToken cancellationToken = default) | ||
| { | ||
| var file = processRequest.ComponentStream; | ||
| this.Logger.LogDebug("Discovered SPDX 3.0 manifest file at: {ManifestLocation}", file.Location); | ||
|
|
||
| try | ||
| { | ||
| // Keep the SHA1 document fingerprint used by SpdxComponent and existing SBOM reference consumers. | ||
| #pragma warning disable CA5350, CA1308 // Existing SPDX document references require lowercase SHA1 checksums. | ||
| var checksum = Convert.ToHexString(await SHA1.HashDataAsync(file.Stream, cancellationToken)).ToLowerInvariant(); | ||
| #pragma warning restore CA5350, CA1308 | ||
| file.Stream.Seek(0, SeekOrigin.Begin); | ||
|
|
||
| using var json = await JsonDocument.ParseAsync(file.Stream, cancellationToken: cancellationToken); | ||
| var component = this.ReadDocument(json.RootElement, checksum, file.Location); | ||
| if (component != null) | ||
| { | ||
| processRequest.SingleFileComponentRecorder.RegisterUsage(new DetectedComponent(component)); | ||
| } | ||
| } | ||
| catch (JsonException e) | ||
|
sfoslund marked this conversation as resolved.
Resolved
|
||
| { | ||
| this.Logger.LogWarning(e, "Unable to parse SPDX 3.0 file at {ManifestLocation}, skipping", file.Location); | ||
| } | ||
| catch (IOException e) | ||
| { | ||
| this.Logger.LogError(e, "Error while reading SPDX 3.0 file at {ManifestLocation}", file.Location); | ||
| } | ||
| catch (Exception e) when (e is OutOfMemoryException or OverflowException) | ||
| { | ||
| this.Logger.LogWarning(e, "SPDX 3.0 file at {ManifestLocation} exceeds available memory or supported size, skipping", file.Location); | ||
| } | ||
| } | ||
|
|
||
| private static bool IsSupportedVersion(string version) | ||
| { | ||
| const string prefix = "3.0."; | ||
| if (!version.StartsWith(prefix, StringComparison.Ordinal) || version.Length == prefix.Length) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| var patchVersion = version[prefix.Length..]; | ||
| return (patchVersion.Length == 1 || patchVersion[0] != '0') | ||
| && patchVersion.All(character => character is >= '0' and <= '9'); | ||
| } | ||
|
|
||
| private static string? ReadString(JsonElement element, string property) | ||
| { | ||
| if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty(property, out var value)) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| if (value.ValueKind != JsonValueKind.String) | ||
| { | ||
| throw new JsonException($"Expected a string for {property}."); | ||
| } | ||
|
|
||
| return value.GetString(); | ||
| } | ||
|
|
||
| private static bool HasType(JsonElement element, string type) | ||
| { | ||
| if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty("type", out var value)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| return value.ValueKind == JsonValueKind.String | ||
| ? value.GetString() == type | ||
| : value.ValueKind == JsonValueKind.Array && value.EnumerateArray().Any(item => item.ValueKind == JsonValueKind.String && item.GetString() == type); | ||
| } | ||
|
|
||
| private static string? ReadId(JsonElement element) => | ||
| element.ValueKind == JsonValueKind.String ? element.GetString() : ReadString(element, "spdxId") ?? ReadString(element, "@id"); | ||
|
|
||
| private static JsonElement Resolve(JsonElement element, IDictionary<string, JsonElement> elements) | ||
| { | ||
| var id = ReadId(element); | ||
| return id != null && elements.TryGetValue(id, out var resolved) ? resolved : element; | ||
| } | ||
|
|
||
| private static IEnumerable<JsonElement> ReadValues(JsonElement element, string property) | ||
| { | ||
| if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty(property, out var value)) | ||
| { | ||
| return []; | ||
| } | ||
|
|
||
| return value.ValueKind == JsonValueKind.Array ? value.EnumerateArray().ToArray() : [value]; | ||
| } | ||
|
|
||
| private static string? ReadCreator(JsonElement creationInfo, string property, string type, IDictionary<string, JsonElement> elements) => | ||
| ReadValues(creationInfo, property) | ||
| .Select(element => Resolve(element, elements)) | ||
| .Where(element => HasType(element, type)) | ||
| .Select(element => ReadString(element, "name")) | ||
| .FirstOrDefault(name => !string.IsNullOrWhiteSpace(name)); | ||
|
|
||
| private SpdxComponent? ReadDocument(JsonElement root, string checksum, string path) | ||
| { | ||
| if (root.ValueKind != JsonValueKind.Object | ||
| || !root.TryGetProperty("@graph", out var graph) | ||
| || graph.ValueKind != JsonValueKind.Array) | ||
| { | ||
| this.Logger.LogDebug("Discovered file at {ManifestLocation} is not an SPDX 3.0 JSON-LD graph, skipping", path); | ||
| return null; | ||
| } | ||
|
|
||
| var documents = graph.EnumerateArray().Where(element => HasType(element, "SpdxDocument")).ToList(); | ||
| if (documents.Count != 1) | ||
| { | ||
| this.Logger.LogWarning("SPDX 3.0 file at {ManifestLocation} must contain exactly one SpdxDocument, skipping", path); | ||
| return null; | ||
| } | ||
|
|
||
| var elements = new Dictionary<string, JsonElement>(StringComparer.Ordinal); | ||
| foreach (var element in graph.EnumerateArray()) | ||
| { | ||
| var id = ReadId(element); | ||
| if (id != null && !elements.TryAdd(id, element)) | ||
|
sfoslund marked this conversation as resolved.
Resolved
|
||
| { | ||
| throw new JsonException($"Duplicate SPDX element identifier: {id}."); | ||
| } | ||
| } | ||
|
|
||
| var document = documents[0]; | ||
| if (!document.TryGetProperty("creationInfo", out var creationInfo)) | ||
| { | ||
| throw new JsonException("SpdxDocument is missing creationInfo."); | ||
| } | ||
|
|
||
| creationInfo = Resolve(creationInfo, elements); | ||
| var version = ReadString(creationInfo, "specVersion") | ||
| ?? throw new JsonException("SpdxDocument creationInfo is missing specVersion."); | ||
|
|
||
| if (!IsSupportedVersion(version)) | ||
| { | ||
| this.Logger.LogDebug("SPDX file at {ManifestLocation} has unsupported specVersion {SpecVersion}, skipping", path, version); | ||
| return null; | ||
| } | ||
|
|
||
| var documentId = ReadId(document); | ||
| if (string.IsNullOrWhiteSpace(documentId) || !Uri.TryCreate(documentId, UriKind.Absolute, out var documentUri)) | ||
| { | ||
| throw new JsonException("SpdxDocument must have an absolute spdxId."); | ||
| } | ||
|
|
||
| var roots = ReadValues(document, "rootElement").Select(ReadId).ToList(); | ||
| if (roots.Any(id => string.IsNullOrWhiteSpace(id))) | ||
| { | ||
| throw new JsonException("SpdxDocument contains an invalid rootElement."); | ||
| } | ||
|
|
||
| if (roots.Count > 1) | ||
| { | ||
| this.Logger.LogWarning("SPDX file at {ManifestLocation} has more than one rootElement, first will be selected as root element.", path); | ||
|
sfoslund marked this conversation as resolved.
Resolved
|
||
| } | ||
| else if (roots.Count == 0) | ||
| { | ||
| this.Logger.LogWarning("SPDX file at {ManifestLocation} has no rootElement, considering the SpdxDocument as the root element.", path); | ||
|
sfoslund marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| // SPDX 3 has no documentNamespace, and name is optional; the document IRI identifies the document. | ||
| var name = ReadString(document, "name"); | ||
| return new SpdxComponent( | ||
| $"SPDX-{version}", | ||
| documentUri, | ||
| string.IsNullOrWhiteSpace(name) ? documentId : name, | ||
| checksum, | ||
| roots.FirstOrDefault() ?? documentId, | ||
| path) | ||
| { | ||
| CreatorTool = ReadCreator(creationInfo, "createdUsing", "Tool", elements), | ||
| CreatorOrganization = ReadCreator(creationInfo, "createdBy", "Organization", elements), | ||
| }; | ||
| } | ||
| } | ||
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
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.
Uh oh!
There was an error while loading. Please reload this page.