Add unit tests for SBOM ingestion and transformation
Some checks failed
Docs CI / lint-and-preview (push) Has been cancelled

- Implement `SbomIngestServiceCollectionExtensionsTests` to verify the SBOM ingestion pipeline exports snapshots correctly.
- Create `SbomIngestTransformerTests` to ensure the transformation produces expected nodes and edges, including deduplication of license nodes and normalization of timestamps.
- Add `SbomSnapshotExporterTests` to test the export functionality for manifest, adjacency, nodes, and edges.
- Introduce `VexOverlayTransformerTests` to validate the transformation of VEX nodes and edges.
- Set up project file for the test project with necessary dependencies and configurations.
- Include JSON fixture files for testing purposes.
This commit is contained in:
master
2025-11-04 07:49:39 +02:00
parent f72c5c513a
commit 2eb6852d34
491 changed files with 39445 additions and 3917 deletions

View File

@@ -0,0 +1,164 @@
using System.Text.Json.Nodes;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using StellaOps.Findings.Ledger.Domain;
using StellaOps.Findings.Ledger.Hashing;
using StellaOps.Findings.Ledger.Infrastructure.Policy;
using StellaOps.Findings.Ledger.Services;
using Xunit;
namespace StellaOps.Findings.Ledger.Tests;
public sealed class InlinePolicyEvaluationServiceTests
{
private readonly InlinePolicyEvaluationService _service = new(NullLogger<InlinePolicyEvaluationService>.Instance);
[Fact]
public async Task EvaluateAsync_UsesPayloadValues_WhenPresent()
{
var payload = new JsonObject
{
["status"] = "triaged",
["severity"] = 5.2,
["labels"] = new JsonObject
{
["kev"] = true,
["runtime"] = "exposed"
},
["labelsRemove"] = new JsonArray("deprecated"),
["explainRef"] = "explain://tenant/findings/1",
["rationaleRefs"] = new JsonArray("explain://tenant/findings/1", "policy://tenant/pol/version/rationale")
};
var existingProjection = new FindingProjection(
"tenant",
"finding",
"policy-sha",
"affected",
7.1m,
new JsonObject { ["deprecated"] = "true" },
Guid.NewGuid(),
null,
new JsonArray("explain://existing"),
DateTimeOffset.UtcNow,
string.Empty);
var record = CreateRecord(payload);
var result = await _service.EvaluateAsync(record, existingProjection, default);
result.Status.Should().Be("triaged");
result.Severity.Should().Be(5.2m);
result.Labels["kev"]!.GetValue<bool>().Should().BeTrue();
result.Labels.ContainsKey("deprecated").Should().BeFalse();
result.Labels["runtime"]!.GetValue<string>().Should().Be("exposed");
result.ExplainRef.Should().Be("explain://tenant/findings/1");
result.Rationale.Should().HaveCount(2);
result.Rationale[0]!.GetValue<string>().Should().Be("explain://tenant/findings/1");
result.Rationale[1]!.GetValue<string>().Should().Be("policy://tenant/pol/version/rationale");
}
[Fact]
public async Task EvaluateAsync_FallsBack_WhenEventMissing()
{
var existingRationale = new JsonArray("explain://existing/rationale");
var existingProjection = new FindingProjection(
"tenant",
"finding",
"policy-sha",
"accepted_risk",
3.4m,
new JsonObject { ["runtime"] = "contained" },
Guid.NewGuid(),
"explain://existing",
existingRationale,
DateTimeOffset.UtcNow,
string.Empty);
var record = new LedgerEventRecord(
"tenant",
Guid.NewGuid(),
1,
Guid.NewGuid(),
"finding.status_changed",
"policy-sha",
"finding",
"artifact",
null,
"user:alice",
"operator",
DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow,
new JsonObject(),
"hash",
"prev",
"leaf",
"{}"
);
var result = await _service.EvaluateAsync(record, existingProjection, default);
result.Status.Should().Be("accepted_risk");
result.Severity.Should().Be(3.4m);
result.Labels["runtime"]!.GetValue<string>().Should().Be("contained");
result.ExplainRef.Should().Be("explain://existing");
result.Rationale.Should().HaveCount(1);
result.Rationale[0]!.GetValue<string>().Should().Be("explain://existing/rationale");
}
private static LedgerEventRecord CreateRecord(JsonObject payload)
{
var eventObject = new JsonObject
{
["id"] = Guid.NewGuid().ToString(),
["type"] = "finding.status_changed",
["tenant"] = "tenant",
["chainId"] = Guid.NewGuid().ToString(),
["sequence"] = 10,
["policyVersion"] = "policy-sha",
["artifactId"] = "artifact",
["finding"] = new JsonObject
{
["id"] = "finding",
["artifactId"] = "artifact",
["vulnId"] = "CVE-0000-0001"
},
["actor"] = new JsonObject
{
["id"] = "user:alice",
["type"] = "operator"
},
["occurredAt"] = "2025-11-04T12:00:00.000Z",
["recordedAt"] = "2025-11-04T12:00:01.000Z",
["payload"] = payload.DeepClone()
};
var envelope = new JsonObject
{
["event"] = eventObject
};
var canonical = LedgerCanonicalJsonSerializer.Canonicalize(envelope);
var canonicalJson = LedgerCanonicalJsonSerializer.Serialize(canonical);
return new LedgerEventRecord(
"tenant",
Guid.Parse(eventObject["chainId"]!.GetValue<string>()),
10,
Guid.Parse(eventObject["id"]!.GetValue<string>()),
eventObject["type"]!.GetValue<string>(),
eventObject["policyVersion"]!.GetValue<string>(),
eventObject["finding"]!["id"]!.GetValue<string>(),
eventObject["artifactId"]!.GetValue<string>(),
null,
eventObject["actor"]!["id"]!.GetValue<string>(),
eventObject["actor"]!["type"]!.GetValue<string>(),
DateTimeOffset.Parse(eventObject["occurredAt"]!.GetValue<string>()),
DateTimeOffset.Parse(eventObject["recordedAt"]!.GetValue<string>()),
canonical,
"hash",
"prev",
"leaf",
canonicalJson);
}
}

View File

@@ -0,0 +1,204 @@
using System.Globalization;
using System.Text.Json.Nodes;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using StellaOps.Findings.Ledger.Domain;
using StellaOps.Findings.Ledger.Hashing;
using StellaOps.Findings.Ledger.Infrastructure;
using StellaOps.Findings.Ledger.Infrastructure.InMemory;
using StellaOps.Findings.Ledger.Infrastructure.Merkle;
using StellaOps.Findings.Ledger.Services;
using Xunit;
namespace StellaOps.Findings.Ledger.Tests;
public sealed class LedgerEventWriteServiceTests
{
private readonly InMemoryLedgerEventRepository _repository = new();
private readonly NullMerkleAnchorScheduler _scheduler = new();
private readonly LedgerEventWriteService _service;
public LedgerEventWriteServiceTests()
{
_service = new LedgerEventWriteService(_repository, _scheduler, NullLogger<LedgerEventWriteService>.Instance);
}
[Fact]
public async Task AppendAsync_ComputesExpectedHashes()
{
var draft = CreateDraft();
var result = await _service.AppendAsync(draft, CancellationToken.None);
result.Status.Should().Be(LedgerWriteStatus.Success);
result.Record.Should().NotBeNull();
var canonicalEnvelope = LedgerCanonicalJsonSerializer.Canonicalize(draft.CanonicalEnvelope);
var expectedHashes = LedgerHashing.ComputeHashes(canonicalEnvelope, draft.SequenceNumber);
result.Record!.EventHash.Should().Be(expectedHashes.EventHash);
result.Record.MerkleLeafHash.Should().Be(expectedHashes.MerkleLeafHash);
result.Record.PreviousHash.Should().Be(LedgerEventConstants.EmptyHash);
}
[Fact]
public async Task AppendAsync_ReturnsConflict_WhenSequenceOutOfOrder()
{
var initial = CreateDraft();
await _service.AppendAsync(initial, CancellationToken.None);
var second = CreateDraft(sequenceNumber: 44, eventId: Guid.NewGuid());
Assert.NotEqual(initial.EventId, second.EventId);
var result = await _service.AppendAsync(second, CancellationToken.None);
result.Status.Should().Be(LedgerWriteStatus.Conflict);
result.Errors.Should().NotBeEmpty();
}
[Fact]
public async Task AppendAsync_ReturnsIdempotent_WhenExistingRecordMatches()
{
var draft = CreateDraft();
var existingRecord = CreateRecordFromDraft(draft, LedgerEventConstants.EmptyHash);
var repository = new StubLedgerEventRepository(existingRecord);
var scheduler = new CapturingMerkleScheduler();
var service = new LedgerEventWriteService(repository, scheduler, NullLogger<LedgerEventWriteService>.Instance);
var result = await service.AppendAsync(draft, CancellationToken.None);
result.Status.Should().Be(LedgerWriteStatus.Idempotent);
scheduler.Enqueued.Should().BeFalse();
repository.AppendWasCalled.Should().BeFalse();
}
private static LedgerEventDraft CreateDraft(long sequenceNumber = 1, Guid? eventId = null)
{
var eventGuid = eventId ?? Guid.Parse("3ac1f4ef-3c26-4b0d-91d4-6a6d3a5bde10");
var payload = new JsonObject
{
["previousStatus"] = "affected",
["status"] = "triaged",
["justification"] = "Ticket SEC-1234 created",
["ticket"] = new JsonObject
{
["id"] = "SEC-1234",
["url"] = "https://tracker.example/sec-1234"
}
};
var occurredAt = DateTimeOffset.Parse("2025-11-03T15:12:05.123Z", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
var recordedAt = DateTimeOffset.Parse("2025-11-03T15:12:06.001Z", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
var eventObject = new JsonObject
{
["id"] = eventGuid.ToString(),
["type"] = "finding.status_changed",
["tenant"] = "tenant-a",
["chainId"] = "5fa2b970-9da2-4ef4-9a63-463c5d98d3cc",
["sequence"] = sequenceNumber,
["policyVersion"] = "sha256:5f38c7887d4a4bb887ce89c393c7a2e23e6e708fda310f9f3ff2a2a0b4dffbdf",
["finding"] = new JsonObject
{
["id"] = "artifact:sha256:3f1e2d9c7b1a0f6534d1b6f998d7a5c3ef9e0ab92f4c1d2e3f5a6b7c8d9e0f1a|pkg:cpe:/o:vendor:product",
["artifactId"] = "sha256:3f1e2d9c7b1a0f6534d1b6f998d7a5c3ef9e0ab92f4c1d2e3f5a6b7c8d9e0f1a",
["vulnId"] = "CVE-2025-1234"
},
["artifactId"] = "sha256:3f1e2d9c7b1a0f6534d1b6f998d7a5c3ef9e0ab92f4c1d2e3f5a6b7c8d9e0f1a",
["actor"] = new JsonObject
{
["id"] = "user:alice@tenant",
["type"] = "operator"
},
["occurredAt"] = occurredAt.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"),
["recordedAt"] = recordedAt.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"),
["payload"] = payload
};
eventObject["sourceRunId"] = "8f89a703-94cd-4e9d-8a75-2f407c4bee7f";
var envelope = new JsonObject
{
["event"] = eventObject
};
var draft = new LedgerEventDraft(
TenantId: "tenant-a",
ChainId: Guid.Parse("5fa2b970-9da2-4ef4-9a63-463c5d98d3cc"),
SequenceNumber: sequenceNumber,
EventId: Guid.Parse("3ac1f4ef-3c26-4b0d-91d4-6a6d3a5bde10"),
EventType: "finding.status_changed",
PolicyVersion: "sha256:5f38c7887d4a4bb887ce89c393c7a2e23e6e708fda310f9f3ff2a2a0b4dffbdf",
FindingId: "artifact:sha256:3f1e2d9c7b1a0f6534d1b6f998d7a5c3ef9e0ab92f4c1d2e3f5a6b7c8d9e0f1a|pkg:cpe:/o:vendor:product",
ArtifactId: "sha256:3f1e2d9c7b1a0f6534d1b6f998d7a5c3ef9e0ab92f4c1d2e3f5a6b7c8d9e0f1a",
SourceRunId: Guid.Parse("8f89a703-94cd-4e9d-8a75-2f407c4bee7f"),
ActorId: "user:alice@tenant",
ActorType: "operator",
OccurredAt: occurredAt,
RecordedAt: recordedAt,
Payload: payload,
CanonicalEnvelope: envelope,
ProvidedPreviousHash: null);
return draft with { EventId = eventGuid };
}
private static LedgerEventRecord CreateRecordFromDraft(LedgerEventDraft draft, string previousHash)
{
var canonicalEnvelope = LedgerCanonicalJsonSerializer.Canonicalize(draft.CanonicalEnvelope);
var hashResult = LedgerHashing.ComputeHashes(canonicalEnvelope, draft.SequenceNumber);
var eventBody = (JsonObject)canonicalEnvelope.DeepClone();
return new LedgerEventRecord(
draft.TenantId,
draft.ChainId,
draft.SequenceNumber,
draft.EventId,
draft.EventType,
draft.PolicyVersion,
draft.FindingId,
draft.ArtifactId,
draft.SourceRunId,
draft.ActorId,
draft.ActorType,
draft.OccurredAt,
draft.RecordedAt,
eventBody,
hashResult.EventHash,
previousHash,
hashResult.MerkleLeafHash,
hashResult.CanonicalJson);
}
private sealed class StubLedgerEventRepository : ILedgerEventRepository
{
private readonly LedgerEventRecord? _existing;
public StubLedgerEventRepository(LedgerEventRecord? existing)
{
_existing = existing;
}
public bool AppendWasCalled { get; private set; }
public Task AppendAsync(LedgerEventRecord record, CancellationToken cancellationToken)
{
AppendWasCalled = true;
return Task.CompletedTask;
}
public Task<LedgerEventRecord?> GetByEventIdAsync(string tenantId, Guid eventId, CancellationToken cancellationToken)
=> Task.FromResult(_existing);
public Task<LedgerChainHead?> GetChainHeadAsync(string tenantId, Guid chainId, CancellationToken cancellationToken)
=> Task.FromResult<LedgerChainHead?>(null);
}
private sealed class CapturingMerkleScheduler : IMerkleAnchorScheduler
{
public bool Enqueued { get; private set; }
public Task EnqueueAsync(LedgerEventRecord record, CancellationToken cancellationToken)
{
Enqueued = true;
return Task.CompletedTask;
}
}
}

View File

@@ -0,0 +1,205 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using FluentAssertions;
using StellaOps.Findings.Ledger.Domain;
using StellaOps.Findings.Ledger.Hashing;
using StellaOps.Findings.Ledger.Infrastructure.Policy;
using StellaOps.Findings.Ledger.Services;
using Xunit;
namespace StellaOps.Findings.Ledger.Tests;
public sealed class LedgerProjectionReducerTests
{
[Fact]
public void Reduce_WhenFindingCreated_InitialisesProjection()
{
var payload = new JsonObject
{
["status"] = "triaged",
["severity"] = 6.5,
["labels"] = new JsonObject
{
["kev"] = true,
["runtime"] = "exposed"
},
["explainRef"] = "explain://tenant-a/finding/123"
};
var record = CreateRecord(LedgerEventConstants.EventFindingCreated, payload);
var evaluation = new PolicyEvaluationResult(
"triaged",
6.5m,
(JsonObject)payload["labels"]!.DeepClone(),
payload["explainRef"]!.GetValue<string>(),
new JsonArray(payload["explainRef"]!.GetValue<string>()));
var result = LedgerProjectionReducer.Reduce(record, current: null, evaluation);
result.Projection.Status.Should().Be("triaged");
result.Projection.Severity.Should().Be(6.5m);
result.Projection.Labels["kev"]!.GetValue<bool>().Should().BeTrue();
result.Projection.Labels["runtime"]!.GetValue<string>().Should().Be("exposed");
result.Projection.ExplainRef.Should().Be("explain://tenant-a/finding/123");
result.Projection.PolicyRationale.Should().ContainSingle()
.Which!.GetValue<string>().Should().Be("explain://tenant-a/finding/123");
result.Projection.CycleHash.Should().NotBeNullOrWhiteSpace();
ProjectionHashing.ComputeCycleHash(result.Projection).Should().Be(result.Projection.CycleHash);
result.History.Status.Should().Be("triaged");
result.History.Severity.Should().Be(6.5m);
result.Action.Should().BeNull();
}
[Fact]
public void Reduce_StatusChange_ProducesHistoryAndAction()
{
var existing = new FindingProjection(
"tenant-a",
"finding-1",
"policy-v1",
"affected",
5.0m,
new JsonObject(),
Guid.NewGuid(),
null,
DateTimeOffset.UtcNow,
string.Empty);
var existingHash = ProjectionHashing.ComputeCycleHash(existing);
existing = existing with { CycleHash = existingHash };
var payload = new JsonObject
{
["status"] = "accepted_risk",
["justification"] = "Approved by CISO"
};
var record = CreateRecord(LedgerEventConstants.EventFindingStatusChanged, payload);
var evaluation = new PolicyEvaluationResult(
"accepted_risk",
existing.Severity,
(JsonObject)existing.Labels.DeepClone(),
null,
new JsonArray());
var result = LedgerProjectionReducer.Reduce(record, existing, evaluation);
result.Projection.Status.Should().Be("accepted_risk");
result.History.Status.Should().Be("accepted_risk");
result.History.Comment.Should().Be("Approved by CISO");
result.Action.Should().NotBeNull();
result.Action!.ActionType.Should().Be("status_change");
result.Action.Payload["justification"]!.GetValue<string>().Should().Be("Approved by CISO");
}
[Fact]
public void Reduce_LabelUpdates_RemoveKeys()
{
var labels = new JsonObject
{
["kev"] = true,
["runtime"] = "exposed"
};
var existing = new FindingProjection(
"tenant-a",
"finding-1",
"policy-v1",
"triaged",
7.1m,
labels,
Guid.NewGuid(),
null,
DateTimeOffset.UtcNow,
string.Empty);
existing = existing with { CycleHash = ProjectionHashing.ComputeCycleHash(existing) };
var payload = new JsonObject
{
["labels"] = new JsonObject
{
["runtime"] = "contained",
["priority"] = "p1"
},
["labelsRemove"] = new JsonArray("kev")
};
var record = CreateRecord(LedgerEventConstants.EventFindingTagUpdated, payload);
var evaluation = new PolicyEvaluationResult(
"triaged",
existing.Severity,
(JsonObject)payload["labels"]!.DeepClone(),
null,
new JsonArray());
var result = LedgerProjectionReducer.Reduce(record, existing, evaluation);
result.Projection.Labels.ContainsKey("kev").Should().BeFalse();
result.Projection.Labels["runtime"]!.GetValue<string>().Should().Be("contained");
result.Projection.Labels["priority"]!.GetValue<string>().Should().Be("p1");
}
private static LedgerEventRecord CreateRecord(string eventType, JsonObject payload)
{
var envelope = new JsonObject
{
["event"] = new JsonObject
{
["id"] = Guid.NewGuid().ToString(),
["type"] = eventType,
["tenant"] = "tenant-a",
["chainId"] = Guid.NewGuid().ToString(),
["sequence"] = 1,
["policyVersion"] = "policy-v1",
["artifactId"] = "artifact-1",
["finding"] = new JsonObject
{
["id"] = "finding-1",
["artifactId"] = "artifact-1",
["vulnId"] = "CVE-2025-0001"
},
["actor"] = new JsonObject
{
["id"] = "user:alice",
["type"] = "operator"
},
["occurredAt"] = "2025-11-03T12:00:00.000Z",
["recordedAt"] = "2025-11-03T12:00:05.000Z",
["payload"] = payload.DeepClone()
}
};
var canonical = LedgerCanonicalJsonSerializer.Canonicalize(envelope);
var canonicalJson = LedgerCanonicalJsonSerializer.Serialize(canonical);
return new LedgerEventRecord(
"tenant-a",
Guid.Parse(canonical["event"]!["chainId"]!.GetValue<string>()),
1,
Guid.Parse(canonical["event"]!["id"]!.GetValue<string>()),
eventType,
canonical["event"]!["policyVersion"]!.GetValue<string>(),
canonical["event"]!["finding"]!["id"]!.GetValue<string>(),
canonical["event"]!["artifactId"]!.GetValue<string>(),
null,
canonical["event"]!["actor"]!["id"]!.GetValue<string>(),
canonical["event"]!["actor"]!["type"]!.GetValue<string>(),
DateTimeOffset.Parse(canonical["event"]!["occurredAt"]!.GetValue<string>()),
DateTimeOffset.Parse(canonical["event"]!["recordedAt"]!.GetValue<string>()),
canonical,
ComputeSha256Hex(canonicalJson),
LedgerEventConstants.EmptyHash,
ComputeSha256Hex("placeholder-1"),
canonicalJson);
}
private static string ComputeSha256Hex(string input)
{
var bytes = Encoding.UTF8.GetBytes(input);
var hashBytes = SHA256.HashData(bytes);
return Convert.ToHexString(hashBytes).ToLowerInvariant();
}
}

View File

@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\StellaOps.Findings.Ledger\StellaOps.Findings.Ledger.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.NET.Test.Sdk" Version="17.14.0" />
<PackageReference Update="xunit" Version="2.9.2" />
<PackageReference Update="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
</ItemGroup>
</Project>