consolidate the tests locations

This commit is contained in:
StellaOps Bot
2025-12-26 01:48:24 +02:00
parent 17613acf57
commit 39359da171
2031 changed files with 2607 additions and 476 deletions

View File

@@ -1,190 +0,0 @@
# tests/AGENTS.md
## Overview
This document provides guidance for AI agents and developers working in the `tests/` directory of the StellaOps codebase.
## Directory Structure
```
tests/
├── acceptance/ # Acceptance test suites
├── AirGap/ # Air-gap specific tests
├── authority/ # Authority module tests
├── chaos/ # Chaos engineering tests
├── e2e/ # End-to-end test suites
├── EvidenceLocker/ # Evidence storage tests
├── fixtures/ # Shared test fixtures
│ ├── offline-bundle/ # Offline bundle for air-gap tests
│ ├── images/ # Container image tarballs
│ └── sboms/ # Sample SBOM documents
├── Graph/ # Graph module tests
├── integration/ # Integration test suites
├── interop/ # Interoperability tests
├── load/ # Load testing scripts
├── native/ # Native code tests
├── offline/ # Offline operation tests
├── plugins/ # Plugin tests
├── Policy/ # Policy module tests
├── Provenance/ # Provenance/attestation tests
├── reachability/ # Reachability analysis tests
├── Replay/ # Replay functionality tests
├── security/ # Security tests (OWASP)
├── shared/ # Shared test utilities
└── Vex/ # VEX processing tests
```
## Test Categories
### When writing tests, use appropriate category traits:
```csharp
[Trait("Category", "Unit")] // Fast, isolated unit tests
[Trait("Category", "Integration")] // Tests requiring infrastructure
[Trait("Category", "E2E")] // Full end-to-end workflows
[Trait("Category", "AirGap")] // Must work without network
[Trait("Category", "Interop")] // Third-party tool compatibility
[Trait("Category", "Performance")] // Performance benchmarks
[Trait("Category", "Chaos")] // Failure injection tests
[Trait("Category", "Security")] // Security-focused tests
```
## Key Patterns
### 1. PostgreSQL Integration Tests
Use the shared fixture from `StellaOps.Infrastructure.Postgres.Testing`:
```csharp
public class MyIntegrationTests : IClassFixture<MyPostgresFixture>
{
private readonly MyPostgresFixture _fixture;
public MyIntegrationTests(MyPostgresFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task MyTest()
{
// _fixture.ConnectionString is available
// _fixture.TruncateAllTablesAsync() for cleanup
}
}
```
### 2. Air-Gap Tests
Inherit from `NetworkIsolatedTestBase` for network-free tests:
```csharp
[Trait("Category", "AirGap")]
public class OfflineTests : NetworkIsolatedTestBase
{
[Fact]
public async Task Test_WorksOffline()
{
// Test implementation
AssertNoNetworkCalls(); // Fails if network accessed
}
protected string GetOfflineBundlePath() =>
Path.Combine(AppContext.BaseDirectory, "fixtures", "offline-bundle");
}
```
### 3. Determinism Tests
Use `DeterminismVerifier` to ensure reproducibility:
```csharp
[Fact]
public void Output_IsDeterministic()
{
var verifier = new DeterminismVerifier();
var result = verifier.Verify(myObject, iterations: 10);
result.IsDeterministic.Should().BeTrue();
}
```
### 4. Golden Corpus Tests
Reference cases from `bench/golden-corpus/`:
```csharp
[Theory]
[MemberData(nameof(GetCorpusCases))]
public async Task Corpus_Case_Passes(string caseId)
{
var testCase = CorpusLoader.Load(caseId);
var result = await ProcessAsync(testCase.Input);
result.Should().BeEquivalentTo(testCase.Expected);
}
```
## Rules for Test Development
### DO:
1. **Tag tests with appropriate categories** for filtering
2. **Use Testcontainers** for infrastructure dependencies
3. **Inherit from shared fixtures** to avoid duplication
4. **Assert no network calls** in air-gap tests
5. **Verify determinism** for any serialization output
6. **Use property-based tests** (FsCheck) for invariants
7. **Document test purpose** in method names
### DON'T:
1. **Don't skip tests** without documenting why
2. **Don't use Thread.Sleep** - use proper async waits
3. **Don't hardcode paths** - use `AppContext.BaseDirectory`
4. **Don't make network calls** in non-interop tests
5. **Don't depend on test execution order**
6. **Don't leave test data in shared databases**
## Test Infrastructure
### Required Services (CI)
```yaml
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_PASSWORD: test
valkey:
image: valkey/valkey:7-alpine
```
### Environment Variables
| Variable | Purpose | Default |
|----------|---------|---------|
| `STELLAOPS_OFFLINE_MODE` | Enable offline mode | `false` |
| `STELLAOPS_OFFLINE_BUNDLE` | Path to offline bundle | - |
| `STELLAOPS_TEST_POSTGRES` | PostgreSQL connection | Testcontainers |
| `STELLAOPS_TEST_VALKEY` | Valkey connection | Testcontainers |
## Related Sprints
| Sprint | Topic |
|--------|-------|
| 5100.0001.0001 | Run Manifest Schema |
| 5100.0001.0002 | Evidence Index Schema |
| 5100.0001.0004 | Golden Corpus Expansion |
| 5100.0002.0001 | Canonicalization Utilities |
| 5100.0002.0002 | Replay Runner Service |
| 5100.0003.0001 | SBOM Interop Round-Trip |
| 5100.0003.0002 | No-Egress Enforcement |
| 5100.0005.0001 | Router Chaos Suite |
## Contact
For test infrastructure questions, see:
- `docs/19_TEST_SUITE_OVERVIEW.md`
- `docs/implplan/SPRINT_5100_0000_0000_epic_summary.md`
- Sprint files in `docs/implplan/SPRINT_5100_*.md`

View File

@@ -1,6 +0,0 @@
# AirGap Tests
## Notes
- Tests now run entirely against in-memory stores (no MongoDB or external services required).
- Keep fixtures deterministic: stable ordering, UTC timestamps, fixed seeds where applicable.
- Sealed-mode and staleness tests rely on local fixture bundles only; no network access is needed.

View File

@@ -1,163 +0,0 @@
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using StellaOps.AirGap.Controller.Domain;
using StellaOps.AirGap.Controller.Options;
using StellaOps.AirGap.Controller.Services;
using StellaOps.AirGap.Controller.Stores;
using StellaOps.AirGap.Importer.Validation;
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Services;
using Xunit;
namespace StellaOps.AirGap.Controller.Tests;
public class AirGapStartupDiagnosticsHostedServiceTests
{
[Fact]
public async Task Blocks_when_allowlist_missing_for_sealed_state()
{
var now = DateTimeOffset.UtcNow;
var store = new InMemoryAirGapStateStore();
await store.SetAsync(new AirGapState
{
TenantId = "default",
Sealed = true,
PolicyHash = "policy-x",
TimeAnchor = new TimeAnchor(now, "rough", "rough", "fp", "digest"),
StalenessBudget = new StalenessBudget(60, 120)
});
var trustDir = CreateTrustMaterial();
var options = BuildOptions(trustDir);
options.EgressAllowlist = null; // simulate missing config section
var service = CreateService(store, options, now);
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => service.StartAsync(CancellationToken.None));
Assert.Contains("egress-allowlist-missing", ex.Message);
}
[Fact]
public async Task Passes_when_materials_present_and_anchor_fresh()
{
var now = DateTimeOffset.UtcNow;
var store = new InMemoryAirGapStateStore();
await store.SetAsync(new AirGapState
{
TenantId = "default",
Sealed = true,
PolicyHash = "policy-ok",
TimeAnchor = new TimeAnchor(now.AddMinutes(-1), "rough", "rough", "fp", "digest"),
StalenessBudget = new StalenessBudget(300, 600)
});
var trustDir = CreateTrustMaterial();
var options = BuildOptions(trustDir, new[] { "127.0.0.1/32" });
var service = CreateService(store, options, now);
await service.StartAsync(CancellationToken.None); // should not throw
}
[Fact]
public async Task Blocks_when_anchor_is_stale()
{
var now = DateTimeOffset.UtcNow;
var store = new InMemoryAirGapStateStore();
await store.SetAsync(new AirGapState
{
TenantId = "default",
Sealed = true,
PolicyHash = "policy-stale",
TimeAnchor = new TimeAnchor(now.AddHours(-2), "rough", "rough", "fp", "digest"),
StalenessBudget = new StalenessBudget(60, 90)
});
var trustDir = CreateTrustMaterial();
var options = BuildOptions(trustDir, new[] { "10.0.0.0/24" });
var service = CreateService(store, options, now);
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => service.StartAsync(CancellationToken.None));
Assert.Contains("time-anchor-stale", ex.Message);
}
[Fact]
public async Task Blocks_when_rotation_pending_without_dual_approval()
{
var now = DateTimeOffset.UtcNow;
var store = new InMemoryAirGapStateStore();
await store.SetAsync(new AirGapState
{
TenantId = "default",
Sealed = true,
PolicyHash = "policy-rot",
TimeAnchor = new TimeAnchor(now, "rough", "rough", "fp", "digest"),
StalenessBudget = new StalenessBudget(120, 240)
});
var trustDir = CreateTrustMaterial();
var options = BuildOptions(trustDir, new[] { "10.10.0.0/16" });
options.Rotation.PendingKeys["k-new"] = Convert.ToBase64String(new byte[] { 1, 2, 3 });
options.Rotation.ActiveKeys["k-old"] = Convert.ToBase64String(new byte[] { 9, 9, 9 });
options.Rotation.ApproverIds.Add("approver-1");
var service = CreateService(store, options, now);
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => service.StartAsync(CancellationToken.None));
Assert.Contains("rotation:rotation-dual-approval-required", ex.Message);
}
private static AirGapStartupOptions BuildOptions(string trustDir, string[]? allowlist = null)
{
return new AirGapStartupOptions
{
TenantId = "default",
EgressAllowlist = allowlist,
Trust = new TrustMaterialOptions
{
RootJsonPath = Path.Combine(trustDir, "root.json"),
SnapshotJsonPath = Path.Combine(trustDir, "snapshot.json"),
TimestampJsonPath = Path.Combine(trustDir, "timestamp.json")
}
};
}
private static AirGapStartupDiagnosticsHostedService CreateService(IAirGapStateStore store, AirGapStartupOptions options, DateTimeOffset now)
{
return new AirGapStartupDiagnosticsHostedService(
store,
new StalenessCalculator(),
new FixedTimeProvider(now),
Microsoft.Extensions.Options.Options.Create(options),
NullLogger<AirGapStartupDiagnosticsHostedService>.Instance,
new AirGapTelemetry(NullLogger<AirGapTelemetry>.Instance),
new TufMetadataValidator(),
new RootRotationPolicy());
}
private static string CreateTrustMaterial()
{
var dir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "airgap-trust-" + Guid.NewGuid().ToString("N"))).FullName;
var expires = DateTimeOffset.UtcNow.AddDays(1).ToString("O");
const string hash = "abc123";
File.WriteAllText(Path.Combine(dir, "root.json"), $"{{\"version\":1,\"expiresUtc\":\"{expires}\"}}");
File.WriteAllText(Path.Combine(dir, "snapshot.json"), $"{{\"version\":1,\"expiresUtc\":\"{expires}\",\"meta\":{{\"snapshot\":{{\"hashes\":{{\"sha256\":\"{hash}\"}}}}}}}}");
File.WriteAllText(Path.Combine(dir, "timestamp.json"), $"{{\"version\":1,\"expiresUtc\":\"{expires}\",\"snapshot\":{{\"meta\":{{\"hashes\":{{\"sha256\":\"{hash}\"}}}}}}}}");
return dir;
}
private sealed class FixedTimeProvider : TimeProvider
{
private readonly DateTimeOffset _now;
public FixedTimeProvider(DateTimeOffset now)
{
_now = now;
}
public override DateTimeOffset GetUtcNow() => _now;
}
}

View File

@@ -1,120 +0,0 @@
using StellaOps.AirGap.Controller.Services;
using StellaOps.AirGap.Controller.Stores;
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Services;
using Xunit;
namespace StellaOps.AirGap.Controller.Tests;
public class AirGapStateServiceTests
{
private readonly AirGapStateService _service;
private readonly InMemoryAirGapStateStore _store = new();
private readonly StalenessCalculator _calculator = new();
public AirGapStateServiceTests()
{
_service = new AirGapStateService(_store, _calculator);
}
[Fact]
public async Task Seal_sets_state_and_computes_staleness()
{
var now = DateTimeOffset.UtcNow;
var anchor = new TimeAnchor(now.AddMinutes(-2), "roughtime", "roughtime", "fp", "digest");
var budget = new StalenessBudget(60, 120);
await _service.SealAsync("tenant-a", "policy-1", anchor, budget, now);
var status = await _service.GetStatusAsync("tenant-a", now);
Assert.True(status.State.Sealed);
Assert.Equal("policy-1", status.State.PolicyHash);
Assert.Equal("tenant-a", status.State.TenantId);
Assert.True(status.Staleness.AgeSeconds > 0);
Assert.True(status.Staleness.IsWarning);
Assert.Equal(120 - status.Staleness.AgeSeconds, status.Staleness.SecondsRemaining);
}
[Fact]
public async Task Unseal_clears_sealed_flag_and_updates_timestamp()
{
var now = DateTimeOffset.UtcNow;
await _service.SealAsync("default", "hash", TimeAnchor.Unknown, StalenessBudget.Default, now);
var later = now.AddMinutes(1);
await _service.UnsealAsync("default", later);
var status = await _service.GetStatusAsync("default", later);
Assert.False(status.State.Sealed);
Assert.Equal(later, status.State.LastTransitionAt);
}
[Fact]
public async Task Seal_persists_drift_baseline_seconds()
{
var now = DateTimeOffset.UtcNow;
var anchor = new TimeAnchor(now.AddMinutes(-5), "roughtime", "roughtime", "fp", "digest");
var budget = StalenessBudget.Default;
var state = await _service.SealAsync("tenant-drift", "policy-drift", anchor, budget, now);
Assert.Equal(300, state.DriftBaselineSeconds); // 5 minutes = 300 seconds
}
[Fact]
public async Task Seal_creates_default_content_budgets_when_not_provided()
{
var now = DateTimeOffset.UtcNow;
var anchor = new TimeAnchor(now.AddMinutes(-1), "roughtime", "roughtime", "fp", "digest");
var budget = new StalenessBudget(120, 240);
var state = await _service.SealAsync("tenant-content", "policy-content", anchor, budget, now);
Assert.Contains("advisories", state.ContentBudgets.Keys);
Assert.Contains("vex", state.ContentBudgets.Keys);
Assert.Contains("policy", state.ContentBudgets.Keys);
Assert.Equal(budget, state.ContentBudgets["advisories"]);
}
[Fact]
public async Task Seal_uses_provided_content_budgets()
{
var now = DateTimeOffset.UtcNow;
var anchor = new TimeAnchor(now.AddMinutes(-1), "roughtime", "roughtime", "fp", "digest");
var budget = StalenessBudget.Default;
var contentBudgets = new Dictionary<string, StalenessBudget>
{
{ "advisories", new StalenessBudget(30, 60) },
{ "vex", new StalenessBudget(60, 120) }
};
var state = await _service.SealAsync("tenant-custom", "policy-custom", anchor, budget, now, contentBudgets);
Assert.Equal(new StalenessBudget(30, 60), state.ContentBudgets["advisories"]);
Assert.Equal(new StalenessBudget(60, 120), state.ContentBudgets["vex"]);
Assert.Equal(budget, state.ContentBudgets["policy"]); // Falls back to default
}
[Fact]
public async Task GetStatus_returns_per_content_staleness()
{
var now = DateTimeOffset.UtcNow;
var anchor = new TimeAnchor(now.AddSeconds(-45), "roughtime", "roughtime", "fp", "digest");
var budget = StalenessBudget.Default;
var contentBudgets = new Dictionary<string, StalenessBudget>
{
{ "advisories", new StalenessBudget(30, 60) },
{ "vex", new StalenessBudget(60, 120) },
{ "policy", new StalenessBudget(100, 200) }
};
await _service.SealAsync("tenant-content-status", "policy-content-status", anchor, budget, now, contentBudgets);
var status = await _service.GetStatusAsync("tenant-content-status", now);
Assert.NotEmpty(status.ContentStaleness);
Assert.True(status.ContentStaleness["advisories"].IsWarning); // 45s >= 30s warning
Assert.False(status.ContentStaleness["advisories"].IsBreach); // 45s < 60s breach
Assert.False(status.ContentStaleness["vex"].IsWarning); // 45s < 60s warning
Assert.False(status.ContentStaleness["policy"].IsWarning); // 45s < 100s warning
}
}

View File

@@ -1,143 +0,0 @@
using StellaOps.AirGap.Controller.Domain;
using StellaOps.AirGap.Controller.Stores;
using StellaOps.AirGap.Time.Models;
using Xunit;
namespace StellaOps.AirGap.Controller.Tests;
public class InMemoryAirGapStateStoreTests
{
private readonly InMemoryAirGapStateStore _store = new();
[Fact]
public async Task Upsert_and_read_state_by_tenant()
{
var state = new AirGapState
{
TenantId = "tenant-x",
Sealed = true,
PolicyHash = "hash-1",
TimeAnchor = new TimeAnchor(DateTimeOffset.UtcNow, "roughtime", "roughtime", "fp", "digest"),
StalenessBudget = new StalenessBudget(10, 20),
LastTransitionAt = DateTimeOffset.UtcNow
};
await _store.SetAsync(state);
var stored = await _store.GetAsync("tenant-x");
Assert.True(stored.Sealed);
Assert.Equal("hash-1", stored.PolicyHash);
Assert.Equal("tenant-x", stored.TenantId);
Assert.Equal(state.TimeAnchor.TokenDigest, stored.TimeAnchor.TokenDigest);
Assert.Equal(10, stored.StalenessBudget.WarningSeconds);
}
[Fact]
public async Task Enforces_singleton_per_tenant()
{
var first = new AirGapState { TenantId = "tenant-y", Sealed = true, PolicyHash = "h1" };
var second = new AirGapState { TenantId = "tenant-y", Sealed = false, PolicyHash = "h2" };
await _store.SetAsync(first);
await _store.SetAsync(second);
var stored = await _store.GetAsync("tenant-y");
Assert.Equal("h2", stored.PolicyHash);
Assert.False(stored.Sealed);
}
[Fact]
public async Task Defaults_to_unknown_when_missing()
{
var stored = await _store.GetAsync("absent");
Assert.False(stored.Sealed);
Assert.Equal("absent", stored.TenantId);
}
[Fact]
public async Task Parallel_upserts_keep_single_document()
{
var tasks = Enumerable.Range(0, 20).Select(i =>
{
var state = new AirGapState
{
TenantId = "tenant-parallel",
Sealed = i % 2 == 0,
PolicyHash = $"hash-{i}"
};
return _store.SetAsync(state);
});
await Task.WhenAll(tasks);
var stored = await _store.GetAsync("tenant-parallel");
Assert.StartsWith("hash-", stored.PolicyHash);
}
[Fact]
public async Task Multi_tenant_updates_do_not_collide()
{
var tenants = Enumerable.Range(0, 5).Select(i => $"t-{i}").ToArray();
var tasks = tenants.Select(t => _store.SetAsync(new AirGapState
{
TenantId = t,
Sealed = true,
PolicyHash = $"hash-{t}"
}));
await Task.WhenAll(tasks);
foreach (var t in tenants)
{
var stored = await _store.GetAsync(t);
Assert.Equal($"hash-{t}", stored.PolicyHash);
}
}
[Fact]
public async Task Staleness_round_trip_matches_budget()
{
var anchor = new TimeAnchor(DateTimeOffset.UtcNow.AddMinutes(-3), "roughtime", "roughtime", "fp", "digest");
var budget = new StalenessBudget(60, 600);
await _store.SetAsync(new AirGapState
{
TenantId = "tenant-staleness",
Sealed = true,
PolicyHash = "hash-s",
TimeAnchor = anchor,
StalenessBudget = budget,
LastTransitionAt = DateTimeOffset.UtcNow
});
var stored = await _store.GetAsync("tenant-staleness");
Assert.Equal(anchor.TokenDigest, stored.TimeAnchor.TokenDigest);
Assert.Equal(budget.WarningSeconds, stored.StalenessBudget.WarningSeconds);
Assert.Equal(budget.BreachSeconds, stored.StalenessBudget.BreachSeconds);
}
[Fact]
public async Task Multi_tenant_states_preserve_transition_times()
{
var tenants = new[] { "a", "b", "c" };
var now = DateTimeOffset.UtcNow;
foreach (var t in tenants)
{
await _store.SetAsync(new AirGapState
{
TenantId = t,
Sealed = true,
PolicyHash = $"ph-{t}",
LastTransitionAt = now
});
}
foreach (var t in tenants)
{
var state = await _store.GetAsync(t);
Assert.Equal(now, state.LastTransitionAt);
Assert.Equal($"ph-{t}", state.PolicyHash);
}
}
}

View File

@@ -1,93 +0,0 @@
using StellaOps.AirGap.Controller.Endpoints.Contracts;
using StellaOps.AirGap.Controller.Services;
using StellaOps.AirGap.Controller.Stores;
using StellaOps.AirGap.Importer.Contracts;
using StellaOps.AirGap.Importer.Validation;
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Services;
using Xunit;
namespace StellaOps.AirGap.Controller.Tests;
public class ReplayVerificationServiceTests
{
private readonly ReplayVerificationService _service;
private readonly AirGapStateService _stateService;
private readonly StalenessCalculator _staleness = new();
private readonly InMemoryAirGapStateStore _store = new();
public ReplayVerificationServiceTests()
{
_stateService = new AirGapStateService(_store, _staleness);
_service = new ReplayVerificationService(_stateService, new ReplayVerifier());
}
[Fact]
public async Task Passes_full_recompute_when_hashes_match()
{
var now = DateTimeOffset.Parse("2025-12-02T01:00:00Z");
await _stateService.SealAsync("tenant-a", "policy-x", TimeAnchor.Unknown, StalenessBudget.Default, now);
var request = new VerifyRequest
{
Depth = ReplayDepth.FullRecompute,
ManifestSha256 = new string('a', 64),
BundleSha256 = new string('b', 64),
ComputedManifestSha256 = new string('a', 64),
ComputedBundleSha256 = new string('b', 64),
ManifestCreatedAt = now.AddHours(-2),
StalenessWindowHours = 24,
BundlePolicyHash = "policy-x"
};
var result = await _service.VerifyAsync("tenant-a", request, now);
Assert.True(result.IsValid);
Assert.Equal("full-recompute-passed", result.Reason);
}
[Fact]
public async Task Detects_stale_manifest()
{
var now = DateTimeOffset.UtcNow;
var request = new VerifyRequest
{
Depth = ReplayDepth.HashOnly,
ManifestSha256 = new string('a', 64),
BundleSha256 = new string('b', 64),
ComputedManifestSha256 = new string('a', 64),
ComputedBundleSha256 = new string('b', 64),
ManifestCreatedAt = now.AddHours(-30),
StalenessWindowHours = 12
};
var result = await _service.VerifyAsync("default", request, now);
Assert.False(result.IsValid);
Assert.Equal("manifest-stale", result.Reason);
}
[Fact]
public async Task Policy_freeze_requires_matching_policy()
{
var now = DateTimeOffset.UtcNow;
await _stateService.SealAsync("tenant-b", "sealed-policy", TimeAnchor.Unknown, StalenessBudget.Default, now);
var request = new VerifyRequest
{
Depth = ReplayDepth.PolicyFreeze,
ManifestSha256 = new string('a', 64),
BundleSha256 = new string('b', 64),
ComputedManifestSha256 = new string('a', 64),
ComputedBundleSha256 = new string('b', 64),
ManifestCreatedAt = now,
StalenessWindowHours = 48,
BundlePolicyHash = "bundle-policy"
};
var result = await _service.VerifyAsync("tenant-b", request, now);
Assert.False(result.IsValid);
Assert.Equal("policy-hash-drift", result.Reason);
}
}

View File

@@ -1,17 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../../src/AirGap/StellaOps.AirGap.Controller/StellaOps.AirGap.Controller.csproj" />
<Compile Include="../../shared/*.cs" Link="Shared/%(Filename)%(Extension)" />
</ItemGroup>
</Project>

View File

@@ -1,40 +0,0 @@
using StellaOps.AirGap.Importer.Contracts;
using StellaOps.AirGap.Importer.Planning;
namespace StellaOps.AirGap.Importer.Tests;
public class BundleImportPlannerTests
{
[Fact]
public void ReturnsFailureWhenBundlePathMissing()
{
var planner = new BundleImportPlanner();
var result = planner.CreatePlan(string.Empty, TrustRootConfig.Empty("/tmp"));
Assert.False(result.InitialState.IsValid);
Assert.Equal("bundle-path-required", result.InitialState.Reason);
}
[Fact]
public void ReturnsFailureWhenTrustRootsMissing()
{
var planner = new BundleImportPlanner();
var result = planner.CreatePlan("bundle.tar", TrustRootConfig.Empty("/tmp"));
Assert.False(result.InitialState.IsValid);
Assert.Equal("trust-roots-required", result.InitialState.Reason);
}
[Fact]
public void ReturnsDefaultPlanWhenInputsProvided()
{
var planner = new BundleImportPlanner();
var trust = new TrustRootConfig("/tmp/trust.json", new[] { "abc" }, new[] { "ed25519" }, null, null, new Dictionary<string, byte[]>());
var result = planner.CreatePlan("bundle.tar", trust);
Assert.True(result.InitialState.IsValid);
Assert.Contains("verify-dsse-signature", result.Steps);
Assert.Equal("bundle.tar", result.Inputs["bundlePath"]);
}
}

View File

@@ -1,71 +0,0 @@
using System.Security.Cryptography;
using StellaOps.AirGap.Importer.Contracts;
using StellaOps.AirGap.Importer.Validation;
namespace StellaOps.AirGap.Importer.Tests;
public class DsseVerifierTests
{
[Fact]
public void FailsWhenUntrustedKey()
{
var verifier = new DsseVerifier();
var envelope = new DsseEnvelope("text/plain", Convert.ToBase64String("hi"u8), new[] { new DsseSignature("k1", "sig") });
var trust = TrustRootConfig.Empty("/tmp");
var result = verifier.Verify(envelope, trust);
Assert.False(result.IsValid);
}
[Fact]
public void VerifiesRsaPssSignature()
{
using var rsa = RSA.Create(2048);
var pub = rsa.ExportSubjectPublicKeyInfo();
var payload = "hello-world";
var payloadType = "application/vnd.stella.bundle";
var pae = BuildPae(payloadType, payload);
var sig = rsa.SignData(pae, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
var envelope = new DsseEnvelope(payloadType, Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(payload)), new[]
{
new DsseSignature("k1", Convert.ToBase64String(sig))
});
var trust = new TrustRootConfig(
"/tmp/root.json",
new[] { Fingerprint(pub) },
new[] { "rsassa-pss-sha256" },
null,
null,
new Dictionary<string, byte[]> { ["k1"] = pub });
var result = new DsseVerifier().Verify(envelope, trust);
Assert.True(result.IsValid);
Assert.Equal("dsse-signature-verified", result.Reason);
}
private static byte[] BuildPae(string payloadType, string payload)
{
var parts = new[] { "DSSEv1", payloadType, payload };
var paeBuilder = new System.Text.StringBuilder();
paeBuilder.Append("PAE:");
paeBuilder.Append(parts.Length);
foreach (var part in parts)
{
paeBuilder.Append(' ');
paeBuilder.Append(part.Length);
paeBuilder.Append(' ');
paeBuilder.Append(part);
}
return System.Text.Encoding.UTF8.GetBytes(paeBuilder.ToString());
}
private static string Fingerprint(byte[] pub)
{
return Convert.ToHexString(SHA256.HashData(pub)).ToLowerInvariant();
}
}

View File

@@ -1 +0,0 @@
global using Xunit;

View File

@@ -1,238 +0,0 @@
using System.Security.Cryptography;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using StellaOps.AirGap.Importer.Contracts;
using StellaOps.AirGap.Importer.Quarantine;
using StellaOps.AirGap.Importer.Validation;
using StellaOps.AirGap.Importer.Versioning;
namespace StellaOps.AirGap.Importer.Tests;
public sealed class ImportValidatorTests
{
[Fact]
public async Task ValidateAsync_WhenTufInvalid_ShouldFailAndQuarantine()
{
var quarantine = new CapturingQuarantineService();
var monotonicity = new CapturingMonotonicityChecker();
var validator = new ImportValidator(
new DsseVerifier(),
new TufMetadataValidator(),
new MerkleRootCalculator(),
new RootRotationPolicy(),
monotonicity,
quarantine,
NullLogger<ImportValidator>.Instance);
var tempRoot = Path.Combine(Path.GetTempPath(), "stellaops-airgap-tests", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempRoot);
var bundlePath = Path.Combine(tempRoot, "bundle.tar.zst");
await File.WriteAllTextAsync(bundlePath, "bundle-bytes");
try
{
var request = BuildRequest(bundlePath, rootJson: "{}", snapshotJson: "{}", timestampJson: "{}");
var result = await validator.ValidateAsync(request);
result.IsValid.Should().BeFalse();
result.Reason.Should().StartWith("tuf:");
quarantine.Requests.Should().HaveCount(1);
quarantine.Requests[0].TenantId.Should().Be("tenant-a");
}
finally
{
try
{
Directory.Delete(tempRoot, recursive: true);
}
catch
{
// best-effort cleanup
}
}
}
[Fact]
public async Task ValidateAsync_WhenAllChecksPass_ShouldSucceedAndRecordActivation()
{
var root = "{\"version\":1,\"expiresUtc\":\"2030-01-01T00:00:00Z\"}";
var snapshot = "{\"version\":1,\"expiresUtc\":\"2030-01-01T00:00:00Z\",\"meta\":{\"snapshot\":{\"hashes\":{\"sha256\":\"abc\"}}}}";
var timestamp = "{\"version\":1,\"expiresUtc\":\"2030-01-01T00:00:00Z\",\"snapshot\":{\"meta\":{\"hashes\":{\"sha256\":\"abc\"}}}}";
using var rsa = RSA.Create(2048);
var pub = rsa.ExportSubjectPublicKeyInfo();
var payload = "bundle-body";
var payloadType = "application/vnd.stella.bundle";
var pae = BuildPae(payloadType, payload);
var sig = rsa.SignData(pae, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
var envelope = new DsseEnvelope(payloadType, Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(payload)), new[]
{
new DsseSignature("k1", Convert.ToBase64String(sig))
});
var trustStore = new TrustStore();
trustStore.LoadActive(new Dictionary<string, byte[]> { ["k1"] = pub });
trustStore.StagePending(new Dictionary<string, byte[]> { ["k2"] = pub });
var quarantine = new CapturingQuarantineService();
var monotonicity = new CapturingMonotonicityChecker();
var validator = new ImportValidator(
new DsseVerifier(),
new TufMetadataValidator(),
new MerkleRootCalculator(),
new RootRotationPolicy(),
monotonicity,
quarantine,
NullLogger<ImportValidator>.Instance);
var tempRoot = Path.Combine(Path.GetTempPath(), "stellaops-airgap-tests", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempRoot);
var bundlePath = Path.Combine(tempRoot, "bundle.tar.zst");
await File.WriteAllTextAsync(bundlePath, "bundle-bytes");
try
{
var request = new ImportValidationRequest(
TenantId: "tenant-a",
BundleType: "offline-kit",
BundleDigest: "sha256:bundle",
BundlePath: bundlePath,
ManifestJson: "{\"version\":\"1.0.0\"}",
ManifestVersion: "1.0.0",
ManifestCreatedAt: DateTimeOffset.Parse("2025-12-15T00:00:00Z"),
ForceActivate: false,
ForceActivateReason: null,
Envelope: envelope,
TrustRoots: new TrustRootConfig("/tmp/root.json", new[] { Fingerprint(pub) }, new[] { "rsassa-pss-sha256" }, null, null, new Dictionary<string, byte[]> { ["k1"] = pub }),
RootJson: root,
SnapshotJson: snapshot,
TimestampJson: timestamp,
PayloadEntries: new List<NamedStream> { new("a.txt", new MemoryStream("data"u8.ToArray())) },
TrustStore: trustStore,
ApproverIds: new[] { "approver-1", "approver-2" });
var result = await validator.ValidateAsync(request);
result.IsValid.Should().BeTrue();
result.Reason.Should().Be("import-validated");
monotonicity.RecordedActivations.Should().HaveCount(1);
monotonicity.RecordedActivations[0].BundleDigest.Should().Be("sha256:bundle");
monotonicity.RecordedActivations[0].Version.SemVer.Should().Be("1.0.0");
quarantine.Requests.Should().BeEmpty();
}
finally
{
try
{
Directory.Delete(tempRoot, recursive: true);
}
catch
{
// best-effort cleanup
}
}
}
private static byte[] BuildPae(string payloadType, string payload)
{
var parts = new[] { "DSSEv1", payloadType, payload };
var paeBuilder = new System.Text.StringBuilder();
paeBuilder.Append("PAE:");
paeBuilder.Append(parts.Length);
foreach (var part in parts)
{
paeBuilder.Append(' ');
paeBuilder.Append(part.Length);
paeBuilder.Append(' ');
paeBuilder.Append(part);
}
return System.Text.Encoding.UTF8.GetBytes(paeBuilder.ToString());
}
private static string Fingerprint(byte[] pub) => Convert.ToHexString(SHA256.HashData(pub)).ToLowerInvariant();
private static ImportValidationRequest BuildRequest(string bundlePath, string rootJson, string snapshotJson, string timestampJson)
{
var envelope = new DsseEnvelope("text/plain", Convert.ToBase64String("hi"u8), Array.Empty<DsseSignature>());
var trustRoot = TrustRootConfig.Empty("/tmp");
var trustStore = new TrustStore();
return new ImportValidationRequest(
TenantId: "tenant-a",
BundleType: "offline-kit",
BundleDigest: "sha256:bundle",
BundlePath: bundlePath,
ManifestJson: null,
ManifestVersion: "1.0.0",
ManifestCreatedAt: DateTimeOffset.Parse("2025-12-15T00:00:00Z"),
ForceActivate: false,
ForceActivateReason: null,
Envelope: envelope,
TrustRoots: trustRoot,
RootJson: rootJson,
SnapshotJson: snapshotJson,
TimestampJson: timestampJson,
PayloadEntries: Array.Empty<NamedStream>(),
TrustStore: trustStore,
ApproverIds: Array.Empty<string>());
}
private sealed class CapturingMonotonicityChecker : IVersionMonotonicityChecker
{
public List<(BundleVersion Version, string BundleDigest)> RecordedActivations { get; } = new();
public Task<MonotonicityCheckResult> CheckAsync(string tenantId, string bundleType, BundleVersion incomingVersion, CancellationToken cancellationToken = default)
{
return Task.FromResult(new MonotonicityCheckResult(
IsMonotonic: true,
CurrentVersion: null,
CurrentBundleDigest: null,
CurrentActivatedAt: null,
ReasonCode: "FIRST_ACTIVATION"));
}
public Task RecordActivationAsync(
string tenantId,
string bundleType,
BundleVersion version,
string bundleDigest,
bool wasForceActivated = false,
string? forceActivateReason = null,
CancellationToken cancellationToken = default)
{
RecordedActivations.Add((version, bundleDigest));
return Task.CompletedTask;
}
}
private sealed class CapturingQuarantineService : IQuarantineService
{
public List<QuarantineRequest> Requests { get; } = new();
public Task<QuarantineResult> QuarantineAsync(QuarantineRequest request, CancellationToken cancellationToken = default)
{
Requests.Add(request);
return Task.FromResult(new QuarantineResult(
Success: true,
QuarantineId: "test",
QuarantinePath: "(memory)",
QuarantinedAt: DateTimeOffset.UnixEpoch));
}
public Task<IReadOnlyList<QuarantineEntry>> ListAsync(string tenantId, QuarantineListOptions? options = null, CancellationToken cancellationToken = default) =>
Task.FromResult<IReadOnlyList<QuarantineEntry>>(Array.Empty<QuarantineEntry>());
public Task<bool> RemoveAsync(string tenantId, string quarantineId, string removalReason, CancellationToken cancellationToken = default) =>
Task.FromResult(false);
public Task<int> CleanupExpiredAsync(TimeSpan retentionPeriod, CancellationToken cancellationToken = default) =>
Task.FromResult(0);
}
}

View File

@@ -1,63 +0,0 @@
using StellaOps.AirGap.Importer.Models;
using StellaOps.AirGap.Importer.Repositories;
namespace StellaOps.AirGap.Importer.Tests;
public class InMemoryBundleRepositoriesTests
{
[Fact]
public async Task CatalogUpsertOverwritesPerTenant()
{
var repo = new InMemoryBundleCatalogRepository();
var entry1 = new BundleCatalogEntry("t1", "b1", "d1", DateTimeOffset.UnixEpoch, new[] { "a" });
var entry2 = new BundleCatalogEntry("t1", "b1", "d2", DateTimeOffset.UnixEpoch.AddMinutes(1), new[] { "b" });
await repo.UpsertAsync(entry1, default);
await repo.UpsertAsync(entry2, default);
var list = await repo.ListAsync("t1", default);
Assert.Single(list);
Assert.Equal("d2", list[0].Digest);
}
[Fact]
public async Task CatalogIsTenantIsolated()
{
var repo = new InMemoryBundleCatalogRepository();
await repo.UpsertAsync(new BundleCatalogEntry("t1", "b1", "d1", DateTimeOffset.UnixEpoch, Array.Empty<string>()), default);
await repo.UpsertAsync(new BundleCatalogEntry("t2", "b1", "d2", DateTimeOffset.UnixEpoch, Array.Empty<string>()), default);
var t1 = await repo.ListAsync("t1", default);
Assert.Single(t1);
Assert.Equal("d1", t1[0].Digest);
}
[Fact]
public async Task ItemsOrderedByPath()
{
var repo = new InMemoryBundleItemRepository();
await repo.UpsertManyAsync(new[]
{
new BundleItem("t1", "b1", "b.txt", "d2", 10),
new BundleItem("t1", "b1", "a.txt", "d1", 5)
}, default);
var list = await repo.ListByBundleAsync("t1", "b1", default);
Assert.Equal(new[] { "a.txt", "b.txt" }, list.Select(i => i.Path).ToArray());
}
[Fact]
public async Task ItemsTenantIsolated()
{
var repo = new InMemoryBundleItemRepository();
await repo.UpsertManyAsync(new[]
{
new BundleItem("t1", "b1", "a.txt", "d1", 1),
new BundleItem("t2", "b1", "a.txt", "d2", 1)
}, default);
var list = await repo.ListByBundleAsync("t1", "b1", default);
Assert.Single(list);
Assert.Equal("d1", list[0].Digest);
}
}

View File

@@ -1,28 +0,0 @@
using StellaOps.AirGap.Importer.Validation;
namespace StellaOps.AirGap.Importer.Tests;
public class MerkleRootCalculatorTests
{
[Fact]
public void EmptySetProducesEmptyRoot()
{
var calc = new MerkleRootCalculator();
var root = calc.ComputeRoot(Array.Empty<NamedStream>());
Assert.Equal(string.Empty, root);
}
[Fact]
public void DeterministicAcrossOrder()
{
var calc = new MerkleRootCalculator();
var a = new NamedStream("b.txt", new MemoryStream("two"u8.ToArray()));
var b = new NamedStream("a.txt", new MemoryStream("one"u8.ToArray()));
var root1 = calc.ComputeRoot(new[] { a, b });
var root2 = calc.ComputeRoot(new[] { b, a });
Assert.Equal(root1, root2);
Assert.NotEqual(string.Empty, root1);
}
}

View File

@@ -1,113 +0,0 @@
using System.Diagnostics.Metrics;
using StellaOps.AirGap.Importer.Telemetry;
namespace StellaOps.AirGap.Importer.Tests;
public sealed class OfflineKitMetricsTests : IDisposable
{
private readonly MeterListener _listener;
private readonly List<RecordedMeasurement> _measurements = [];
public OfflineKitMetricsTests()
{
_listener = new MeterListener();
_listener.InstrumentPublished = (instrument, listener) =>
{
if (instrument.Meter.Name == OfflineKitMetrics.MeterName)
{
listener.EnableMeasurementEvents(instrument);
}
};
_listener.SetMeasurementEventCallback<double>((instrument, measurement, tags, state) =>
{
_measurements.Add(new RecordedMeasurement(instrument.Name, measurement, tags.ToArray()));
});
_listener.SetMeasurementEventCallback<long>((instrument, measurement, tags, state) =>
{
_measurements.Add(new RecordedMeasurement(instrument.Name, measurement, tags.ToArray()));
});
_listener.Start();
}
public void Dispose() => _listener.Dispose();
[Fact]
public void RecordImport_EmitsCounterWithLabels()
{
using var metrics = new OfflineKitMetrics();
metrics.RecordImport(status: "success", tenantId: "tenant-a");
Assert.Contains(_measurements, m =>
m.Name == "offlinekit_import_total" &&
m.Value is long v &&
v == 1 &&
m.HasTag(OfflineKitMetrics.TagNames.Status, "success") &&
m.HasTag(OfflineKitMetrics.TagNames.TenantId, "tenant-a"));
}
[Fact]
public void RecordAttestationVerifyLatency_EmitsHistogramWithLabels()
{
using var metrics = new OfflineKitMetrics();
metrics.RecordAttestationVerifyLatency(attestationType: "dsse", seconds: 1.234, success: true);
Assert.Contains(_measurements, m =>
m.Name == "offlinekit_attestation_verify_latency_seconds" &&
m.Value is double v &&
Math.Abs(v - 1.234) < 0.000_001 &&
m.HasTag(OfflineKitMetrics.TagNames.AttestationType, "dsse") &&
m.HasTag(OfflineKitMetrics.TagNames.Success, "true"));
}
[Fact]
public void RecordRekorSuccess_EmitsCounterWithLabels()
{
using var metrics = new OfflineKitMetrics();
metrics.RecordRekorSuccess(mode: "offline");
Assert.Contains(_measurements, m =>
m.Name == "attestor_rekor_success_total" &&
m.Value is long v &&
v == 1 &&
m.HasTag(OfflineKitMetrics.TagNames.Mode, "offline"));
}
[Fact]
public void RecordRekorRetry_EmitsCounterWithLabels()
{
using var metrics = new OfflineKitMetrics();
metrics.RecordRekorRetry(reason: "stale_snapshot");
Assert.Contains(_measurements, m =>
m.Name == "attestor_rekor_retry_total" &&
m.Value is long v &&
v == 1 &&
m.HasTag(OfflineKitMetrics.TagNames.Reason, "stale_snapshot"));
}
[Fact]
public void RecordRekorInclusionLatency_EmitsHistogramWithLabels()
{
using var metrics = new OfflineKitMetrics();
metrics.RecordRekorInclusionLatency(seconds: 0.5, success: false);
Assert.Contains(_measurements, m =>
m.Name == "rekor_inclusion_latency" &&
m.Value is double v &&
Math.Abs(v - 0.5) < 0.000_001 &&
m.HasTag(OfflineKitMetrics.TagNames.Success, "false"));
}
private sealed record RecordedMeasurement(string Name, object Value, IReadOnlyList<KeyValuePair<string, object?>> Tags)
{
public bool HasTag(string key, string expectedValue) =>
Tags.Any(t => t.Key == key && string.Equals(t.Value?.ToString(), expectedValue, StringComparison.Ordinal));
}
}

View File

@@ -1,155 +0,0 @@
using System.Text.Json;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using StellaOps.AirGap.Importer.Quarantine;
namespace StellaOps.AirGap.Importer.Tests.Quarantine;
public sealed class FileSystemQuarantineServiceTests
{
[Fact]
public async Task QuarantineAsync_ShouldCreateExpectedFiles_AndListAsyncShouldReturnEntry()
{
var root = CreateTempDirectory();
try
{
var bundlePath = Path.Combine(root, "bundle.tar.zst");
await File.WriteAllTextAsync(bundlePath, "bundle-bytes");
var options = Options.Create(new QuarantineOptions
{
QuarantineRoot = Path.Combine(root, "quarantine"),
RetentionPeriod = TimeSpan.FromDays(30),
MaxQuarantineSizeBytes = 1024 * 1024,
EnableAutomaticCleanup = true
});
var svc = new FileSystemQuarantineService(
options,
NullLogger<FileSystemQuarantineService>.Instance,
TimeProvider.System);
var result = await svc.QuarantineAsync(new QuarantineRequest(
TenantId: "tenant-a",
BundlePath: bundlePath,
ManifestJson: "{\"version\":\"1.0.0\"}",
ReasonCode: "dsse:invalid",
ReasonMessage: "dsse:invalid",
VerificationLog: new[] { "tuf:ok", "dsse:invalid" },
Metadata: new Dictionary<string, string> { ["k"] = "v" }));
result.Success.Should().BeTrue();
Directory.Exists(result.QuarantinePath).Should().BeTrue();
File.Exists(Path.Combine(result.QuarantinePath, "bundle.tar.zst")).Should().BeTrue();
File.Exists(Path.Combine(result.QuarantinePath, "manifest.json")).Should().BeTrue();
File.Exists(Path.Combine(result.QuarantinePath, "verification.log")).Should().BeTrue();
File.Exists(Path.Combine(result.QuarantinePath, "failure-reason.txt")).Should().BeTrue();
File.Exists(Path.Combine(result.QuarantinePath, "quarantine.json")).Should().BeTrue();
var listed = await svc.ListAsync("tenant-a");
listed.Should().ContainSingle(e => e.QuarantineId == result.QuarantineId);
}
finally
{
SafeDeleteDirectory(root);
}
}
[Fact]
public async Task RemoveAsync_ShouldMoveToRemovedFolder()
{
var root = CreateTempDirectory();
try
{
var bundlePath = Path.Combine(root, "bundle.tar.zst");
await File.WriteAllTextAsync(bundlePath, "bundle-bytes");
var quarantineRoot = Path.Combine(root, "quarantine");
var options = Options.Create(new QuarantineOptions { QuarantineRoot = quarantineRoot, MaxQuarantineSizeBytes = 1024 * 1024 });
var svc = new FileSystemQuarantineService(options, NullLogger<FileSystemQuarantineService>.Instance, TimeProvider.System);
var result = await svc.QuarantineAsync(new QuarantineRequest(
TenantId: "tenant-a",
BundlePath: bundlePath,
ManifestJson: null,
ReasonCode: "tuf:invalid",
ReasonMessage: "tuf:invalid",
VerificationLog: new[] { "tuf:invalid" }));
var removed = await svc.RemoveAsync("tenant-a", result.QuarantineId, "investigated");
removed.Should().BeTrue();
Directory.Exists(result.QuarantinePath).Should().BeFalse();
Directory.Exists(Path.Combine(quarantineRoot, "tenant-a", ".removed", result.QuarantineId)).Should().BeTrue();
}
finally
{
SafeDeleteDirectory(root);
}
}
[Fact]
public async Task CleanupExpiredAsync_ShouldDeleteOldEntries()
{
var root = CreateTempDirectory();
try
{
var bundlePath = Path.Combine(root, "bundle.tar.zst");
await File.WriteAllTextAsync(bundlePath, "bundle-bytes");
var quarantineRoot = Path.Combine(root, "quarantine");
var options = Options.Create(new QuarantineOptions { QuarantineRoot = quarantineRoot, MaxQuarantineSizeBytes = 1024 * 1024 });
var svc = new FileSystemQuarantineService(options, NullLogger<FileSystemQuarantineService>.Instance, TimeProvider.System);
var result = await svc.QuarantineAsync(new QuarantineRequest(
TenantId: "tenant-a",
BundlePath: bundlePath,
ManifestJson: null,
ReasonCode: "tuf:invalid",
ReasonMessage: "tuf:invalid",
VerificationLog: new[] { "tuf:invalid" }));
var jsonPath = Path.Combine(result.QuarantinePath, "quarantine.json");
var json = await File.ReadAllTextAsync(jsonPath);
var jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web) { WriteIndented = true };
var entry = JsonSerializer.Deserialize<QuarantineEntry>(json, jsonOptions);
entry.Should().NotBeNull();
var oldEntry = entry! with { QuarantinedAt = DateTimeOffset.Parse("1900-01-01T00:00:00Z") };
await File.WriteAllTextAsync(jsonPath, JsonSerializer.Serialize(oldEntry, jsonOptions));
var removed = await svc.CleanupExpiredAsync(TimeSpan.FromDays(30));
removed.Should().BeGreaterThanOrEqualTo(1);
Directory.Exists(result.QuarantinePath).Should().BeFalse();
}
finally
{
SafeDeleteDirectory(root);
}
}
private static string CreateTempDirectory()
{
var dir = Path.Combine(Path.GetTempPath(), "stellaops-airgap-tests", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
return dir;
}
private static void SafeDeleteDirectory(string path)
{
try
{
if (Directory.Exists(path))
{
Directory.Delete(path, recursive: true);
}
}
catch
{
// best-effort cleanup
}
}
}

View File

@@ -1,65 +0,0 @@
using FluentAssertions;
using StellaOps.AirGap.Importer.Reconciliation;
namespace StellaOps.AirGap.Importer.Tests.Reconciliation;
public sealed class ArtifactIndexTests
{
[Fact]
public void NormalizeDigest_BareHex_AddsPrefixAndLowercases()
{
var hex = new string('A', 64);
ArtifactIndex.NormalizeDigest(hex).Should().Be("sha256:" + new string('a', 64));
}
[Fact]
public void NormalizeDigest_WithSha256Prefix_IsCanonical()
{
var hex = new string('B', 64);
ArtifactIndex.NormalizeDigest("sha256:" + hex).Should().Be("sha256:" + new string('b', 64));
}
[Fact]
public void NormalizeDigest_WithOtherAlgorithm_Throws()
{
var ex = Assert.Throws<FormatException>(() => ArtifactIndex.NormalizeDigest("sha512:" + new string('a', 64)));
ex.Message.Should().Contain("Only sha256");
}
[Fact]
public void AddOrUpdate_MergesEntries_DeduplicatesAndSorts()
{
var digest = new string('c', 64);
var entryA = ArtifactEntry.Empty(digest) with
{
Sboms = new[]
{
new SbomReference("b", "b.json", SbomFormat.CycloneDx, null),
new SbomReference("a", "a.json", SbomFormat.Spdx, null),
}
};
var entryB = ArtifactEntry.Empty("sha256:" + digest.ToUpperInvariant()) with
{
Sboms = new[]
{
new SbomReference("a", "a2.json", SbomFormat.CycloneDx, null),
new SbomReference("c", "c.json", SbomFormat.Spdx, null),
}
};
var index = new ArtifactIndex();
index.AddOrUpdate(entryA);
index.AddOrUpdate(entryB);
var stored = index.Get("sha256:" + digest);
stored.Should().NotBeNull();
stored!.Digest.Should().Be("sha256:" + digest);
stored.Sboms.Select(s => (s.ContentHash, s.FilePath)).Should().Equal(
("a", "a.json"),
("b", "b.json"),
("c", "c.json"));
}
}

View File

@@ -1,136 +0,0 @@
// =============================================================================
// CycloneDxParserTests.cs
// Golden-file tests for CycloneDX SBOM parsing
// Part of Task T24: Golden-file tests for determinism
// =============================================================================
using FluentAssertions;
using StellaOps.AirGap.Importer.Reconciliation;
using StellaOps.AirGap.Importer.Reconciliation.Parsers;
namespace StellaOps.AirGap.Importer.Tests.Reconciliation;
public sealed class CycloneDxParserTests
{
private static readonly string FixturesPath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Reconciliation", "Fixtures");
[Fact]
public async Task ParseAsync_ValidCycloneDx_ExtractsAllSubjects()
{
// Arrange
var parser = new CycloneDxParser();
var filePath = Path.Combine(FixturesPath, "sample.cdx.json");
// Skip if fixtures not available
if (!File.Exists(filePath))
{
return;
}
// Act
var result = await parser.ParseAsync(filePath);
// Assert
result.IsSuccess.Should().BeTrue();
result.Format.Should().Be(SbomFormat.CycloneDx);
result.SpecVersion.Should().Be("1.6");
result.SerialNumber.Should().Be("urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79");
result.GeneratorTool.Should().Contain("syft");
// Should have 3 subjects with SHA-256 hashes (primary + 2 components)
result.Subjects.Should().HaveCount(3);
// Verify subjects are sorted by digest
result.Subjects.Should().BeInAscendingOrder(s => s.Digest, StringComparer.Ordinal);
}
[Fact]
public async Task ParseAsync_ExtractsPrimarySubject()
{
// Arrange
var parser = new CycloneDxParser();
var filePath = Path.Combine(FixturesPath, "sample.cdx.json");
if (!File.Exists(filePath))
{
return;
}
// Act
var result = await parser.ParseAsync(filePath);
// Assert
result.PrimarySubject.Should().NotBeNull();
result.PrimarySubject!.Name.Should().Be("test-app");
result.PrimarySubject.Version.Should().Be("1.0.0");
result.PrimarySubject.Digest.Should().StartWith("sha256:");
}
[Fact]
public async Task ParseAsync_SubjectDigestsAreNormalized()
{
// Arrange
var parser = new CycloneDxParser();
var filePath = Path.Combine(FixturesPath, "sample.cdx.json");
if (!File.Exists(filePath))
{
return;
}
// Act
var result = await parser.ParseAsync(filePath);
// Assert - all digests should be normalized sha256:lowercase format
foreach (var subject in result.Subjects)
{
subject.Digest.Should().StartWith("sha256:");
subject.Digest[7..].Should().MatchRegex("^[a-f0-9]{64}$");
}
}
[Fact]
public void DetectFormat_CycloneDxFile_ReturnsCycloneDx()
{
var parser = new CycloneDxParser();
parser.DetectFormat("test.cdx.json").Should().Be(SbomFormat.CycloneDx);
parser.DetectFormat("test.bom.json").Should().Be(SbomFormat.CycloneDx);
}
[Fact]
public void DetectFormat_NonCycloneDxFile_ReturnsUnknown()
{
var parser = new CycloneDxParser();
parser.DetectFormat("test.spdx.json").Should().Be(SbomFormat.Unknown);
parser.DetectFormat("test.json").Should().Be(SbomFormat.Unknown);
}
[Fact]
public async Task ParseAsync_Deterministic_SameOutputForSameInput()
{
// Arrange
var parser = new CycloneDxParser();
var filePath = Path.Combine(FixturesPath, "sample.cdx.json");
if (!File.Exists(filePath))
{
return;
}
// Act - parse twice
var result1 = await parser.ParseAsync(filePath);
var result2 = await parser.ParseAsync(filePath);
// Assert - results should be identical
result1.Subjects.Select(s => s.Digest)
.Should().BeEquivalentTo(result2.Subjects.Select(s => s.Digest));
result1.Subjects.Select(s => s.Name)
.Should().BeEquivalentTo(result2.Subjects.Select(s => s.Name));
// Order should be the same
result1.Subjects.Select(s => s.Digest).Should().Equal(result2.Subjects.Select(s => s.Digest));
}
}

View File

@@ -1,141 +0,0 @@
// =============================================================================
// DsseAttestationParserTests.cs
// Golden-file tests for DSSE attestation parsing
// Part of Task T24: Golden-file tests for determinism
// =============================================================================
using FluentAssertions;
using StellaOps.AirGap.Importer.Reconciliation.Parsers;
namespace StellaOps.AirGap.Importer.Tests.Reconciliation;
public sealed class DsseAttestationParserTests
{
private static readonly string FixturesPath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Reconciliation", "Fixtures");
[Fact]
public async Task ParseAsync_ValidDsse_ExtractsEnvelope()
{
// Arrange
var parser = new DsseAttestationParser();
var filePath = Path.Combine(FixturesPath, "sample.intoto.json");
if (!File.Exists(filePath))
{
return;
}
// Act
var result = await parser.ParseAsync(filePath);
// Assert
result.IsSuccess.Should().BeTrue();
result.Envelope.Should().NotBeNull();
result.Envelope!.PayloadType.Should().Be("application/vnd.in-toto+json");
result.Envelope.Signatures.Should().HaveCount(1);
result.Envelope.Signatures[0].KeyId.Should().Be("test-key-id");
}
[Fact]
public async Task ParseAsync_ValidDsse_ExtractsStatement()
{
// Arrange
var parser = new DsseAttestationParser();
var filePath = Path.Combine(FixturesPath, "sample.intoto.json");
if (!File.Exists(filePath))
{
return;
}
// Act
var result = await parser.ParseAsync(filePath);
// Assert
result.Statement.Should().NotBeNull();
result.Statement!.Type.Should().Be("https://in-toto.io/Statement/v1");
result.Statement.PredicateType.Should().Be("https://slsa.dev/provenance/v1");
result.Statement.Subjects.Should().HaveCount(1);
}
[Fact]
public async Task ParseAsync_ExtractsSubjectDigests()
{
// Arrange
var parser = new DsseAttestationParser();
var filePath = Path.Combine(FixturesPath, "sample.intoto.json");
if (!File.Exists(filePath))
{
return;
}
// Act
var result = await parser.ParseAsync(filePath);
// Assert
var subject = result.Statement!.Subjects[0];
subject.Name.Should().Be("test-app");
subject.GetSha256Digest().Should().Be("sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
}
[Fact]
public void IsAttestation_DsseFile_ReturnsTrue()
{
var parser = new DsseAttestationParser();
parser.IsAttestation("test.intoto.json").Should().BeTrue();
parser.IsAttestation("test.intoto.jsonl").Should().BeTrue();
parser.IsAttestation("test.dsig").Should().BeTrue();
parser.IsAttestation("test.dsse").Should().BeTrue();
}
[Fact]
public void IsAttestation_NonDsseFile_ReturnsFalse()
{
var parser = new DsseAttestationParser();
parser.IsAttestation("test.json").Should().BeFalse();
parser.IsAttestation("test.cdx.json").Should().BeFalse();
parser.IsAttestation("test.spdx.json").Should().BeFalse();
}
[Fact]
public async Task ParseAsync_Deterministic_SameOutputForSameInput()
{
// Arrange
var parser = new DsseAttestationParser();
var filePath = Path.Combine(FixturesPath, "sample.intoto.json");
if (!File.Exists(filePath))
{
return;
}
// Act - parse twice
var result1 = await parser.ParseAsync(filePath);
var result2 = await parser.ParseAsync(filePath);
// Assert - results should be identical
result1.Statement!.PredicateType.Should().Be(result2.Statement!.PredicateType);
result1.Statement.Subjects.Count.Should().Be(result2.Statement.Subjects.Count);
result1.Statement.Subjects[0].GetSha256Digest()
.Should().Be(result2.Statement.Subjects[0].GetSha256Digest());
}
[Fact]
public async Task ParseAsync_InvalidJson_ReturnsFailure()
{
// Arrange
var parser = new DsseAttestationParser();
var json = "not valid json";
using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
// Act
var result = await parser.ParseAsync(stream);
// Assert
result.IsSuccess.Should().BeFalse();
result.ErrorMessage.Should().Contain("parsing error");
}
}

View File

@@ -1,65 +0,0 @@
using System.Security.Cryptography;
using System.Text;
using FluentAssertions;
using StellaOps.AirGap.Importer.Reconciliation;
namespace StellaOps.AirGap.Importer.Tests.Reconciliation;
public sealed class EvidenceDirectoryDiscoveryTests
{
[Fact]
public void Discover_ReturnsDeterministicRelativePathsAndHashes()
{
var root = Path.Combine(Path.GetTempPath(), "stellaops-evidence-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
try
{
WriteUtf8(Path.Combine(root, "sboms", "a.cdx.json"), "{\"bom\":1}");
WriteUtf8(Path.Combine(root, "attestations", "z.intoto.jsonl.dsig"), "dsse");
WriteUtf8(Path.Combine(root, "vex", "v.openvex.json"), "{\"vex\":true}");
var discovered = EvidenceDirectoryDiscovery.Discover(root);
discovered.Should().HaveCount(3);
discovered.Select(d => d.RelativePath).Should().Equal(
"attestations/z.intoto.jsonl.dsig",
"sboms/a.cdx.json",
"vex/v.openvex.json");
discovered[0].Kind.Should().Be(EvidenceFileKind.Attestation);
discovered[1].Kind.Should().Be(EvidenceFileKind.Sbom);
discovered[2].Kind.Should().Be(EvidenceFileKind.Vex);
discovered[0].ContentSha256.Should().Be(HashUtf8("dsse"));
discovered[1].ContentSha256.Should().Be(HashUtf8("{\"bom\":1}"));
discovered[2].ContentSha256.Should().Be(HashUtf8("{\"vex\":true}"));
}
finally
{
Directory.Delete(root, recursive: true);
}
}
[Fact]
public void Discover_WhenDirectoryMissing_Throws()
{
var missing = Path.Combine(Path.GetTempPath(), "stellaops-missing-" + Guid.NewGuid().ToString("N"));
Action act = () => EvidenceDirectoryDiscovery.Discover(missing);
act.Should().Throw<DirectoryNotFoundException>();
}
private static void WriteUtf8(string path, string content)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, content, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
}
private static string HashUtf8(string content)
{
using var sha256 = SHA256.Create();
var bytes = Encoding.UTF8.GetBytes(content);
var hash = sha256.ComputeHash(bytes);
return "sha256:" + Convert.ToHexString(hash).ToLowerInvariant();
}
}

View File

@@ -1,56 +0,0 @@
{
"bomFormat": "CycloneDX",
"specVersion": "1.6",
"version": 1,
"serialNumber": "urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79",
"metadata": {
"timestamp": "2025-01-15T10:00:00Z",
"component": {
"type": "application",
"name": "test-app",
"version": "1.0.0",
"hashes": [
{
"alg": "SHA-256",
"content": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
]
},
"tools": {
"components": [
{
"name": "syft",
"version": "1.0.0"
}
]
}
},
"components": [
{
"type": "library",
"name": "zlib",
"version": "1.2.11",
"bom-ref": "pkg:generic/zlib@1.2.11",
"purl": "pkg:generic/zlib@1.2.11",
"hashes": [
{
"alg": "SHA-256",
"content": "c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1"
}
]
},
{
"type": "library",
"name": "openssl",
"version": "3.0.0",
"bom-ref": "pkg:generic/openssl@3.0.0",
"purl": "pkg:generic/openssl@3.0.0",
"hashes": [
{
"alg": "SHA-256",
"content": "919b4a3e65a8deade6b3c94dd44cb98e0f65a1785a787689c23e6b5c0b4edfea"
}
]
}
]
}

View File

@@ -1,10 +0,0 @@
{
"payloadType": "application/vnd.in-toto+json",
"payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGVUeXBlIjoiaHR0cHM6Ly9zbHNhLmRldi9wcm92ZW5hbmNlL3YxIiwic3ViamVjdCI6W3sibmFtZSI6InRlc3QtYXBwIiwiZGlnZXN0Ijp7InNoYTI1NiI6ImUzYjBjNDQyOThmYzFjMTQ5YWZiZjRjODk5NmZiOTI0MjdhZTQxZTQ2NDliOTM0Y2E0OTU5OTFiNzg1MmI4NTUifX1dLCJwcmVkaWNhdGUiOnsiYnVpbGRlcklkIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9idWlsZGVyIiwiYnVpbGRUeXBlIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9idWlsZC10eXBlIn19",
"signatures": [
{
"keyid": "test-key-id",
"sig": "MEUCIQDFmJRQSwWMbQGiS8X5mY9CvZxVbVmXJ7JQVGEYIhXEBQIgbqDBJxP2P9N2kGPXDlX7Qx8KPVQjN3P1Y5Z9A8B2C3D="
}
]
}

View File

@@ -1,88 +0,0 @@
{
"spdxVersion": "SPDX-2.3",
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "test-app-sbom",
"documentNamespace": "https://example.com/test-app/1.0.0",
"creationInfo": {
"created": "2025-01-15T10:00:00Z",
"creators": [
"Tool: syft-1.0.0"
]
},
"documentDescribes": [
"SPDXRef-Package-test-app"
],
"packages": [
{
"SPDXID": "SPDXRef-Package-test-app",
"name": "test-app",
"versionInfo": "1.0.0",
"downloadLocation": "NOASSERTION",
"filesAnalyzed": false,
"checksums": [
{
"algorithm": "SHA256",
"checksumValue": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
]
},
{
"SPDXID": "SPDXRef-Package-zlib",
"name": "zlib",
"versionInfo": "1.2.11",
"downloadLocation": "NOASSERTION",
"filesAnalyzed": false,
"checksums": [
{
"algorithm": "SHA256",
"checksumValue": "c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1"
}
],
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceType": "purl",
"referenceLocator": "pkg:generic/zlib@1.2.11"
}
]
},
{
"SPDXID": "SPDXRef-Package-openssl",
"name": "openssl",
"versionInfo": "3.0.0",
"downloadLocation": "NOASSERTION",
"filesAnalyzed": false,
"checksums": [
{
"algorithm": "SHA256",
"checksumValue": "919b4a3e65a8deade6b3c94dd44cb98e0f65a1785a787689c23e6b5c0b4edfea"
}
],
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceType": "purl",
"referenceLocator": "pkg:generic/openssl@3.0.0"
}
]
}
],
"relationships": [
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relatedSpdxElement": "SPDXRef-Package-test-app",
"relationshipType": "DESCRIBES"
},
{
"spdxElementId": "SPDXRef-Package-test-app",
"relatedSpdxElement": "SPDXRef-Package-zlib",
"relationshipType": "DEPENDS_ON"
},
{
"spdxElementId": "SPDXRef-Package-test-app",
"relatedSpdxElement": "SPDXRef-Package-openssl",
"relationshipType": "DEPENDS_ON"
}
]
}

View File

@@ -1,453 +0,0 @@
// =============================================================================
// SourcePrecedenceLatticePropertyTests.cs
// Property-based tests for lattice properties
// Part of Task T25: Write property-based tests
// =============================================================================
using StellaOps.AirGap.Importer.Reconciliation;
namespace StellaOps.AirGap.Importer.Tests.Reconciliation;
/// <summary>
/// Property-based tests verifying lattice algebraic properties.
/// A lattice must satisfy: associativity, commutativity, idempotence, and absorption.
/// </summary>
public sealed class SourcePrecedenceLatticePropertyTests
{
private static readonly SourcePrecedence[] AllPrecedences =
[
SourcePrecedence.Unknown,
SourcePrecedence.ThirdParty,
SourcePrecedence.Maintainer,
SourcePrecedence.Vendor
];
#region Lattice Algebraic Properties
/// <summary>
/// Property: Join is commutative - Join(a, b) = Join(b, a)
/// </summary>
[Fact]
public void Join_IsCommutative()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
var joinAB = SourcePrecedenceLattice.Join(a, b);
var joinBA = SourcePrecedenceLattice.Join(b, a);
Assert.Equal(joinAB, joinBA);
}
}
}
/// <summary>
/// Property: Meet is commutative - Meet(a, b) = Meet(b, a)
/// </summary>
[Fact]
public void Meet_IsCommutative()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
var meetAB = SourcePrecedenceLattice.Meet(a, b);
var meetBA = SourcePrecedenceLattice.Meet(b, a);
Assert.Equal(meetAB, meetBA);
}
}
}
/// <summary>
/// Property: Join is associative - Join(Join(a, b), c) = Join(a, Join(b, c))
/// </summary>
[Fact]
public void Join_IsAssociative()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
foreach (var c in AllPrecedences)
{
var left = SourcePrecedenceLattice.Join(SourcePrecedenceLattice.Join(a, b), c);
var right = SourcePrecedenceLattice.Join(a, SourcePrecedenceLattice.Join(b, c));
Assert.Equal(left, right);
}
}
}
}
/// <summary>
/// Property: Meet is associative - Meet(Meet(a, b), c) = Meet(a, Meet(b, c))
/// </summary>
[Fact]
public void Meet_IsAssociative()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
foreach (var c in AllPrecedences)
{
var left = SourcePrecedenceLattice.Meet(SourcePrecedenceLattice.Meet(a, b), c);
var right = SourcePrecedenceLattice.Meet(a, SourcePrecedenceLattice.Meet(b, c));
Assert.Equal(left, right);
}
}
}
}
/// <summary>
/// Property: Join is idempotent - Join(a, a) = a
/// </summary>
[Fact]
public void Join_IsIdempotent()
{
foreach (var a in AllPrecedences)
{
var result = SourcePrecedenceLattice.Join(a, a);
Assert.Equal(a, result);
}
}
/// <summary>
/// Property: Meet is idempotent - Meet(a, a) = a
/// </summary>
[Fact]
public void Meet_IsIdempotent()
{
foreach (var a in AllPrecedences)
{
var result = SourcePrecedenceLattice.Meet(a, a);
Assert.Equal(a, result);
}
}
/// <summary>
/// Property: Absorption law 1 - Join(a, Meet(a, b)) = a
/// </summary>
[Fact]
public void Absorption_JoinMeet_ReturnsFirst()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
var meet = SourcePrecedenceLattice.Meet(a, b);
var result = SourcePrecedenceLattice.Join(a, meet);
Assert.Equal(a, result);
}
}
}
/// <summary>
/// Property: Absorption law 2 - Meet(a, Join(a, b)) = a
/// </summary>
[Fact]
public void Absorption_MeetJoin_ReturnsFirst()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
var join = SourcePrecedenceLattice.Join(a, b);
var result = SourcePrecedenceLattice.Meet(a, join);
Assert.Equal(a, result);
}
}
}
#endregion
#region Ordering Properties
/// <summary>
/// Property: Compare is antisymmetric - if Compare(a,b) > 0 then Compare(b,a) < 0
/// </summary>
[Fact]
public void Compare_IsAntisymmetric()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
var compareAB = SourcePrecedenceLattice.Compare(a, b);
var compareBA = SourcePrecedenceLattice.Compare(b, a);
if (compareAB > 0)
{
Assert.True(compareBA < 0);
}
else if (compareAB < 0)
{
Assert.True(compareBA > 0);
}
else
{
Assert.Equal(0, compareBA);
}
}
}
}
/// <summary>
/// Property: Compare is transitive - if Compare(a,b) > 0 and Compare(b,c) > 0 then Compare(a,c) > 0
/// </summary>
[Fact]
public void Compare_IsTransitive()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
foreach (var c in AllPrecedences)
{
var ab = SourcePrecedenceLattice.Compare(a, b);
var bc = SourcePrecedenceLattice.Compare(b, c);
var ac = SourcePrecedenceLattice.Compare(a, c);
if (ab > 0 && bc > 0)
{
Assert.True(ac > 0);
}
if (ab < 0 && bc < 0)
{
Assert.True(ac < 0);
}
}
}
}
}
/// <summary>
/// Property: Compare is reflexive - Compare(a, a) = 0
/// </summary>
[Fact]
public void Compare_IsReflexive()
{
foreach (var a in AllPrecedences)
{
Assert.Equal(0, SourcePrecedenceLattice.Compare(a, a));
}
}
#endregion
#region Join/Meet Bound Properties
/// <summary>
/// Property: Join returns an upper bound - Join(a, b) >= a AND Join(a, b) >= b
/// </summary>
[Fact]
public void Join_ReturnsUpperBound()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
var join = SourcePrecedenceLattice.Join(a, b);
Assert.True(SourcePrecedenceLattice.Compare(join, a) >= 0);
Assert.True(SourcePrecedenceLattice.Compare(join, b) >= 0);
}
}
}
/// <summary>
/// Property: Meet returns a lower bound - Meet(a, b) <= a AND Meet(a, b) <= b
/// </summary>
[Fact]
public void Meet_ReturnsLowerBound()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
var meet = SourcePrecedenceLattice.Meet(a, b);
Assert.True(SourcePrecedenceLattice.Compare(meet, a) <= 0);
Assert.True(SourcePrecedenceLattice.Compare(meet, b) <= 0);
}
}
}
/// <summary>
/// Property: Join is least upper bound - for all c, if c >= a and c >= b then c >= Join(a,b)
/// </summary>
[Fact]
public void Join_IsLeastUpperBound()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
var join = SourcePrecedenceLattice.Join(a, b);
foreach (var c in AllPrecedences)
{
var cGeA = SourcePrecedenceLattice.Compare(c, a) >= 0;
var cGeB = SourcePrecedenceLattice.Compare(c, b) >= 0;
if (cGeA && cGeB)
{
Assert.True(SourcePrecedenceLattice.Compare(c, join) >= 0);
}
}
}
}
}
/// <summary>
/// Property: Meet is greatest lower bound - for all c, if c <= a and c <= b then c <= Meet(a,b)
/// </summary>
[Fact]
public void Meet_IsGreatestLowerBound()
{
foreach (var a in AllPrecedences)
{
foreach (var b in AllPrecedences)
{
var meet = SourcePrecedenceLattice.Meet(a, b);
foreach (var c in AllPrecedences)
{
var cLeA = SourcePrecedenceLattice.Compare(c, a) <= 0;
var cLeB = SourcePrecedenceLattice.Compare(c, b) <= 0;
if (cLeA && cLeB)
{
Assert.True(SourcePrecedenceLattice.Compare(c, meet) <= 0);
}
}
}
}
}
#endregion
#region Bounded Lattice Properties
/// <summary>
/// Property: Unknown is the bottom element - Join(Unknown, a) = a
/// </summary>
[Fact]
public void Unknown_IsBottomElement()
{
foreach (var a in AllPrecedences)
{
var result = SourcePrecedenceLattice.Join(SourcePrecedence.Unknown, a);
Assert.Equal(a, result);
}
}
/// <summary>
/// Property: Vendor is the top element - Meet(Vendor, a) = a
/// </summary>
[Fact]
public void Vendor_IsTopElement()
{
foreach (var a in AllPrecedences)
{
var result = SourcePrecedenceLattice.Meet(SourcePrecedence.Vendor, a);
Assert.Equal(a, result);
}
}
#endregion
#region Merge Determinism
/// <summary>
/// Property: Merge is deterministic - same inputs always produce same output
/// </summary>
[Fact]
public void Merge_IsDeterministic()
{
var lattice = new SourcePrecedenceLattice();
var timestamp = new DateTimeOffset(2025, 12, 4, 12, 0, 0, TimeSpan.Zero);
var statements = new[]
{
CreateStatement("CVE-2024-001", "product-1", VexStatus.Affected, SourcePrecedence.ThirdParty, timestamp),
CreateStatement("CVE-2024-001", "product-1", VexStatus.NotAffected, SourcePrecedence.Vendor, timestamp),
CreateStatement("CVE-2024-001", "product-1", VexStatus.Fixed, SourcePrecedence.Maintainer, timestamp)
};
// Run merge 100 times and verify same result
var firstResult = lattice.Merge(statements);
for (int i = 0; i < 100; i++)
{
var result = lattice.Merge(statements);
Assert.Equal(firstResult.Status, result.Status);
Assert.Equal(firstResult.Source, result.Source);
Assert.Equal(firstResult.VulnerabilityId, result.VulnerabilityId);
}
}
/// <summary>
/// Property: Higher precedence always wins in merge
/// </summary>
[Fact]
public void Merge_HigherPrecedenceWins()
{
var lattice = new SourcePrecedenceLattice();
var timestamp = new DateTimeOffset(2025, 12, 4, 12, 0, 0, TimeSpan.Zero);
// Vendor should win over ThirdParty
var vendorStatement = CreateStatement("CVE-2024-001", "product-1", VexStatus.NotAffected, SourcePrecedence.Vendor, timestamp);
var thirdPartyStatement = CreateStatement("CVE-2024-001", "product-1", VexStatus.Affected, SourcePrecedence.ThirdParty, timestamp);
var result = lattice.Merge(vendorStatement, thirdPartyStatement);
Assert.Equal(SourcePrecedence.Vendor, result.Source);
Assert.Equal(VexStatus.NotAffected, result.Status);
}
/// <summary>
/// Property: More recent timestamp wins when precedence is equal
/// </summary>
[Fact]
public void Merge_MoreRecentTimestampWins_WhenPrecedenceEqual()
{
var lattice = new SourcePrecedenceLattice();
var olderTimestamp = new DateTimeOffset(2025, 12, 1, 12, 0, 0, TimeSpan.Zero);
var newerTimestamp = new DateTimeOffset(2025, 12, 4, 12, 0, 0, TimeSpan.Zero);
var olderStatement = CreateStatement("CVE-2024-001", "product-1", VexStatus.Affected, SourcePrecedence.Maintainer, olderTimestamp);
var newerStatement = CreateStatement("CVE-2024-001", "product-1", VexStatus.Fixed, SourcePrecedence.Maintainer, newerTimestamp);
var result = lattice.Merge(olderStatement, newerStatement);
Assert.Equal(VexStatus.Fixed, result.Status);
Assert.Equal(newerTimestamp, result.Timestamp);
}
private static VexStatement CreateStatement(
string vulnId,
string productId,
VexStatus status,
SourcePrecedence source,
DateTimeOffset? timestamp)
{
return new VexStatement
{
VulnerabilityId = vulnId,
ProductId = productId,
Status = status,
Source = source,
Timestamp = timestamp
};
}
#endregion
}

View File

@@ -1,149 +0,0 @@
// =============================================================================
// SpdxParserTests.cs
// Golden-file tests for SPDX SBOM parsing
// Part of Task T24: Golden-file tests for determinism
// =============================================================================
using FluentAssertions;
using StellaOps.AirGap.Importer.Reconciliation;
using StellaOps.AirGap.Importer.Reconciliation.Parsers;
namespace StellaOps.AirGap.Importer.Tests.Reconciliation;
public sealed class SpdxParserTests
{
private static readonly string FixturesPath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Reconciliation", "Fixtures");
[Fact]
public async Task ParseAsync_ValidSpdx_ExtractsAllSubjects()
{
// Arrange
var parser = new SpdxParser();
var filePath = Path.Combine(FixturesPath, "sample.spdx.json");
if (!File.Exists(filePath))
{
return;
}
// Act
var result = await parser.ParseAsync(filePath);
// Assert
result.IsSuccess.Should().BeTrue();
result.Format.Should().Be(SbomFormat.Spdx);
result.SpecVersion.Should().Be("2.3");
result.SerialNumber.Should().Be("https://example.com/test-app/1.0.0");
result.GeneratorTool.Should().Contain("syft");
// Should have 3 packages with SHA256 checksums
result.Subjects.Should().HaveCount(3);
// Verify subjects are sorted by digest
result.Subjects.Should().BeInAscendingOrder(s => s.Digest, StringComparer.Ordinal);
}
[Fact]
public async Task ParseAsync_ExtractsPrimarySubject()
{
// Arrange
var parser = new SpdxParser();
var filePath = Path.Combine(FixturesPath, "sample.spdx.json");
if (!File.Exists(filePath))
{
return;
}
// Act
var result = await parser.ParseAsync(filePath);
// Assert
result.PrimarySubject.Should().NotBeNull();
result.PrimarySubject!.Name.Should().Be("test-app");
result.PrimarySubject.Version.Should().Be("1.0.0");
result.PrimarySubject.SpdxId.Should().Be("SPDXRef-Package-test-app");
}
[Fact]
public async Task ParseAsync_ExtractsPurls()
{
// Arrange
var parser = new SpdxParser();
var filePath = Path.Combine(FixturesPath, "sample.spdx.json");
if (!File.Exists(filePath))
{
return;
}
// Act
var result = await parser.ParseAsync(filePath);
// Assert - check for components with purls
var zlib = result.Subjects.FirstOrDefault(s => s.Name == "zlib");
zlib.Should().NotBeNull();
zlib!.Purl.Should().Be("pkg:generic/zlib@1.2.11");
}
[Fact]
public async Task ParseAsync_SubjectDigestsAreNormalized()
{
// Arrange
var parser = new SpdxParser();
var filePath = Path.Combine(FixturesPath, "sample.spdx.json");
if (!File.Exists(filePath))
{
return;
}
// Act
var result = await parser.ParseAsync(filePath);
// Assert - all digests should be normalized sha256:lowercase format
foreach (var subject in result.Subjects)
{
subject.Digest.Should().StartWith("sha256:");
subject.Digest[7..].Should().MatchRegex("^[a-f0-9]{64}$");
}
}
[Fact]
public void DetectFormat_SpdxFile_ReturnsSpdx()
{
var parser = new SpdxParser();
parser.DetectFormat("test.spdx.json").Should().Be(SbomFormat.Spdx);
}
[Fact]
public void DetectFormat_NonSpdxFile_ReturnsUnknown()
{
var parser = new SpdxParser();
parser.DetectFormat("test.cdx.json").Should().Be(SbomFormat.Unknown);
parser.DetectFormat("test.json").Should().Be(SbomFormat.Unknown);
}
[Fact]
public async Task ParseAsync_Deterministic_SameOutputForSameInput()
{
// Arrange
var parser = new SpdxParser();
var filePath = Path.Combine(FixturesPath, "sample.spdx.json");
if (!File.Exists(filePath))
{
return;
}
// Act - parse twice
var result1 = await parser.ParseAsync(filePath);
var result2 = await parser.ParseAsync(filePath);
// Assert - results should be identical and in same order
result1.Subjects.Select(s => s.Digest).Should().Equal(result2.Subjects.Select(s => s.Digest));
result1.Subjects.Select(s => s.Name).Should().Equal(result2.Subjects.Select(s => s.Name));
}
}

View File

@@ -1,72 +0,0 @@
using StellaOps.AirGap.Importer.Contracts;
using StellaOps.AirGap.Importer.Validation;
namespace StellaOps.AirGap.Importer.Tests;
public class ReplayVerifierTests
{
private readonly ReplayVerifier _verifier = new();
[Fact]
public void FullRecompute_succeeds_when_hashes_match_and_fresh()
{
var now = DateTimeOffset.Parse("2025-12-02T01:00:00Z");
var request = new ReplayVerificationRequest(
"aa".PadRight(64, 'a'),
"bb".PadRight(64, 'b'),
"aa".PadRight(64, 'a'),
"bb".PadRight(64, 'b'),
now.AddHours(-4),
24,
"cc".PadRight(64, 'c'),
"cc".PadRight(64, 'c'),
ReplayDepth.FullRecompute);
var result = _verifier.Verify(request, now);
Assert.True(result.IsValid);
Assert.Equal("full-recompute-passed", result.Reason);
}
[Fact]
public void Detects_hash_drift()
{
var now = DateTimeOffset.UtcNow;
var request = new ReplayVerificationRequest(
"aa".PadRight(64, 'a'),
"bb".PadRight(64, 'b'),
"00".PadRight(64, '0'),
"bb".PadRight(64, 'b'),
now,
1,
null,
null,
ReplayDepth.HashOnly);
var result = _verifier.Verify(request, now);
Assert.False(result.IsValid);
Assert.Equal("manifest-hash-drift", result.Reason);
}
[Fact]
public void PolicyFreeze_requires_matching_policy_hash()
{
var now = DateTimeOffset.UtcNow;
var request = new ReplayVerificationRequest(
"aa".PadRight(64, 'a'),
"bb".PadRight(64, 'b'),
"aa".PadRight(64, 'a'),
"bb".PadRight(64, 'b'),
now,
12,
"bundle-policy",
"sealed-policy-other",
ReplayDepth.PolicyFreeze);
var result = _verifier.Verify(request, now);
Assert.False(result.IsValid);
Assert.Equal("policy-hash-drift", result.Reason);
}
}

View File

@@ -1,40 +0,0 @@
using StellaOps.AirGap.Importer.Validation;
namespace StellaOps.AirGap.Importer.Tests;
public class RootRotationPolicyTests
{
[Fact]
public void RequiresTwoApprovers()
{
var policy = new RootRotationPolicy();
var result = policy.Validate(new Dictionary<string, byte[]>(), new Dictionary<string, byte[]> { ["k1"] = new byte[] { 1 } }, new[] { "a" });
Assert.False(result.IsValid);
Assert.Equal("rotation-dual-approval-required", result.Reason);
}
[Fact]
public void RejectsNoChange()
{
var policy = new RootRotationPolicy();
var result = policy.Validate(
new Dictionary<string, byte[]> { ["k1"] = new byte[] { 1 } },
new Dictionary<string, byte[]> { ["k1"] = new byte[] { 1 } },
new[] { "a", "b" });
Assert.False(result.IsValid);
Assert.Equal("rotation-no-change", result.Reason);
}
[Fact]
public void AcceptsRotationWithDualApproval()
{
var policy = new RootRotationPolicy();
var result = policy.Validate(
new Dictionary<string, byte[]> { ["old"] = new byte[] { 1 } },
new Dictionary<string, byte[]> { ["new"] = new byte[] { 2 } },
new[] { "a", "b" });
Assert.True(result.IsValid);
Assert.Equal("rotation-approved", result.Reason);
}
}

View File

@@ -1,22 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../../src/AirGap/StellaOps.AirGap.Importer/StellaOps.AirGap.Importer.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="Reconciliation/Fixtures/**/*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -1,42 +0,0 @@
using StellaOps.AirGap.Importer.Validation;
namespace StellaOps.AirGap.Importer.Tests;
public class TufMetadataValidatorTests
{
[Fact]
public void RejectsInvalidJson()
{
var validator = new TufMetadataValidator();
var result = validator.Validate("{}", "{}", "{}");
Assert.False(result.IsValid);
}
[Fact]
public void AcceptsConsistentSnapshotHash()
{
var validator = new TufMetadataValidator();
var root = "{\"version\":1,\"expiresUtc\":\"2030-01-01T00:00:00Z\"}";
var snapshot = "{\"version\":1,\"expiresUtc\":\"2030-01-01T00:00:00Z\",\"meta\":{\"snapshot\":{\"hashes\":{\"sha256\":\"abc\"}}}}";
var timestamp = "{\"version\":1,\"expiresUtc\":\"2030-01-01T00:00:00Z\",\"snapshot\":{\"meta\":{\"hashes\":{\"sha256\":\"abc\"}}}}";
var result = validator.Validate(root, snapshot, timestamp);
Assert.True(result.IsValid);
Assert.Equal("tuf-metadata-valid", result.Reason);
}
[Fact]
public void DetectsHashMismatch()
{
var validator = new TufMetadataValidator();
var root = "{\"version\":1,\"expiresUtc\":\"2030-01-01T00:00:00Z\"}";
var snapshot = "{\"version\":1,\"expiresUtc\":\"2030-01-01T00:00:00Z\",\"meta\":{\"snapshot\":{\"hashes\":{\"sha256\":\"abc\"}}}}";
var timestamp = "{\"version\":1,\"expiresUtc\":\"2030-01-01T00:00:00Z\",\"snapshot\":{\"meta\":{\"hashes\":{\"sha256\":\"def\"}}}}";
var result = validator.Validate(root, snapshot, timestamp);
Assert.False(result.IsValid);
Assert.Equal("tuf-snapshot-hash-mismatch", result.Reason);
}
}

View File

@@ -1,204 +0,0 @@
using System.Security.Cryptography;
using System.Text;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using StellaOps.AirGap.Importer.Contracts;
using StellaOps.AirGap.Importer.Quarantine;
using StellaOps.AirGap.Importer.Validation;
using StellaOps.AirGap.Importer.Versioning;
namespace StellaOps.AirGap.Importer.Tests.Validation;
public sealed class ImportValidatorIntegrationTests
{
[Fact]
public async Task ValidateAsync_WhenNonMonotonic_ShouldFailAndQuarantine()
{
var quarantine = new CapturingQuarantineService();
var monotonicity = new FixedMonotonicityChecker(isMonotonic: false);
var validator = new ImportValidator(
new DsseVerifier(),
new TufMetadataValidator(),
new MerkleRootCalculator(),
new RootRotationPolicy(),
monotonicity,
quarantine,
NullLogger<ImportValidator>.Instance);
var tempRoot = Path.Combine(Path.GetTempPath(), "stellaops-airgap-tests", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempRoot);
var bundlePath = Path.Combine(tempRoot, "bundle.tar.zst");
await File.WriteAllTextAsync(bundlePath, "bundle-bytes");
try
{
var (envelope, trustRoots) = CreateValidDsse();
var trustStore = new TrustStore();
trustStore.LoadActive(new Dictionary<string, byte[]>());
trustStore.StagePending(new Dictionary<string, byte[]> { ["pending-key"] = new byte[] { 1, 2, 3 } });
var request = new ImportValidationRequest(
TenantId: "tenant-a",
BundleType: "offline-kit",
BundleDigest: "sha256:bundle",
BundlePath: bundlePath,
ManifestJson: "{\"version\":\"1.0.0\"}",
ManifestVersion: "1.0.0",
ManifestCreatedAt: DateTimeOffset.Parse("2025-12-15T00:00:00Z"),
ForceActivate: false,
ForceActivateReason: null,
Envelope: envelope,
TrustRoots: trustRoots,
RootJson: """
{"version":1,"expiresUtc":"2025-12-31T00:00:00Z"}
""",
SnapshotJson: """
{"version":1,"expiresUtc":"2025-12-31T00:00:00Z","meta":{"snapshot":{"hashes":{"sha256":"abc"}}}}
""",
TimestampJson: """
{"version":1,"expiresUtc":"2025-12-31T00:00:00Z","snapshot":{"meta":{"hashes":{"sha256":"abc"}}}}
""",
PayloadEntries: new[] { new NamedStream("payload.txt", new MemoryStream(Encoding.UTF8.GetBytes("hello"))) },
TrustStore: trustStore,
ApproverIds: new[] { "approver-a", "approver-b" });
var result = await validator.ValidateAsync(request);
result.IsValid.Should().BeFalse();
result.Reason.Should().Contain("version-non-monotonic");
quarantine.Requests.Should().HaveCount(1);
quarantine.Requests[0].TenantId.Should().Be("tenant-a");
quarantine.Requests[0].ReasonCode.Should().Contain("version-non-monotonic");
}
finally
{
try
{
Directory.Delete(tempRoot, recursive: true);
}
catch
{
// best-effort cleanup
}
}
}
private static (DsseEnvelope envelope, TrustRootConfig trustRoots) CreateValidDsse()
{
using var rsa = RSA.Create(2048);
var publicKey = rsa.ExportSubjectPublicKeyInfo();
var fingerprint = Convert.ToHexString(SHA256.HashData(publicKey)).ToLowerInvariant();
var payloadType = "application/vnd.in-toto+json";
var payloadBytes = Encoding.UTF8.GetBytes("{\"hello\":\"world\"}");
var payloadBase64 = Convert.ToBase64String(payloadBytes);
var pae = BuildPae(payloadType, payloadBytes);
var signature = rsa.SignData(pae, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
var envelope = new DsseEnvelope(
PayloadType: payloadType,
Payload: payloadBase64,
Signatures: new[] { new DsseSignature("key-1", Convert.ToBase64String(signature)) });
var trustRoots = new TrustRootConfig(
RootBundlePath: "(memory)",
TrustedKeyFingerprints: new[] { fingerprint },
AllowedSignatureAlgorithms: new[] { "rsa-pss-sha256" },
NotBeforeUtc: null,
NotAfterUtc: null,
PublicKeys: new Dictionary<string, byte[]> { ["key-1"] = publicKey });
return (envelope, trustRoots);
}
private static byte[] BuildPae(string payloadType, byte[] payloadBytes)
{
const string paePrefix = "DSSEv1";
var payload = Encoding.UTF8.GetString(payloadBytes);
var parts = new[]
{
paePrefix,
payloadType,
payload
};
var paeBuilder = new StringBuilder();
paeBuilder.Append("PAE:");
paeBuilder.Append(parts.Length);
foreach (var part in parts)
{
paeBuilder.Append(' ');
paeBuilder.Append(part.Length);
paeBuilder.Append(' ');
paeBuilder.Append(part);
}
return Encoding.UTF8.GetBytes(paeBuilder.ToString());
}
private sealed class FixedMonotonicityChecker : IVersionMonotonicityChecker
{
private readonly bool _isMonotonic;
public FixedMonotonicityChecker(bool isMonotonic)
{
_isMonotonic = isMonotonic;
}
public Task<MonotonicityCheckResult> CheckAsync(
string tenantId,
string bundleType,
BundleVersion incomingVersion,
CancellationToken cancellationToken = default)
{
return Task.FromResult(new MonotonicityCheckResult(
IsMonotonic: _isMonotonic,
CurrentVersion: new BundleVersion(2, 0, 0, DateTimeOffset.Parse("2025-12-14T00:00:00Z")),
CurrentBundleDigest: "sha256:current",
CurrentActivatedAt: DateTimeOffset.Parse("2025-12-14T00:00:00Z"),
ReasonCode: _isMonotonic ? "MONOTONIC_OK" : "VERSION_NON_MONOTONIC"));
}
public Task RecordActivationAsync(
string tenantId,
string bundleType,
BundleVersion version,
string bundleDigest,
bool wasForceActivated = false,
string? forceActivateReason = null,
CancellationToken cancellationToken = default)
{
return Task.CompletedTask;
}
}
private sealed class CapturingQuarantineService : IQuarantineService
{
public List<QuarantineRequest> Requests { get; } = new();
public Task<QuarantineResult> QuarantineAsync(QuarantineRequest request, CancellationToken cancellationToken = default)
{
Requests.Add(request);
return Task.FromResult(new QuarantineResult(
Success: true,
QuarantineId: "test",
QuarantinePath: "(memory)",
QuarantinedAt: DateTimeOffset.UnixEpoch));
}
public Task<IReadOnlyList<QuarantineEntry>> ListAsync(string tenantId, QuarantineListOptions? options = null, CancellationToken cancellationToken = default) =>
Task.FromResult<IReadOnlyList<QuarantineEntry>>(Array.Empty<QuarantineEntry>());
public Task<bool> RemoveAsync(string tenantId, string quarantineId, string removalReason, CancellationToken cancellationToken = default) =>
Task.FromResult(false);
public Task<int> CleanupExpiredAsync(TimeSpan retentionPeriod, CancellationToken cancellationToken = default) =>
Task.FromResult(0);
}
}

View File

@@ -1,165 +0,0 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using FluentAssertions;
using StellaOps.AirGap.Importer.Validation;
namespace StellaOps.AirGap.Importer.Tests.Validation;
public sealed class RekorOfflineReceiptVerifierTests
{
[Fact]
public async Task VerifyAsync_ValidReceiptAndCheckpoint_Succeeds()
{
var temp = Path.Combine(Path.GetTempPath(), "stellaops-rekor-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(temp);
try
{
// Leaf 0 is the DSSE digest we verify for inclusion.
var dsseSha256 = SHA256.HashData(Encoding.UTF8.GetBytes("dsse-envelope"));
var otherDsseSha256 = SHA256.HashData(Encoding.UTF8.GetBytes("other-envelope"));
var leaf0 = HashLeaf(dsseSha256);
var leaf1 = HashLeaf(otherDsseSha256);
var root = HashInterior(leaf0, leaf1);
var rootBase64 = Convert.ToBase64String(root);
var treeSize = 2L;
var origin = "rekor.sigstore.dev - 2605736670972794746";
var timestamp = "1700000000";
var canonicalBody = $"{origin}\n{treeSize}\n{rootBase64}\n{timestamp}\n";
using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var signature = ecdsa.SignData(Encoding.UTF8.GetBytes(canonicalBody), HashAlgorithmName.SHA256);
var signatureBase64 = Convert.ToBase64String(signature);
var checkpointPath = Path.Combine(temp, "checkpoint.sig");
await File.WriteAllTextAsync(
checkpointPath,
canonicalBody + $"sig {signatureBase64}\n",
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var publicKeyPath = Path.Combine(temp, "rekor-pub.pem");
await File.WriteAllTextAsync(
publicKeyPath,
WrapPem("PUBLIC KEY", ecdsa.ExportSubjectPublicKeyInfo()),
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var receiptPath = Path.Combine(temp, "rekor-receipt.json");
var receiptJson = JsonSerializer.Serialize(new
{
uuid = "uuid-1",
logIndex = 0,
rootHash = Convert.ToHexString(root).ToLowerInvariant(),
hashes = new[] { Convert.ToHexString(leaf1).ToLowerInvariant() },
checkpoint = "checkpoint.sig"
}, new JsonSerializerOptions(JsonSerializerDefaults.Web) { WriteIndented = true });
await File.WriteAllTextAsync(receiptPath, receiptJson, new UTF8Encoding(false));
var result = await RekorOfflineReceiptVerifier.VerifyAsync(receiptPath, dsseSha256, publicKeyPath, CancellationToken.None);
result.Verified.Should().BeTrue();
result.CheckpointSignatureVerified.Should().BeTrue();
result.RekorUuid.Should().Be("uuid-1");
result.LogIndex.Should().Be(0);
result.TreeSize.Should().Be(2);
result.ExpectedRootHash.Should().Be(Convert.ToHexString(root).ToLowerInvariant());
result.ComputedRootHash.Should().Be(Convert.ToHexString(root).ToLowerInvariant());
}
finally
{
Directory.Delete(temp, recursive: true);
}
}
[Fact]
public async Task VerifyAsync_TamperedCheckpointSignature_Fails()
{
var temp = Path.Combine(Path.GetTempPath(), "stellaops-rekor-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(temp);
try
{
var dsseSha256 = SHA256.HashData(Encoding.UTF8.GetBytes("dsse-envelope"));
var otherDsseSha256 = SHA256.HashData(Encoding.UTF8.GetBytes("other-envelope"));
var leaf0 = HashLeaf(dsseSha256);
var leaf1 = HashLeaf(otherDsseSha256);
var root = HashInterior(leaf0, leaf1);
var rootBase64 = Convert.ToBase64String(root);
var treeSize = 2L;
var origin = "rekor.sigstore.dev - 2605736670972794746";
var timestamp = "1700000000";
var canonicalBody = $"{origin}\n{treeSize}\n{rootBase64}\n{timestamp}\n";
using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var signature = ecdsa.SignData(Encoding.UTF8.GetBytes(canonicalBody), HashAlgorithmName.SHA256);
signature[0] ^= 0xFF; // tamper
var checkpointPath = Path.Combine(temp, "checkpoint.sig");
await File.WriteAllTextAsync(
checkpointPath,
canonicalBody + $"sig {Convert.ToBase64String(signature)}\n",
new UTF8Encoding(false));
var publicKeyPath = Path.Combine(temp, "rekor-pub.pem");
await File.WriteAllTextAsync(
publicKeyPath,
WrapPem("PUBLIC KEY", ecdsa.ExportSubjectPublicKeyInfo()),
new UTF8Encoding(false));
var receiptPath = Path.Combine(temp, "rekor-receipt.json");
var receiptJson = JsonSerializer.Serialize(new
{
uuid = "uuid-1",
logIndex = 0,
rootHash = Convert.ToHexString(root).ToLowerInvariant(),
hashes = new[] { Convert.ToHexString(leaf1).ToLowerInvariant() },
checkpoint = "checkpoint.sig"
}, new JsonSerializerOptions(JsonSerializerDefaults.Web) { WriteIndented = true });
await File.WriteAllTextAsync(receiptPath, receiptJson, new UTF8Encoding(false));
var result = await RekorOfflineReceiptVerifier.VerifyAsync(receiptPath, dsseSha256, publicKeyPath, CancellationToken.None);
result.Verified.Should().BeFalse();
result.FailureReason.Should().Contain("checkpoint signature", because: result.FailureReason);
}
finally
{
Directory.Delete(temp, recursive: true);
}
}
private static byte[] HashLeaf(byte[] leafData)
{
var buffer = new byte[1 + leafData.Length];
buffer[0] = 0x00;
leafData.CopyTo(buffer, 1);
return SHA256.HashData(buffer);
}
private static byte[] HashInterior(byte[] left, byte[] right)
{
var buffer = new byte[1 + left.Length + right.Length];
buffer[0] = 0x01;
left.CopyTo(buffer, 1);
right.CopyTo(buffer, 1 + left.Length);
return SHA256.HashData(buffer);
}
private static string WrapPem(string label, byte[] derBytes)
{
var base64 = Convert.ToBase64String(derBytes);
var sb = new StringBuilder();
sb.AppendLine($"-----BEGIN {label}-----");
for (var i = 0; i < base64.Length; i += 64)
{
sb.AppendLine(base64.Substring(i, Math.Min(64, base64.Length - i)));
}
sb.AppendLine($"-----END {label}-----");
return sb.ToString();
}
}

View File

@@ -1,79 +0,0 @@
using FluentAssertions;
using StellaOps.AirGap.Importer.Versioning;
namespace StellaOps.AirGap.Importer.Tests.Versioning;
public sealed class BundleVersionTests
{
[Fact]
public void Parse_ShouldParseSemVer()
{
var createdAt = new DateTimeOffset(2025, 12, 14, 0, 0, 0, TimeSpan.Zero);
var version = BundleVersion.Parse("1.2.3", createdAt);
version.Major.Should().Be(1);
version.Minor.Should().Be(2);
version.Patch.Should().Be(3);
version.Prerelease.Should().BeNull();
version.CreatedAt.Should().Be(createdAt);
version.SemVer.Should().Be("1.2.3");
}
[Fact]
public void Parse_ShouldParsePrerelease()
{
var createdAt = new DateTimeOffset(2025, 12, 14, 0, 0, 0, TimeSpan.Zero);
var version = BundleVersion.Parse("1.2.3-edge.1", createdAt);
version.SemVer.Should().Be("1.2.3-edge.1");
version.Prerelease.Should().Be("edge.1");
}
[Fact]
public void IsNewerThan_ShouldCompareMajorMinorPatch()
{
var a = new BundleVersion(1, 2, 3, DateTimeOffset.UnixEpoch);
var b = new BundleVersion(2, 0, 0, DateTimeOffset.UnixEpoch);
b.IsNewerThan(a).Should().BeTrue();
a.IsNewerThan(b).Should().BeFalse();
}
[Fact]
public void IsNewerThan_ShouldTreatReleaseAsNewerThanPrerelease()
{
var now = new DateTimeOffset(2025, 12, 14, 0, 0, 0, TimeSpan.Zero);
var prerelease = new BundleVersion(1, 2, 3, now, "alpha");
var release = new BundleVersion(1, 2, 3, now, null);
release.IsNewerThan(prerelease).Should().BeTrue();
prerelease.IsNewerThan(release).Should().BeFalse();
}
[Fact]
public void IsNewerThan_ShouldOrderPrereleaseIdentifiers()
{
var now = new DateTimeOffset(2025, 12, 14, 0, 0, 0, TimeSpan.Zero);
var alpha = new BundleVersion(1, 2, 3, now, "alpha");
var beta = new BundleVersion(1, 2, 3, now, "beta");
var rc1 = new BundleVersion(1, 2, 3, now, "rc.1");
var rc2 = new BundleVersion(1, 2, 3, now, "rc.2");
beta.IsNewerThan(alpha).Should().BeTrue();
rc1.IsNewerThan(beta).Should().BeTrue();
rc2.IsNewerThan(rc1).Should().BeTrue();
}
[Fact]
public void IsNewerThan_ShouldUseCreatedAtAsTiebreaker()
{
var earlier = new DateTimeOffset(2025, 12, 14, 0, 0, 0, TimeSpan.Zero);
var later = earlier.AddMinutes(1);
var a = new BundleVersion(1, 2, 3, earlier, "edge");
var b = new BundleVersion(1, 2, 3, later, "edge");
b.IsNewerThan(a).Should().BeTrue();
a.IsNewerThan(b).Should().BeFalse();
}
}

View File

@@ -1,157 +0,0 @@
using FluentAssertions;
using StellaOps.AirGap.Importer.Versioning;
namespace StellaOps.AirGap.Importer.Tests.Versioning;
public sealed class VersionMonotonicityCheckerTests
{
[Fact]
public async Task CheckAsync_WhenNoCurrent_ShouldBeFirstActivation()
{
var store = new InMemoryBundleVersionStore();
var checker = new VersionMonotonicityChecker(store, new FixedTimeProvider(DateTimeOffset.Parse("2025-12-14T00:00:00Z")));
var incoming = BundleVersion.Parse("1.0.0", DateTimeOffset.Parse("2025-12-14T00:00:00Z"));
var result = await checker.CheckAsync("tenant-a", "offline-kit", incoming);
result.IsMonotonic.Should().BeTrue();
result.ReasonCode.Should().Be("FIRST_ACTIVATION");
result.CurrentVersion.Should().BeNull();
result.CurrentBundleDigest.Should().BeNull();
}
[Fact]
public async Task CheckAsync_WhenOlder_ShouldBeNonMonotonic()
{
var store = new InMemoryBundleVersionStore();
await store.UpsertAsync(new BundleVersionRecord(
TenantId: "tenant-a",
BundleType: "offline-kit",
VersionString: "2.0.0",
Major: 2,
Minor: 0,
Patch: 0,
Prerelease: null,
BundleCreatedAt: DateTimeOffset.Parse("2025-12-14T00:00:00Z"),
BundleDigest: "sha256:current",
ActivatedAt: DateTimeOffset.Parse("2025-12-14T00:00:00Z"),
WasForceActivated: false,
ForceActivateReason: null));
var checker = new VersionMonotonicityChecker(store, new FixedTimeProvider(DateTimeOffset.Parse("2025-12-14T00:00:00Z")));
var incoming = BundleVersion.Parse("1.0.0", DateTimeOffset.Parse("2025-12-14T00:00:00Z"));
var result = await checker.CheckAsync("tenant-a", "offline-kit", incoming);
result.IsMonotonic.Should().BeFalse();
result.ReasonCode.Should().Be("VERSION_NON_MONOTONIC");
result.CurrentVersion.Should().NotBeNull();
result.CurrentVersion!.SemVer.Should().Be("2.0.0");
}
[Fact]
public async Task RecordActivationAsync_WhenNonMonotonicWithoutForce_ShouldThrow()
{
var store = new InMemoryBundleVersionStore();
await store.UpsertAsync(new BundleVersionRecord(
TenantId: "tenant-a",
BundleType: "offline-kit",
VersionString: "2.0.0",
Major: 2,
Minor: 0,
Patch: 0,
Prerelease: null,
BundleCreatedAt: DateTimeOffset.Parse("2025-12-14T00:00:00Z"),
BundleDigest: "sha256:current",
ActivatedAt: DateTimeOffset.Parse("2025-12-14T00:00:00Z"),
WasForceActivated: false,
ForceActivateReason: null));
var checker = new VersionMonotonicityChecker(store, new FixedTimeProvider(DateTimeOffset.Parse("2025-12-15T00:00:00Z")));
var incoming = BundleVersion.Parse("1.0.0", DateTimeOffset.Parse("2025-12-15T00:00:00Z"));
var act = () => checker.RecordActivationAsync("tenant-a", "offline-kit", incoming, "sha256:new");
await act.Should().ThrowAsync<InvalidOperationException>();
}
[Fact]
public async Task RecordActivationAsync_WhenForced_ShouldWriteForceFields()
{
var store = new InMemoryBundleVersionStore();
await store.UpsertAsync(new BundleVersionRecord(
TenantId: "tenant-a",
BundleType: "offline-kit",
VersionString: "2.0.0",
Major: 2,
Minor: 0,
Patch: 0,
Prerelease: null,
BundleCreatedAt: DateTimeOffset.Parse("2025-12-14T00:00:00Z"),
BundleDigest: "sha256:current",
ActivatedAt: DateTimeOffset.Parse("2025-12-14T00:00:00Z"),
WasForceActivated: false,
ForceActivateReason: null));
var checker = new VersionMonotonicityChecker(store, new FixedTimeProvider(DateTimeOffset.Parse("2025-12-15T00:00:00Z")));
var incoming = BundleVersion.Parse("1.0.0", DateTimeOffset.Parse("2025-12-15T00:00:00Z"));
await checker.RecordActivationAsync(
"tenant-a",
"offline-kit",
incoming,
"sha256:new",
wasForceActivated: true,
forceActivateReason: "manual rollback permitted");
var current = await store.GetCurrentAsync("tenant-a", "offline-kit");
current.Should().NotBeNull();
current!.WasForceActivated.Should().BeTrue();
current.ForceActivateReason.Should().Be("manual rollback permitted");
current.BundleDigest.Should().Be("sha256:new");
}
private sealed class InMemoryBundleVersionStore : IBundleVersionStore
{
private BundleVersionRecord? _current;
private readonly List<BundleVersionRecord> _history = new();
public Task<BundleVersionRecord?> GetCurrentAsync(string tenantId, string bundleType, CancellationToken ct = default)
{
return Task.FromResult(_current is not null &&
_current.TenantId.Equals(tenantId, StringComparison.Ordinal) &&
_current.BundleType.Equals(bundleType, StringComparison.Ordinal)
? _current
: null);
}
public Task UpsertAsync(BundleVersionRecord record, CancellationToken ct = default)
{
_current = record;
_history.Insert(0, record);
return Task.CompletedTask;
}
public Task<IReadOnlyList<BundleVersionRecord>> GetHistoryAsync(string tenantId, string bundleType, int limit = 10, CancellationToken ct = default)
{
var items = _history
.Where(r => r.TenantId.Equals(tenantId, StringComparison.Ordinal) && r.BundleType.Equals(bundleType, StringComparison.Ordinal))
.Take(limit)
.ToArray();
return Task.FromResult<IReadOnlyList<BundleVersionRecord>>(items);
}
}
private sealed class FixedTimeProvider : TimeProvider
{
private readonly DateTimeOffset _utcNow;
public FixedTimeProvider(DateTimeOffset utcNow)
{
_utcNow = utcNow;
}
public override DateTimeOffset GetUtcNow() => _utcNow;
}
}

View File

@@ -1,35 +0,0 @@
using Microsoft.Extensions.Options;
using StellaOps.AirGap.Time.Config;
using StellaOps.AirGap.Time.Models;
namespace StellaOps.AirGap.Time.Tests;
public class AirGapOptionsValidatorTests
{
[Fact]
public void FailsWhenTenantMissing()
{
var opts = new AirGapOptions { TenantId = "" };
var validator = new AirGapOptionsValidator();
var result = validator.Validate(null, opts);
Assert.True(result.Failed);
}
[Fact]
public void FailsWhenWarningExceedsBreach()
{
var opts = new AirGapOptions { TenantId = "t", Staleness = new StalenessOptions { WarningSeconds = 20, BreachSeconds = 10 } };
var validator = new AirGapOptionsValidator();
var result = validator.Validate(null, opts);
Assert.True(result.Failed);
}
[Fact]
public void SucceedsForValidOptions()
{
var opts = new AirGapOptions { TenantId = "t", Staleness = new StalenessOptions { WarningSeconds = 10, BreachSeconds = 20 } };
var validator = new AirGapOptionsValidator();
var result = validator.Validate(null, opts);
Assert.True(result.Succeeded);
}
}

View File

@@ -1 +0,0 @@
global using Xunit;

View File

@@ -1,93 +0,0 @@
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Services;
namespace StellaOps.AirGap.Time.Tests;
/// <summary>
/// Tests for Rfc3161Verifier with real SignedCms verification.
/// Per AIRGAP-TIME-57-001: Trusted time-anchor service.
/// </summary>
public class Rfc3161VerifierTests
{
private readonly Rfc3161Verifier _verifier = new();
[Fact]
public void Verify_ReturnsFailure_WhenTrustRootsEmpty()
{
var token = new byte[] { 0x01, 0x02, 0x03 };
var result = _verifier.Verify(token, Array.Empty<TimeTrustRoot>(), out var anchor);
Assert.False(result.IsValid);
Assert.Equal("rfc3161-trust-roots-required", result.Reason);
Assert.Equal(TimeAnchor.Unknown, anchor);
}
[Fact]
public void Verify_ReturnsFailure_WhenTokenEmpty()
{
var trust = new[] { new TimeTrustRoot("tsa-root", new byte[] { 0x01 }, "rsa") };
var result = _verifier.Verify(ReadOnlySpan<byte>.Empty, trust, out var anchor);
Assert.False(result.IsValid);
Assert.Equal("rfc3161-token-empty", result.Reason);
Assert.Equal(TimeAnchor.Unknown, anchor);
}
[Fact]
public void Verify_ReturnsFailure_WhenInvalidAsn1Structure()
{
var token = new byte[] { 0x01, 0x02, 0x03 }; // Invalid ASN.1
var trust = new[] { new TimeTrustRoot("tsa-root", new byte[] { 0x01 }, "rsa") };
var result = _verifier.Verify(token, trust, out var anchor);
Assert.False(result.IsValid);
Assert.Contains("rfc3161-", result.Reason);
Assert.Equal(TimeAnchor.Unknown, anchor);
}
[Fact]
public void Verify_ProducesTokenDigest()
{
var token = new byte[] { 0x30, 0x00 }; // Empty SEQUENCE (minimal valid ASN.1)
var trust = new[] { new TimeTrustRoot("tsa-root", new byte[] { 0x01 }, "rsa") };
var result = _verifier.Verify(token, trust, out _);
// Should fail on CMS decode but attempt was made
Assert.False(result.IsValid);
Assert.Contains("rfc3161-", result.Reason);
}
[Fact]
public void Verify_HandlesExceptionsGracefully()
{
// Create bytes that might cause internal exceptions
var token = new byte[256];
new Random(42).NextBytes(token);
var trust = new[] { new TimeTrustRoot("tsa-root", new byte[] { 0x01 }, "rsa") };
var result = _verifier.Verify(token, trust, out var anchor);
// Should not throw, should return failure result
Assert.False(result.IsValid);
Assert.Contains("rfc3161-", result.Reason);
Assert.Equal(TimeAnchor.Unknown, anchor);
}
[Fact]
public void Verify_ReportsDecodeErrorForMalformedCms()
{
// Create something that looks like CMS but isn't valid
var token = new byte[] { 0x30, 0x82, 0x00, 0x10, 0x06, 0x09 };
var trust = new[] { new TimeTrustRoot("tsa-root", new byte[] { 0x01 }, "rsa") };
var result = _verifier.Verify(token, trust, out _);
Assert.False(result.IsValid);
// Should report either decode or error
Assert.True(result.Reason?.Contains("rfc3161-") ?? false);
}
}

View File

@@ -1,150 +0,0 @@
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Services;
namespace StellaOps.AirGap.Time.Tests;
/// <summary>
/// Tests for RoughtimeVerifier with real Ed25519 signature verification.
/// Per AIRGAP-TIME-57-001: Trusted time-anchor service.
/// </summary>
public class RoughtimeVerifierTests
{
private readonly RoughtimeVerifier _verifier = new();
[Fact]
public void Verify_ReturnsFailure_WhenTrustRootsEmpty()
{
var token = new byte[] { 0x01, 0x02, 0x03, 0x04 };
var result = _verifier.Verify(token, Array.Empty<TimeTrustRoot>(), out var anchor);
Assert.False(result.IsValid);
Assert.Equal("roughtime-trust-roots-required", result.Reason);
Assert.Equal(TimeAnchor.Unknown, anchor);
}
[Fact]
public void Verify_ReturnsFailure_WhenTokenEmpty()
{
var trust = new[] { new TimeTrustRoot("root1", new byte[32], "ed25519") };
var result = _verifier.Verify(ReadOnlySpan<byte>.Empty, trust, out var anchor);
Assert.False(result.IsValid);
Assert.Equal("roughtime-token-empty", result.Reason);
Assert.Equal(TimeAnchor.Unknown, anchor);
}
[Fact]
public void Verify_ReturnsFailure_WhenTokenTooShort()
{
var token = new byte[] { 0x01, 0x02, 0x03 };
var trust = new[] { new TimeTrustRoot("root1", new byte[32], "ed25519") };
var result = _verifier.Verify(token, trust, out var anchor);
Assert.False(result.IsValid);
Assert.Equal("roughtime-message-too-short", result.Reason);
}
[Fact]
public void Verify_ReturnsFailure_WhenInvalidTagCount()
{
// Create a minimal wire format with invalid tag count
var token = new byte[8];
// Set num_tags to 0 (invalid)
BitConverter.TryWriteBytes(token.AsSpan(0, 4), (uint)0);
var trust = new[] { new TimeTrustRoot("root1", new byte[32], "ed25519") };
var result = _verifier.Verify(token, trust, out var anchor);
Assert.False(result.IsValid);
Assert.Equal("roughtime-invalid-tag-count", result.Reason);
}
[Fact]
public void Verify_ReturnsFailure_WhenNonEd25519Algorithm()
{
// Create a minimal valid-looking wire format
var token = CreateMinimalRoughtimeToken();
var trust = new[] { new TimeTrustRoot("root1", new byte[32], "rsa") }; // Wrong algorithm
var result = _verifier.Verify(token, trust, out var anchor);
Assert.False(result.IsValid);
// Should fail either on parsing or signature verification
Assert.Contains("roughtime-", result.Reason);
}
[Fact]
public void Verify_ReturnsFailure_WhenKeyLengthWrong()
{
var token = CreateMinimalRoughtimeToken();
var trust = new[] { new TimeTrustRoot("root1", new byte[16], "ed25519") }; // Wrong key length
var result = _verifier.Verify(token, trust, out var anchor);
Assert.False(result.IsValid);
Assert.Contains("roughtime-", result.Reason);
}
[Fact]
public void Verify_ProducesTokenDigest()
{
var token = new byte[] { 0xAA, 0xBB, 0xCC, 0xDD };
var trust = new[] { new TimeTrustRoot("root1", new byte[32], "ed25519") };
var result = _verifier.Verify(token, trust, out _);
// Even on failure, we should get a deterministic result
Assert.False(result.IsValid);
}
/// <summary>
/// Creates a minimal Roughtime wire format token for testing parsing paths.
/// Note: This will fail signature verification but tests the parsing logic.
/// </summary>
private static byte[] CreateMinimalRoughtimeToken()
{
// Roughtime wire format:
// [num_tags:u32] [offsets:u32[n-1]] [tags:u32[n]] [values...]
// We'll create 2 tags: SIG and SREP
const uint TagSig = 0x00474953; // "SIG\0"
const uint TagSrep = 0x50455253; // "SREP"
var sigValue = new byte[64]; // Ed25519 signature
var srepValue = CreateMinimalSrep();
// Header: num_tags=2, offset[0]=64 (sig length), tags=[SIG, SREP]
var headerSize = 4 + 4 + 8; // num_tags + 1 offset + 2 tags = 16 bytes
var token = new byte[headerSize + sigValue.Length + srepValue.Length];
BitConverter.TryWriteBytes(token.AsSpan(0, 4), (uint)2); // num_tags = 2
BitConverter.TryWriteBytes(token.AsSpan(4, 4), (uint)64); // offset[0] = 64 (sig length)
BitConverter.TryWriteBytes(token.AsSpan(8, 4), TagSig);
BitConverter.TryWriteBytes(token.AsSpan(12, 4), TagSrep);
sigValue.CopyTo(token.AsSpan(16));
srepValue.CopyTo(token.AsSpan(16 + 64));
return token;
}
private static byte[] CreateMinimalSrep()
{
// SREP with MIDP tag containing 8-byte timestamp
const uint TagMidp = 0x5044494D; // "MIDP"
// Header: num_tags=1, tags=[MIDP]
var headerSize = 4 + 4; // num_tags + 1 tag = 8 bytes
var srepValue = new byte[headerSize + 8]; // + 8 bytes for MIDP value
BitConverter.TryWriteBytes(srepValue.AsSpan(0, 4), (uint)1); // num_tags = 1
BitConverter.TryWriteBytes(srepValue.AsSpan(4, 4), TagMidp);
// MIDP value: microseconds since Unix epoch (example: 2025-01-01 00:00:00 UTC)
BitConverter.TryWriteBytes(srepValue.AsSpan(8, 8), 1735689600000000L);
return srepValue;
}
}

View File

@@ -1,63 +0,0 @@
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Services;
using StellaOps.AirGap.Time.Stores;
namespace StellaOps.AirGap.Time.Tests;
public class SealedStartupValidatorTests
{
[Fact]
public async Task FailsWhenAnchorMissing()
{
var validator = Build(out var statusService);
var result = await validator.ValidateAsync("t1", StalenessBudget.Default, default);
Assert.False(result.IsValid);
Assert.Equal("time-anchor-missing", result.Reason);
}
[Fact]
public async Task FailsWhenBreach()
{
var validator = Build(out var statusService);
var anchor = new TimeAnchor(DateTimeOffset.UnixEpoch, "src", "fmt", "fp", "digest");
await statusService.SetAnchorAsync("t1", anchor, new StalenessBudget(10, 20));
var now = DateTimeOffset.UnixEpoch.AddSeconds(25);
var status = await statusService.GetStatusAsync("t1", now);
var result = status.Staleness.IsBreach;
Assert.True(result);
var validation = await validator.ValidateAsync("t1", new StalenessBudget(10, 20), default);
Assert.False(validation.IsValid);
Assert.Equal("time-anchor-stale", validation.Reason);
}
[Fact]
public async Task SucceedsWhenFresh()
{
var validator = Build(out var statusService);
var now = DateTimeOffset.UtcNow;
var anchor = new TimeAnchor(now, "src", "fmt", "fp", "digest");
await statusService.SetAnchorAsync("t1", anchor, new StalenessBudget(10, 20));
var validation = await validator.ValidateAsync("t1", new StalenessBudget(10, 20), default);
Assert.True(validation.IsValid);
}
[Fact]
public async Task FailsOnBudgetMismatch()
{
var validator = Build(out var statusService);
var anchor = new TimeAnchor(DateTimeOffset.UtcNow, "src", "fmt", "fp", "digest");
await statusService.SetAnchorAsync("t1", anchor, new StalenessBudget(10, 20));
var validation = await validator.ValidateAsync("t1", new StalenessBudget(5, 15), default);
Assert.False(validation.IsValid);
Assert.Equal("time-anchor-budget-mismatch", validation.Reason);
}
private static SealedStartupValidator Build(out TimeStatusService statusService)
{
var store = new InMemoryTimeAnchorStore();
statusService = new TimeStatusService(store, new StalenessCalculator(), new TimeTelemetry(), Microsoft.Extensions.Options.Options.Create(new AirGapOptions()));
return new SealedStartupValidator(statusService);
}
}

View File

@@ -1,43 +0,0 @@
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Services;
namespace StellaOps.AirGap.Time.Tests;
public class StalenessCalculatorTests
{
[Fact]
public void UnknownWhenNoAnchor()
{
var calc = new StalenessCalculator();
var result = calc.Evaluate(TimeAnchor.Unknown, StalenessBudget.Default, DateTimeOffset.UnixEpoch);
Assert.False(result.IsWarning);
Assert.False(result.IsBreach);
}
[Fact]
public void BreachWhenBeyondBudget()
{
var anchor = new TimeAnchor(DateTimeOffset.UnixEpoch, "source", "fmt", "fp", "digest");
var budget = new StalenessBudget(10, 20);
var calc = new StalenessCalculator();
var result = calc.Evaluate(anchor, budget, DateTimeOffset.UnixEpoch.AddSeconds(25));
Assert.True(result.IsBreach);
Assert.True(result.IsWarning);
Assert.Equal(25, result.AgeSeconds);
}
[Fact]
public void WarningWhenBetweenWarningAndBreach()
{
var anchor = new TimeAnchor(DateTimeOffset.UnixEpoch, "source", "fmt", "fp", "digest");
var budget = new StalenessBudget(10, 20);
var calc = new StalenessCalculator();
var result = calc.Evaluate(anchor, budget, DateTimeOffset.UnixEpoch.AddSeconds(15));
Assert.True(result.IsWarning);
Assert.False(result.IsBreach);
}
}

View File

@@ -1,16 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../../src/AirGap/StellaOps.AirGap.Time/StellaOps.AirGap.Time.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,61 +0,0 @@
using Microsoft.Extensions.Options;
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Parsing;
using StellaOps.AirGap.Time.Services;
namespace StellaOps.AirGap.Time.Tests;
public class TimeAnchorLoaderTests
{
[Fact]
public void RejectsInvalidHex()
{
var loader = Build();
var trust = new[] { new TimeTrustRoot("k1", new byte[32], "ed25519") };
var result = loader.TryLoadHex("not-hex", TimeTokenFormat.Roughtime, trust, out _);
Assert.False(result.IsValid);
Assert.Equal("token-hex-invalid", result.Reason);
}
[Fact]
public void LoadsHexToken()
{
var loader = Build();
var hex = "01020304";
var trust = new[] { new TimeTrustRoot("k1", new byte[32], "ed25519") };
var result = loader.TryLoadHex(hex, TimeTokenFormat.Roughtime, trust, out var anchor);
Assert.True(result.IsValid);
Assert.Equal("Roughtime", anchor.Format);
}
[Fact]
public void RejectsIncompatibleTrustRoots()
{
var loader = Build();
var hex = "010203";
var rsaKey = new byte[128];
var trust = new[] { new TimeTrustRoot("k1", rsaKey, "rsa") };
var result = loader.TryLoadHex(hex, TimeTokenFormat.Roughtime, trust, out _);
Assert.False(result.IsValid);
Assert.Equal("trust-roots-incompatible-format", result.Reason);
}
[Fact]
public void RejectsWhenTrustRootsMissing()
{
var loader = Build();
var result = loader.TryLoadHex("010203", TimeTokenFormat.Roughtime, Array.Empty<TimeTrustRoot>(), out _);
Assert.False(result.IsValid);
Assert.Equal("trust-roots-required", result.Reason);
}
private static TimeAnchorLoader Build()
{
var options = Options.Create(new AirGapOptions { AllowUntrustedAnchors = false });
return new TimeAnchorLoader(new TimeVerificationService(), new TimeTokenParser(), options);
}
}

View File

@@ -1,261 +0,0 @@
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Services;
using StellaOps.AirGap.Time.Stores;
namespace StellaOps.AirGap.Time.Tests;
/// <summary>
/// Tests for TimeAnchorPolicyService.
/// Per AIRGAP-TIME-57-001: Time-anchor policy enforcement.
/// </summary>
public class TimeAnchorPolicyServiceTests
{
private readonly TimeProvider _fixedTimeProvider;
private readonly InMemoryTimeAnchorStore _store;
private readonly StalenessCalculator _calculator;
private readonly TimeTelemetry _telemetry;
private readonly TimeStatusService _statusService;
private readonly AirGapOptions _airGapOptions;
public TimeAnchorPolicyServiceTests()
{
_fixedTimeProvider = new FakeTimeProvider(new DateTimeOffset(2025, 1, 15, 12, 0, 0, TimeSpan.Zero));
_store = new InMemoryTimeAnchorStore();
_calculator = new StalenessCalculator();
_telemetry = new TimeTelemetry();
_airGapOptions = new AirGapOptions
{
Staleness = new AirGapOptions.StalenessOptions { WarningSeconds = 3600, BreachSeconds = 7200 },
ContentBudgets = new Dictionary<string, AirGapOptions.StalenessOptions>()
};
_statusService = new TimeStatusService(_store, _calculator, _telemetry, Options.Create(_airGapOptions));
}
private TimeAnchorPolicyService CreateService(TimeAnchorPolicyOptions? options = null)
{
return new TimeAnchorPolicyService(
_statusService,
Options.Create(options ?? new TimeAnchorPolicyOptions()),
NullLogger<TimeAnchorPolicyService>.Instance,
_fixedTimeProvider);
}
[Fact]
public async Task ValidateTimeAnchorAsync_ReturnsFailure_WhenNoAnchor()
{
var service = CreateService();
var result = await service.ValidateTimeAnchorAsync("tenant-1");
Assert.False(result.Allowed);
Assert.Equal(TimeAnchorPolicyErrorCodes.AnchorMissing, result.ErrorCode);
Assert.NotNull(result.Remediation);
}
[Fact]
public async Task ValidateTimeAnchorAsync_ReturnsSuccess_WhenAnchorValid()
{
var service = CreateService();
var anchor = new TimeAnchor(
_fixedTimeProvider.GetUtcNow().AddMinutes(-30),
"test-source",
"Roughtime",
"fingerprint",
"digest123");
var budget = new StalenessBudget(3600, 7200);
await _store.SetAsync("tenant-1", anchor, budget, CancellationToken.None);
var result = await service.ValidateTimeAnchorAsync("tenant-1");
Assert.True(result.Allowed);
Assert.Null(result.ErrorCode);
Assert.NotNull(result.Staleness);
Assert.False(result.Staleness.IsBreach);
}
[Fact]
public async Task ValidateTimeAnchorAsync_ReturnsWarning_WhenAnchorStale()
{
var service = CreateService();
var anchor = new TimeAnchor(
_fixedTimeProvider.GetUtcNow().AddSeconds(-5000), // Past warning threshold
"test-source",
"Roughtime",
"fingerprint",
"digest123");
var budget = new StalenessBudget(3600, 7200);
await _store.SetAsync("tenant-1", anchor, budget, CancellationToken.None);
var result = await service.ValidateTimeAnchorAsync("tenant-1");
Assert.True(result.Allowed); // Allowed but with warning
Assert.NotNull(result.Staleness);
Assert.True(result.Staleness.IsWarning);
Assert.Contains("warning", result.Reason, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task ValidateTimeAnchorAsync_ReturnsFailure_WhenAnchorBreached()
{
var service = CreateService();
var anchor = new TimeAnchor(
_fixedTimeProvider.GetUtcNow().AddSeconds(-8000), // Past breach threshold
"test-source",
"Roughtime",
"fingerprint",
"digest123");
var budget = new StalenessBudget(3600, 7200);
await _store.SetAsync("tenant-1", anchor, budget, CancellationToken.None);
var result = await service.ValidateTimeAnchorAsync("tenant-1");
Assert.False(result.Allowed);
Assert.Equal(TimeAnchorPolicyErrorCodes.AnchorBreached, result.ErrorCode);
Assert.NotNull(result.Staleness);
Assert.True(result.Staleness.IsBreach);
}
[Fact]
public async Task EnforceBundleImportPolicyAsync_AllowsImport_WhenAnchorValid()
{
var service = CreateService();
var anchor = new TimeAnchor(
_fixedTimeProvider.GetUtcNow().AddMinutes(-30),
"test-source",
"Roughtime",
"fingerprint",
"digest123");
var budget = new StalenessBudget(3600, 7200);
await _store.SetAsync("tenant-1", anchor, budget, CancellationToken.None);
var result = await service.EnforceBundleImportPolicyAsync(
"tenant-1",
"bundle-123",
_fixedTimeProvider.GetUtcNow().AddMinutes(-15));
Assert.True(result.Allowed);
}
[Fact]
public async Task EnforceBundleImportPolicyAsync_BlocksImport_WhenDriftExceeded()
{
var options = new TimeAnchorPolicyOptions { MaxDriftSeconds = 3600 }; // 1 hour max
var service = CreateService(options);
var anchor = new TimeAnchor(
_fixedTimeProvider.GetUtcNow().AddMinutes(-30),
"test-source",
"Roughtime",
"fingerprint",
"digest123");
var budget = new StalenessBudget(86400, 172800); // Large budget
await _store.SetAsync("tenant-1", anchor, budget, CancellationToken.None);
var bundleTimestamp = _fixedTimeProvider.GetUtcNow().AddDays(-2); // 2 days ago
var result = await service.EnforceBundleImportPolicyAsync(
"tenant-1",
"bundle-123",
bundleTimestamp);
Assert.False(result.Allowed);
Assert.Equal(TimeAnchorPolicyErrorCodes.DriftExceeded, result.ErrorCode);
}
[Fact]
public async Task EnforceOperationPolicyAsync_BlocksStrictOperations_WhenNoAnchor()
{
var options = new TimeAnchorPolicyOptions
{
StrictOperations = new[] { "attestation.sign" }
};
var service = CreateService(options);
var result = await service.EnforceOperationPolicyAsync("tenant-1", "attestation.sign");
Assert.False(result.Allowed);
Assert.Equal(TimeAnchorPolicyErrorCodes.AnchorMissing, result.ErrorCode);
}
[Fact]
public async Task EnforceOperationPolicyAsync_AllowsNonStrictOperations_InNonStrictMode()
{
var options = new TimeAnchorPolicyOptions
{
StrictEnforcement = false,
StrictOperations = new[] { "attestation.sign" }
};
var service = CreateService(options);
var result = await service.EnforceOperationPolicyAsync("tenant-1", "some.other.operation");
Assert.True(result.Allowed);
}
[Fact]
public async Task CalculateDriftAsync_ReturnsNoDrift_WhenNoAnchor()
{
var service = CreateService();
var result = await service.CalculateDriftAsync("tenant-1", _fixedTimeProvider.GetUtcNow());
Assert.False(result.HasAnchor);
Assert.Equal(TimeSpan.Zero, result.Drift);
Assert.Null(result.AnchorTime);
}
[Fact]
public async Task CalculateDriftAsync_ReturnsDrift_WhenAnchorExists()
{
var service = CreateService(new TimeAnchorPolicyOptions { MaxDriftSeconds = 3600 });
var anchorTime = _fixedTimeProvider.GetUtcNow().AddMinutes(-30);
var anchor = new TimeAnchor(anchorTime, "test", "Roughtime", "fp", "digest");
var budget = new StalenessBudget(3600, 7200);
await _store.SetAsync("tenant-1", anchor, budget, CancellationToken.None);
var targetTime = _fixedTimeProvider.GetUtcNow().AddMinutes(15);
var result = await service.CalculateDriftAsync("tenant-1", targetTime);
Assert.True(result.HasAnchor);
Assert.Equal(anchorTime, result.AnchorTime);
Assert.Equal(45, (int)result.Drift.TotalMinutes); // 30 min + 15 min
Assert.False(result.DriftExceedsThreshold);
}
[Fact]
public async Task CalculateDriftAsync_DetectsExcessiveDrift()
{
var service = CreateService(new TimeAnchorPolicyOptions { MaxDriftSeconds = 60 }); // 1 minute max
var anchor = new TimeAnchor(
_fixedTimeProvider.GetUtcNow(),
"test",
"Roughtime",
"fp",
"digest");
var budget = new StalenessBudget(3600, 7200);
await _store.SetAsync("tenant-1", anchor, budget, CancellationToken.None);
var targetTime = _fixedTimeProvider.GetUtcNow().AddMinutes(5); // 5 minutes drift
var result = await service.CalculateDriftAsync("tenant-1", targetTime);
Assert.True(result.HasAnchor);
Assert.True(result.DriftExceedsThreshold);
}
private sealed class FakeTimeProvider : TimeProvider
{
private readonly DateTimeOffset _now;
public FakeTimeProvider(DateTimeOffset now) => _now = now;
public override DateTimeOffset GetUtcNow() => _now;
}
}

View File

@@ -1,24 +0,0 @@
using StellaOps.AirGap.Time.Models;
namespace StellaOps.AirGap.Time.Tests;
public class TimeStatusDtoTests
{
[Fact]
public void SerializesDeterministically()
{
var status = new TimeStatus(
new TimeAnchor(DateTimeOffset.Parse("2025-01-01T00:00:00Z"), "source", "fmt", "fp", "digest"),
new StalenessEvaluation(42, 10, 20, true, false),
new StalenessBudget(10, 20),
new Dictionary<string, StalenessEvaluation>
{
{ "advisories", new StalenessEvaluation(42, 10, 20, true, false) }
},
DateTimeOffset.Parse("2025-01-02T00:00:00Z"));
var json = TimeStatusDto.FromStatus(status).ToJson();
Assert.Contains("\"contentStaleness\":{\"advisories\":{", json);
Assert.Contains("\"ageSeconds\":42", json);
}
}

View File

@@ -1,45 +0,0 @@
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Services;
using StellaOps.AirGap.Time.Stores;
namespace StellaOps.AirGap.Time.Tests;
public class TimeStatusServiceTests
{
[Fact]
public async Task ReturnsUnknownWhenNoAnchor()
{
var svc = Build(out var telemetry);
var status = await svc.GetStatusAsync("t1", DateTimeOffset.UnixEpoch);
Assert.Equal(TimeAnchor.Unknown, status.Anchor);
Assert.False(status.Staleness.IsWarning);
Assert.Equal(0, telemetry.GetLatest("t1")?.AgeSeconds ?? 0);
}
[Fact]
public async Task PersistsAnchorAndBudget()
{
var svc = Build(out var telemetry);
var anchor = new TimeAnchor(DateTimeOffset.UnixEpoch, "source", "fmt", "fp", "digest");
var budget = new StalenessBudget(10, 20);
await svc.SetAnchorAsync("t1", anchor, budget);
var status = await svc.GetStatusAsync("t1", DateTimeOffset.UnixEpoch.AddSeconds(15));
Assert.Equal(anchor, status.Anchor);
Assert.True(status.Staleness.IsWarning);
Assert.False(status.Staleness.IsBreach);
Assert.Equal(15, status.Staleness.AgeSeconds);
var snap = telemetry.GetLatest("t1");
Assert.NotNull(snap);
Assert.Equal(status.Staleness.AgeSeconds, snap!.AgeSeconds);
Assert.True(snap.IsWarning);
}
private static TimeStatusService Build(out TimeTelemetry telemetry)
{
telemetry = new TimeTelemetry();
var options = Microsoft.Extensions.Options.Options.Create(new AirGapOptions());
return new TimeStatusService(new InMemoryTimeAnchorStore(), new StalenessCalculator(), telemetry, options);
}
}

View File

@@ -1,27 +0,0 @@
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Services;
namespace StellaOps.AirGap.Time.Tests;
public class TimeTelemetryTests
{
[Fact]
public void Records_latest_snapshot_per_tenant()
{
var telemetry = new TimeTelemetry();
var status = new TimeStatus(
new TimeAnchor(DateTimeOffset.UnixEpoch, "src", "fmt", "fp", "digest"),
new StalenessEvaluation(90, 60, 120, true, false),
StalenessBudget.Default,
new Dictionary<string, StalenessEvaluation>{{"advisories", new StalenessEvaluation(90,60,120,true,false)}},
DateTimeOffset.UtcNow);
telemetry.Record("t1", status);
var snap = telemetry.GetLatest("t1");
Assert.NotNull(snap);
Assert.Equal(90, snap!.AgeSeconds);
Assert.True(snap.IsWarning);
Assert.False(snap.IsBreach);
}
}

View File

@@ -1,34 +0,0 @@
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Parsing;
namespace StellaOps.AirGap.Time.Tests;
public class TimeTokenParserTests
{
[Fact]
public void EmptyTokenFails()
{
var parser = new TimeTokenParser();
var result = parser.TryParse(Array.Empty<byte>(), TimeTokenFormat.Roughtime, out var anchor);
Assert.False(result.IsValid);
Assert.Equal("token-empty", result.Reason);
Assert.Equal(TimeAnchor.Unknown, anchor);
}
[Fact]
public void RoughtimeTokenProducesDigest()
{
var parser = new TimeTokenParser();
var token = new byte[] { 0x01, 0x02, 0x03 };
var result = parser.TryParse(token, TimeTokenFormat.Roughtime, out var anchor);
Assert.True(result.IsValid);
Assert.Equal("Roughtime", anchor.Format);
Assert.Equal("roughtime-token", anchor.Source);
Assert.Equal("structure-stubbed", result.Reason);
Assert.Matches("^[0-9a-f]{64}$", anchor.TokenDigest);
Assert.NotEqual(DateTimeOffset.UnixEpoch, anchor.AnchorTime); // deterministic derivation
}
}

View File

@@ -1,28 +0,0 @@
using StellaOps.AirGap.Time.Models;
using StellaOps.AirGap.Time.Parsing;
using StellaOps.AirGap.Time.Services;
namespace StellaOps.AirGap.Time.Tests;
public class TimeVerificationServiceTests
{
[Fact]
public void FailsWithoutTrustRoots()
{
var svc = new TimeVerificationService();
var result = svc.Verify(new byte[] { 0x01 }, TimeTokenFormat.Roughtime, Array.Empty<TimeTrustRoot>(), out _);
Assert.False(result.IsValid);
Assert.Equal("trust-roots-required", result.Reason);
}
[Fact]
public void SucceedsForRoughtimeWithTrustRoot()
{
var svc = new TimeVerificationService();
var trust = new[] { new TimeTrustRoot("k1", new byte[] { 0x01 }, "rsassa-pss-sha256") };
var result = svc.Verify(new byte[] { 0x01, 0x02 }, TimeTokenFormat.Roughtime, trust, out var anchor);
Assert.True(result.IsValid);
Assert.Equal("Roughtime", anchor.Format);
Assert.Equal("k1", anchor.SignatureFingerprint);
}
}

View File

@@ -1,20 +0,0 @@
# Evidence Locker Golden Fixtures (EB10)
Purpose: reference bundles and replay records used by CI to prove deterministic packaging, DSSE subject stability, and portable redaction behaviour.
## Layout
- `sealed/` sealed bundle ingredients (`manifest.json`, `checksums.txt`, DSSE `signature.json`, `bundle.json`, evidence ndjson) plus `expected.json`.
- `portable/` redacted bundle ingredients and `expected.json` noting masked fields and tenant token.
- `replay/` `replay.ndjson` with `expected.json` (recordDigest, sequence, ledger URI); ordering is canonical (recordedAtUtc, scanId).
## Expectations
- Gzip timestamp pinned to `2025-01-01T00:00:00Z`; tar entries use `0644` perms and fixed mtime.
- `checksums.txt` sorted lexicographically by `canonicalPath`; Merkle root equals `sha256sum checksums.txt`.
- DSSE subject ties to the Merkle root; manifest validates against `schemas/bundle.manifest.schema.json`.
- Portable bundles must exclude tenant identifiers and include redaction metadata in the manifest.
## How to (re)generate
1. Set `TZ=UTC` and ensure deterministic tool versions.
2. Run EvidenceLocker pipeline to produce sealed bundle; copy outputs here with expected hash values.
3. Produce portable bundle and replay records using the same input set; write `expected.json` capturing root hashes and replay digests.
4. Update xUnit tests in `StellaOps.EvidenceLocker.Tests` to consume these fixtures without network calls.

View File

@@ -1,7 +0,0 @@
{
"bundleId": "11111111111111111111111111111111",
"tenant": "redacted",
"kind": "evaluation",
"createdAt": "2025-12-04T00:00:00Z",
"portable": true
}

View File

@@ -1,14 +0,0 @@
{
"algorithm": "sha256",
"root": "72c82a7a3d114164d491e2ecd7098bc015b115ee1ec7c42d648f0348e573cfcf",
"generatedAt": "2025-12-04T00:00:00Z",
"bundleId": "11111111111111111111111111111111",
"tenantId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"entries": [
{ "canonicalPath": "bundle.json", "sha256": "10695174db1b549d77be583e529a249713e9bd23e46cc5e73250db5dfc92c4a9", "sizeBytes": 160 },
{ "canonicalPath": "instructions-portable.txt", "sha256": "dd2a3b62857cf331b423e7dc3b869ad2dc9bfa852109a20bcbecc7bcef9bdcb7", "sizeBytes": 180 },
{ "canonicalPath": "linksets.ndjson", "sha256": "a4d84bbc3262190fd3e1f5dbc15915c97e464326a56534483ce810c905288b9d", "sizeBytes": 151 },
{ "canonicalPath": "observations.ndjson", "sha256": "c523f82e71c8a1bd9be0650883faf00ec39a792023066105d7cda544ad6ef5fd", "sizeBytes": 149 }
],
"chunking": { "strategy": "none" }
}

View File

@@ -1,18 +0,0 @@
{
"bundleId": "11111111111111111111111111111111",
"tenantRedacted": true,
"merkleRoot": "72c82a7a3d114164d491e2ecd7098bc015b115ee1ec7c42d648f0348e573cfcf",
"subject": "sha256:72c82a7a3d114164d491e2ecd7098bc015b115ee1ec7c42d648f0348e573cfcf",
"entries": [
"bundle.json",
"instructions-portable.txt",
"linksets.ndjson",
"observations.ndjson"
],
"dsseKeyId": "demo-ed25519",
"logPolicy": "skip-offline",
"redaction": {
"maskedFields": ["tenantId"],
"tenantToken": "portable-tenant-01"
}
}

View File

@@ -1,4 +0,0 @@
Portable bundle verification:
1) sha256sum -c checksums.txt
2) expect no tenant identifiers in manifest or bundle.json
3) merkle_root=$(sha256sum checksums.txt | awk '{print $1}')

View File

@@ -1 +0,0 @@
{"linksetId":"lnk-demo-001","advisoryId":"CVE-2025-0001","components":["pkg:deb/openssl@1.1.1w"],"normalized":true,"createdAt":"2025-11-30T00:05:00Z"}

View File

@@ -1,58 +0,0 @@
{
"bundleId": "11111111111111111111111111111111",
"tenantId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"kind": "evaluation",
"createdAt": "2025-12-04T00:00:00Z",
"metadata": {
"scope": "demo",
"portable": "true"
},
"redaction": {
"portable": true,
"maskedFields": ["tenantId"],
"tenantToken": "portable-tenant-01"
},
"entries": [
{
"section": "manifest",
"canonicalPath": "bundle.json",
"sha256": "10695174db1b549d77be583e529a249713e9bd23e46cc5e73250db5dfc92c4a9",
"sizeBytes": 160,
"mediaType": "application/json",
"attributes": {
"role": "bundle",
"portable": "true"
}
},
{
"section": "evidence",
"canonicalPath": "observations.ndjson",
"sha256": "c523f82e71c8a1bd9be0650883faf00ec39a792023066105d7cda544ad6ef5fd",
"sizeBytes": 149,
"mediaType": "application/x-ndjson",
"attributes": {
"dataset": "observations"
}
},
{
"section": "evidence",
"canonicalPath": "linksets.ndjson",
"sha256": "a4d84bbc3262190fd3e1f5dbc15915c97e464326a56534483ce810c905288b9d",
"sizeBytes": 151,
"mediaType": "application/x-ndjson",
"attributes": {
"dataset": "linksets"
}
},
{
"section": "docs",
"canonicalPath": "instructions-portable.txt",
"sha256": "dd2a3b62857cf331b423e7dc3b869ad2dc9bfa852109a20bcbecc7bcef9bdcb7",
"sizeBytes": 180,
"mediaType": "text/plain",
"attributes": {
"purpose": "verification"
}
}
]
}

View File

@@ -1 +0,0 @@
{"observationId":"obs-demo-001","advisoryId":"CVE-2025-0001","component":"pkg:deb/openssl@1.1.1w","source":"nvd","fetchedAt":"2025-11-30T00:00:00Z"}

View File

@@ -1,15 +0,0 @@
{
"payloadType": "application/vnd.stellaops.evidence+json",
"payload": "ewogICJidW5kbGVJZCI6ICIxMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMSIsCiAgInRlbmFudElkIjogImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwKICAia2luZCI6ICJldmFsdWF0aW9uIiwKICAiY3JlYXRlZEF0IjogIjIwMjUtMTItMDRUMDA6MDA6MDBaIiwKICAibWV0YWRhdGEiOiB7CiAgICAic2NvcGUiOiAiZGVtbyIsCiAgICAicG9ydGFibGUiOiAidHJ1ZSIKICB9LAogICJyZWRhY3Rpb24iOiB7CiAgICAicG9ydGFibGUiOiB0cnVlLAogICAgIm1hc2tlZEZpZWxkcyI6IFsidGVuYW50SWQiXSwKICAgICJ0ZW5hbnRUb2tlbiI6ICJwb3J0YWJsZS10ZW5hbnQtMDEiCiAgfSwKICAiZW50cmllcyI6IFsKICAgIHsKICAgICAgInNlY3Rpb24iOiAibWFuaWZlc3QiLAogICAgICAiY2Fub25pY2FsUGF0aCI6ICJidW5kbGUuanNvbiIsCiAgICAgICJzaGEyNTYiOiAiMTA2OTUxNzRkYjFiNTQ5ZDc3YmU1ODNlNTI5YTI0OTcxM2U5YmQyM2U0NmNjNWU3MzI1MGRiNWRmYzkyYzRhOSIsCiAgICAgICJzaXplQnl0ZXMiOiAxNjAsCiAgICAgICJtZWRpYVR5cGUiOiAiYXBwbGljYXRpb24vanNvbiIsCiAgICAgICJhdHRyaWJ1dGVzIjogewogICAgICAgICJyb2xlIjogImJ1bmRsZSIsCiAgICAgICAgInBvcnRhYmxlIjogInRydWUiCiAgICAgIH0KICAgIH0sCiAgICB7CiAgICAgICJzZWN0aW9uIjogImV2aWRlbmNlIiwKICAgICAgImNhbm9uaWNhbFBhdGgiOiAib2JzZXJ2YXRpb25zLm5kanNvbiIsCiAgICAgICJzaGEyNTYiOiAiYzUyM2Y4MmU3MWM4YTFiZDliZTA2NTA4ODNmYWYwMGVjMzlhNzkyMDIzMDY2MTA1ZDdjZGE1NDRhZDZlZjVmZCIsCiAgICAgICJzaXplQnl0ZXMiOiAxNDksCiAgICAgICJtZWRpYVR5cGUiOiAiYXBwbGljYXRpb24veC1uZGpzb24iLAogICAgICAiYXR0cmlidXRlcyI6IHsKICAgICAgICAiZGF0YXNldCI6ICJvYnNlcnZhdGlvbnMiCiAgICAgIH0KICAgIH0sCiAgICB7CiAgICAgICJzZWN0aW9uIjogImV2aWRlbmNlIiwKICAgICAgImNhbm9uaWNhbFBhdGgiOiAibGlua3NldHMubmRqc29uIiwKICAgICAgInNoYTI1NiI6ICJhNGQ4NGJiYzMyNjIxOTBmZDNlMWY1ZGJjMTU5MTVjOTdlNDY0MzI2YTU2NTM0NDgzY2U4MTBjOTA1Mjg4YjlkIiwKICAgICAgInNpemVCeXRlcyI6IDE1MSwKICAgICAgIm1lZGlhVHlwZSI6ICJhcHBsaWNhdGlvbi94LW5kanNvbiIsCiAgICAgICJhdHRyaWJ1dGVzIjogewogICAgICAgICJkYXRhc2V0IjogImxpbmtzZXRzIgogICAgICB9CiAgICB9LAogICAgewogICAgICAic2VjdGlvbiI6ICJkb2NzIiwKICAgICAgImNhbm9uaWNhbFBhdGgiOiAiaW5zdHJ1Y3Rpb25zLXBvcnRhYmxlLnR4dCIsCiAgICAgICJzaGEyNTYiOiAiZGQyYTNiNjI4NTdjZjMzMWI0MjNlN2RjM2I4NjlhZDJkYzliZmE4NTIxMDlhMjBiY2JlY2M3YmNlZjliZGNiNyIsCiAgICAgICJzaXplQnl0ZXMiOiAxODAsCiAgICAgICJtZWRpYVR5cGUiOiAidGV4dC9wbGFpbiIsCiAgICAgICJhdHRyaWJ1dGVzIjogewogICAgICAgICJwdXJwb3NlIjogInZlcmlmaWNhdGlvbiIKICAgICAgfQogICAgfQogIF0KfQo=",
"signatures": [
{
"keyid": "demo-ed25519",
"sig": "MEQCIGZkZGVtb3NpZw==",
"algorithm": "ed25519",
"provider": "sovereign-default",
"subjectMerkleRoot": "72c82a7a3d114164d491e2ecd7098bc015b115ee1ec7c42d648f0348e573cfcf",
"transparency": null,
"log_policy": "skip-offline"
}
]
}

View File

@@ -1,7 +0,0 @@
{
"recordDigest": "sha256:8765b4a8411e76b36a2d2d43eba4c2197b4dcf0c5c0a11685ce46780a7c54222",
"sequence": 0,
"ledgerUri": "offline://demo-ledger",
"dsseEnvelope": "ZHNzZV9lbmNfZGVtbyIs",
"ordering": "recordedAtUtc, scanId"
}

View File

@@ -1 +0,0 @@
{"scanId":"22222222-2222-4222-8222-222222222222","tenantId":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","subjectDigest":"sha256:c15ab4d1348da9e5000a5d3da50790ea120d865cafb0961845ed6f1e96927596","scanKind":"sbom","startedAtUtc":"2025-12-03T00:00:00Z","completedAtUtc":"2025-12-03T00:10:00Z","recordedAtUtc":"2025-12-03T00:10:01Z","artifacts":[{"type":"sbom","digest":"sha256:aaaa","uri":"s3://demo/sbom"}],"provenance":{"dsseEnvelope":"ZHNzZV9lbmNfZGVtbyIs"},"summary":{"findings":1,"advisories":1,"policies":0}}

View File

@@ -1 +0,0 @@
8765b4a8411e76b36a2d2d43eba4c2197b4dcf0c5c0a11685ce46780a7c54222 replay.ndjson

View File

@@ -1,7 +0,0 @@
{
"bundleId": "11111111111111111111111111111111",
"tenantId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"kind": "evaluation",
"createdAt": "2025-12-04T00:00:00Z",
"portable": false
}

View File

@@ -1,14 +0,0 @@
{
"algorithm": "sha256",
"root": "c15ab4d1348da9e5000a5d3da50790ea120d865cafb0961845ed6f1e96927596",
"generatedAt": "2025-12-04T00:00:00Z",
"bundleId": "11111111111111111111111111111111",
"tenantId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"entries": [
{ "canonicalPath": "bundle.json", "sha256": "86872809b585f9b43f53b12a8fb27dbb0a3b9c4f74e41c38118877ebcff1c273", "sizeBytes": 187 },
{ "canonicalPath": "instructions.txt", "sha256": "39a5880af850121919a540dd4528e49a3b5687cb922195b07db2c56f9e90dd1b", "sizeBytes": 160 },
{ "canonicalPath": "linksets.ndjson", "sha256": "a4d84bbc3262190fd3e1f5dbc15915c97e464326a56534483ce810c905288b9d", "sizeBytes": 151 },
{ "canonicalPath": "observations.ndjson", "sha256": "c523f82e71c8a1bd9be0650883faf00ec39a792023066105d7cda544ad6ef5fd", "sizeBytes": 149 }
],
"chunking": { "strategy": "none" }
}

View File

@@ -1,14 +0,0 @@
{
"bundleId": "11111111111111111111111111111111",
"tenantId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"merkleRoot": "c15ab4d1348da9e5000a5d3da50790ea120d865cafb0961845ed6f1e96927596",
"subject": "sha256:c15ab4d1348da9e5000a5d3da50790ea120d865cafb0961845ed6f1e96927596",
"entries": [
"bundle.json",
"instructions.txt",
"linksets.ndjson",
"observations.ndjson"
],
"dsseKeyId": "demo-ed25519",
"logPolicy": "skip-offline"
}

View File

@@ -1,4 +0,0 @@
Offline verification steps:
1) sha256sum -c checksums.txt
2) merkle_root=$(sha256sum checksums.txt | awk '{print $1}')
3) compare merkle_root with DSSE subject

View File

@@ -1 +0,0 @@
{"linksetId":"lnk-demo-001","advisoryId":"CVE-2025-0001","components":["pkg:deb/openssl@1.1.1w"],"normalized":true,"createdAt":"2025-11-30T00:05:00Z"}

View File

@@ -1,52 +0,0 @@
{
"bundleId": "11111111111111111111111111111111",
"tenantId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"kind": "evaluation",
"createdAt": "2025-12-04T00:00:00Z",
"metadata": {
"scope": "demo",
"advisory": "CVE-2025-0001"
},
"entries": [
{
"section": "manifest",
"canonicalPath": "bundle.json",
"sha256": "86872809b585f9b43f53b12a8fb27dbb0a3b9c4f74e41c38118877ebcff1c273",
"sizeBytes": 187,
"mediaType": "application/json",
"attributes": {
"role": "bundle"
}
},
{
"section": "evidence",
"canonicalPath": "observations.ndjson",
"sha256": "c523f82e71c8a1bd9be0650883faf00ec39a792023066105d7cda544ad6ef5fd",
"sizeBytes": 149,
"mediaType": "application/x-ndjson",
"attributes": {
"dataset": "observations"
}
},
{
"section": "evidence",
"canonicalPath": "linksets.ndjson",
"sha256": "a4d84bbc3262190fd3e1f5dbc15915c97e464326a56534483ce810c905288b9d",
"sizeBytes": 151,
"mediaType": "application/x-ndjson",
"attributes": {
"dataset": "linksets"
}
},
{
"section": "docs",
"canonicalPath": "instructions.txt",
"sha256": "39a5880af850121919a540dd4528e49a3b5687cb922195b07db2c56f9e90dd1b",
"sizeBytes": 160,
"mediaType": "text/plain",
"attributes": {
"purpose": "verification"
}
}
]
}

View File

@@ -1 +0,0 @@
{"observationId":"obs-demo-001","advisoryId":"CVE-2025-0001","component":"pkg:deb/openssl@1.1.1w","source":"nvd","fetchedAt":"2025-11-30T00:00:00Z"}

View File

@@ -1,15 +0,0 @@
{
"payloadType": "application/vnd.stellaops.evidence+json",
"payload": "ewogICJidW5kbGVJZCI6ICIxMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMSIsCiAgInRlbmFudElkIjogImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwKICAia2luZCI6ICJldmFsdWF0aW9uIiwKICAiY3JlYXRlZEF0IjogIjIwMjUtMTItMDRUMDA6MDA6MDBaIiwKICAibWV0YWRhdGEiOiB7CiAgICAic2NvcGUiOiAiZGVtbyIsCiAgICAiYWR2aXNvcnkiOiAiQ1ZFLTIwMjUtMDAwMSIKICB9LAogICJlbnRyaWVzIjogWwogICAgewogICAgICAic2VjdGlvbiI6ICJtYW5pZmVzdCIsCiAgICAgICJjYW5vbmljYWxQYXRoIjogImJ1bmRsZS5qc29uIiwKICAgICAgInNoYTI1NiI6ICI4Njg3MjgwOWI1ODVmOWI0M2Y1M2IxMmE4ZmIyN2RiYjBhM2I5YzRmNzRlNDFjMzgxMTg4NzdlYmNmZjFjMjczIiwKICAgICAgInNpemVCeXRlcyI6IDE4NywKICAgICAgIm1lZGlhVHlwZSI6ICJhcHBsaWNhdGlvbi9qc29uIiwKICAgICAgImF0dHJpYnV0ZXMiOiB7CiAgICAgICAgInJvbGUiOiAiYnVuZGxlIgogICAgICB9CiAgICB9LAogICAgewogICAgICAic2VjdGlvbiI6ICJldmlkZW5jZSIsCiAgICAgICJjYW5vbmljYWxQYXRoIjogIm9ic2VydmF0aW9ucy5uZGpzb24iLAogICAgICAic2hhMjU2IjogImM1MjNmODJlNzFjOGExYmQ5YmUwNjUwODgzZmFmMDBlYzM5YTc5MjAyMzA2NjEwNWQ3Y2RhNTQ0YWQ2ZWY1ZmQiLAogICAgICAic2l6ZUJ5dGVzIjogMTQ5LAogICAgICAibWVkaWFUeXBlIjogImFwcGxpY2F0aW9uL3gtbmRqc29uIiwKICAgICAgImF0dHJpYnV0ZXMiOiB7CiAgICAgICAgImRhdGFzZXQiOiAib2JzZXJ2YXRpb25zIgogICAgICB9CiAgICB9LAogICAgewogICAgICAic2VjdGlvbiI6ICJldmlkZW5jZSIsCiAgICAgICJjYW5vbmljYWxQYXRoIjogImxpbmtzZXRzLm5kanNvbiIsCiAgICAgICJzaGEyNTYiOiAiYTRkODRiYmMzMjYyMTkwZmQzZTFmNWRiYzE1OTE1Yzk3ZTQ2NDMyNmE1NjUzNDQ4M2NlODEwYzkwNTI4OGI5ZCIsCiAgICAgICJzaXplQnl0ZXMiOiAxNTEsCiAgICAgICJtZWRpYVR5cGUiOiAiYXBwbGljYXRpb24veC1uZGpzb24iLAogICAgICAiYXR0cmlidXRlcyI6IHsKICAgICAgICAiZGF0YXNldCI6ICJsaW5rc2V0cyIKICAgICAgfQogICAgfSwKICAgIHsKICAgICAgInNlY3Rpb24iOiAiZG9jcyIsCiAgICAgICJjYW5vbmljYWxQYXRoIjogImluc3RydWN0aW9ucy50eHQiLAogICAgICAic2hhMjU2IjogIjM5YTU4ODBhZjg1MDEyMTkxOWE1NDBkZDQ1MjhlNDlhM2I1Njg3Y2I5MjIxOTViMDdkYjJjNTZmOWU5MGRkMWIiLAogICAgICAic2l6ZUJ5dGVzIjogMTYwLAogICAgICAibWVkaWFUeXBlIjogInRleHQvcGxhaW4iLAogICAgICAiYXR0cmlidXRlcyI6IHsKICAgICAgICAicHVycG9zZSI6ICJ2ZXJpZmljYXRpb24iCiAgICAgIH0KICAgIH0KICBdCn0K",
"signatures": [
{
"keyid": "demo-ed25519",
"sig": "MEQCIGZkZGVtb3NpZw==",
"algorithm": "ed25519",
"provider": "sovereign-default",
"subjectMerkleRoot": "c15ab4d1348da9e5000a5d3da50790ea120d865cafb0961845ed6f1e96927596",
"transparency": null,
"log_policy": "skip-offline"
}
]
}

View File

@@ -1,148 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using StellaOps.Graph.Indexer.Ingestion.Advisory;
using StellaOps.Graph.Indexer.Ingestion.Sbom;
using Xunit;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class AdvisoryLinksetProcessorTests
{
[Fact]
public async Task ProcessAsync_persists_batch_and_records_success()
{
var snapshot = CreateSnapshot();
var transformer = new AdvisoryLinksetTransformer();
var writer = new CaptureWriter();
var metrics = new CaptureMetrics();
var processor = new AdvisoryLinksetProcessor(
transformer,
writer,
metrics,
NullLogger<AdvisoryLinksetProcessor>.Instance);
await processor.ProcessAsync(snapshot, CancellationToken.None);
writer.LastBatch.Should().NotBeNull();
writer.LastBatch!.Edges.Length.Should().Be(1, "duplicate impacts should collapse into one edge");
metrics.LastRecord.Should().NotBeNull();
metrics.LastRecord!.Success.Should().BeTrue();
metrics.LastRecord.NodeCount.Should().Be(writer.LastBatch!.Nodes.Length);
metrics.LastRecord.EdgeCount.Should().Be(writer.LastBatch!.Edges.Length);
}
[Fact]
public async Task ProcessAsync_records_failure_when_writer_throws()
{
var snapshot = CreateSnapshot();
var transformer = new AdvisoryLinksetTransformer();
var writer = new CaptureWriter(shouldThrow: true);
var metrics = new CaptureMetrics();
var processor = new AdvisoryLinksetProcessor(
transformer,
writer,
metrics,
NullLogger<AdvisoryLinksetProcessor>.Instance);
var act = () => processor.ProcessAsync(snapshot, CancellationToken.None);
await act.Should().ThrowAsync<InvalidOperationException>();
metrics.LastRecord.Should().NotBeNull();
metrics.LastRecord!.Success.Should().BeFalse();
}
private static AdvisoryLinksetSnapshot CreateSnapshot()
{
return new AdvisoryLinksetSnapshot
{
Tenant = "tenant-alpha",
Source = "concelier.overlay.v1",
LinksetDigest = "sha256:linkset001",
CollectedAt = DateTimeOffset.Parse("2025-10-30T12:05:00Z"),
EventOffset = 2201,
Advisory = new AdvisoryDetails
{
Source = "concelier.linkset.v1",
AdvisorySource = "ghsa",
AdvisoryId = "GHSA-1234-5678-90AB",
Severity = "HIGH",
PublishedAt = DateTimeOffset.Parse("2025-10-25T09:00:00Z"),
ContentHash = "sha256:ddd444"
},
Components = new[]
{
new AdvisoryComponentImpact
{
ComponentPurl = "pkg:nuget/Newtonsoft.Json@13.0.3",
ComponentSourceType = "inventory",
EvidenceDigest = "sha256:evidence004",
MatchedVersions = new[] { "13.0.3" },
Cvss = 8.1,
Confidence = 0.9,
Source = "concelier.overlay.v1",
CollectedAt = DateTimeOffset.Parse("2025-10-30T12:05:10Z"),
EventOffset = 3100,
SbomDigest = "sha256:sbom111"
},
new AdvisoryComponentImpact
{
ComponentPurl = "pkg:nuget/Newtonsoft.Json@13.0.3",
ComponentSourceType = "inventory",
EvidenceDigest = "sha256:evidence004",
MatchedVersions = new[] { "13.0.3" },
Cvss = 8.1,
Confidence = 0.9,
Source = "concelier.overlay.v1",
CollectedAt = DateTimeOffset.Parse("2025-10-30T12:05:10Z"),
EventOffset = 3100,
SbomDigest = "sha256:sbom111"
}
}
};
}
private sealed class CaptureWriter : IGraphDocumentWriter
{
private readonly bool _shouldThrow;
public CaptureWriter(bool shouldThrow = false)
{
_shouldThrow = shouldThrow;
}
public GraphBuildBatch? LastBatch { get; private set; }
public Task WriteAsync(GraphBuildBatch batch, CancellationToken cancellationToken)
{
LastBatch = batch;
if (_shouldThrow)
{
throw new InvalidOperationException("Simulated write failure");
}
return Task.CompletedTask;
}
}
private sealed class CaptureMetrics : IAdvisoryLinksetMetrics
{
public BatchRecord? LastRecord { get; private set; }
public void RecordBatch(string source, string tenant, int nodeCount, int edgeCount, TimeSpan duration, bool success)
{
LastRecord = new BatchRecord(source, tenant, nodeCount, edgeCount, duration, success);
}
}
private sealed record BatchRecord(
string Source,
string Tenant,
int NodeCount,
int EdgeCount,
TimeSpan Duration,
bool Success);
}

View File

@@ -1,107 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using FluentAssertions;
using StellaOps.Graph.Indexer.Ingestion.Advisory;
using Xunit;
using Xunit.Abstractions;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class AdvisoryLinksetTransformerTests
{
private readonly ITestOutputHelper _output;
public AdvisoryLinksetTransformerTests(ITestOutputHelper output)
{
_output = output;
}
private static readonly string FixturesRoot =
Path.Combine(AppContext.BaseDirectory, "Fixtures", "v1");
private static readonly HashSet<string> ExpectedNodeKinds = new(StringComparer.Ordinal)
{
"advisory"
};
private static readonly HashSet<string> ExpectedEdgeKinds = new(StringComparer.Ordinal)
{
"AFFECTED_BY"
};
[Fact]
public void Transform_projects_advisory_nodes_and_affected_by_edges()
{
var snapshot = LoadSnapshot("concelier-linkset.json");
var transformer = new AdvisoryLinksetTransformer();
var batch = transformer.Transform(snapshot);
var expectedNodes = LoadArray("nodes.json")
.Cast<JsonObject>()
.Where(node => ExpectedNodeKinds.Contains(node["kind"]!.GetValue<string>()))
.OrderBy(node => node["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var expectedEdges = LoadArray("edges.json")
.Cast<JsonObject>()
.Where(edge => ExpectedEdgeKinds.Contains(edge["kind"]!.GetValue<string>()))
.OrderBy(edge => edge["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var actualNodes = batch.Nodes
.Where(node => ExpectedNodeKinds.Contains(node["kind"]!.GetValue<string>()))
.OrderBy(node => node["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var actualEdges = batch.Edges
.Where(edge => ExpectedEdgeKinds.Contains(edge["kind"]!.GetValue<string>()))
.OrderBy(edge => edge["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
actualNodes.Length.Should().Be(expectedNodes.Length);
actualEdges.Length.Should().Be(expectedEdges.Length);
for (var i = 0; i < expectedNodes.Length; i++)
{
if (!JsonNode.DeepEquals(expectedNodes[i], actualNodes[i]))
{
_output.WriteLine($"Expected Node: {expectedNodes[i]}");
_output.WriteLine($"Actual Node: {actualNodes[i]}");
}
JsonNode.DeepEquals(expectedNodes[i], actualNodes[i]).Should().BeTrue();
}
for (var i = 0; i < expectedEdges.Length; i++)
{
if (!JsonNode.DeepEquals(expectedEdges[i], actualEdges[i]))
{
_output.WriteLine($"Expected Edge: {expectedEdges[i]}");
_output.WriteLine($"Actual Edge: {actualEdges[i]}");
}
JsonNode.DeepEquals(expectedEdges[i], actualEdges[i]).Should().BeTrue();
}
}
private static AdvisoryLinksetSnapshot LoadSnapshot(string fileName)
{
var path = Path.Combine(FixturesRoot, fileName);
var json = File.ReadAllText(path);
return JsonSerializer.Deserialize<AdvisoryLinksetSnapshot>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
})!;
}
private static JsonArray LoadArray(string fileName)
{
var path = Path.Combine(FixturesRoot, fileName);
return (JsonArray)JsonNode.Parse(File.ReadAllText(path))!;
}
}

View File

@@ -1,54 +0,0 @@
using System.IO;
using System.Text.Json.Nodes;
using FluentAssertions;
using StellaOps.Graph.Indexer.Ingestion.Sbom;
using Xunit;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class FileSystemSnapshotFileWriterTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), $"graph-snapshots-{Guid.NewGuid():N}");
[Fact]
public async Task WriteJsonAsync_writes_canonical_json()
{
var writer = new FileSystemSnapshotFileWriter(_root);
var json = new JsonObject
{
["b"] = "value2",
["a"] = "value1"
};
await writer.WriteJsonAsync("manifest.json", json, CancellationToken.None);
var content = await File.ReadAllTextAsync(Path.Combine(_root, "manifest.json"));
content.Should().Be("{\"a\":\"value1\",\"b\":\"value2\"}");
}
[Fact]
public async Task WriteJsonLinesAsync_writes_each_object_on_new_line()
{
var writer = new FileSystemSnapshotFileWriter(_root);
var items = new[]
{
new JsonObject { ["id"] = "1", ["kind"] = "component" },
new JsonObject { ["id"] = "2", ["kind"] = "artifact" }
};
await writer.WriteJsonLinesAsync("nodes.jsonl", items, CancellationToken.None);
var lines = await File.ReadAllLinesAsync(Path.Combine(_root, "nodes.jsonl"));
lines.Should().HaveCount(2);
lines[0].Should().Be("{\"id\":\"1\",\"kind\":\"component\"}");
lines[1].Should().Be("{\"id\":\"2\",\"kind\":\"artifact\"}");
}
public void Dispose()
{
if (Directory.Exists(_root))
{
Directory.Delete(_root, recursive: true);
}
}
}

View File

@@ -1,32 +0,0 @@
{
"tenant": "tenant-alpha",
"source": "concelier.overlay.v1",
"linksetDigest": "sha256:linkset001",
"collectedAt": "2025-10-30T12:05:10Z",
"eventOffset": 3100,
"advisory": {
"source": "concelier.linkset.v1",
"advisorySource": "ghsa",
"advisoryId": "GHSA-1234-5678-90AB",
"severity": "HIGH",
"publishedAt": "2025-10-25T09:00:00Z",
"contentHash": "sha256:ddd444",
"linksetDigest": "sha256:linkset001"
},
"components": [
{
"purl": "pkg:nuget/Newtonsoft.Json@13.0.3",
"sourceType": "inventory",
"sbomDigest": "sha256:sbom111",
"evidenceDigest": "sha256:evidence004",
"matchedVersions": [
"13.0.3"
],
"cvss": 8.1,
"confidence": 0.9,
"source": "concelier.overlay.v1",
"collectedAt": "2025-10-30T12:05:10Z",
"eventOffset": 3100
}
]
}

View File

@@ -1,209 +0,0 @@
[
{
"kind": "CONTAINS",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"artifact_node_id": "gn:tenant-alpha:artifact:RX033HH7S6JXMY66QM51S89SX76B3JXJHWHPXPPBJCD05BR3GVXG",
"component_node_id": "gn:tenant-alpha:component:BQSZFXSPNGS6M8XEQZ6XX3E7775XZQABM301GFPFXCQSQSA1WHZ0",
"sbom_digest": "sha256:sbom111"
},
"attributes": {
"detected_by": "sbom.analyzer.nuget",
"layer_digest": "sha256:layer123",
"scope": "runtime",
"evidence_digest": "sha256:evidence001"
},
"provenance": {
"source": "scanner.sbom.v1",
"collected_at": "2025-10-30T12:00:02Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 2100
},
"valid_from": "2025-10-30T12:00:02Z",
"valid_to": null,
"id": "ge:tenant-alpha:CONTAINS:EVA5N7P029VYV9W8Q7XJC0JFTEQYFSAQ6381SNVM3T1G5290XHTG",
"hash": "139e534be32f666cbd8e4fb0daee629b7b133ef8d10e98413ffc33fde59f7935"
},
{
"kind": "DEPENDS_ON",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"component_node_id": "gn:tenant-alpha:component:BQSZFXSPNGS6M8XEQZ6XX3E7775XZQABM301GFPFXCQSQSA1WHZ0",
"dependency_purl": "pkg:nuget/System.Text.Encoding.Extensions@4.7.0",
"sbom_digest": "sha256:sbom111"
},
"attributes": {
"dependency_purl": "pkg:nuget/System.Text.Encoding.Extensions@4.7.0",
"dependency_version": "4.7.0",
"relationship": "direct",
"evidence_digest": "sha256:evidence002"
},
"provenance": {
"source": "scanner.sbom.v1",
"collected_at": "2025-10-30T12:00:02Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 2101
},
"valid_from": "2025-10-30T12:00:02Z",
"valid_to": null,
"id": "ge:tenant-alpha:DEPENDS_ON:FJ7GZ9RHPKPR30XVKECD702QG20PGT3V75DY1GST8AAW9SR8TBB0",
"hash": "4caae0dff840dee840d413005f1b493936446322e8cfcecd393983184cc399c1"
},
{
"kind": "DECLARED_IN",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"component_node_id": "gn:tenant-alpha:component:BQSZFXSPNGS6M8XEQZ6XX3E7775XZQABM301GFPFXCQSQSA1WHZ0",
"file_node_id": "gn:tenant-alpha:file:M1MWHCXA66MQE8FZMPK3RNRMN7Z18H4VGWX6QTNNBKABFKRACKDG",
"sbom_digest": "sha256:sbom111"
},
"attributes": {
"detected_by": "sbom.analyzer.nuget",
"scope": "runtime",
"evidence_digest": "sha256:evidence003"
},
"provenance": {
"source": "scanner.layer.v1",
"collected_at": "2025-10-30T12:00:03Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 2102
},
"valid_from": "2025-10-30T12:00:03Z",
"valid_to": null,
"id": "ge:tenant-alpha:DECLARED_IN:T7E8NQEMKXPZ3T1SWT8HXKWAHJVS9QKD87XBKAQAAQ29CDHEA47G",
"hash": "2a2e7ba8785d75eb11feebc2df99a6a04d05ee609b36cbe0b15fa142e4c4f184"
},
{
"kind": "BUILT_FROM",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"parent_artifact_node_id": "gn:tenant-alpha:artifact:RX033HH7S6JXMY66QM51S89SX76B3JXJHWHPXPPBJCD05BR3GVXG",
"child_artifact_digest": "sha256:base000"
},
"attributes": {
"build_type": "https://slsa.dev/provenance/v1",
"builder_id": "builder://tekton/pipeline/default",
"attestation_digest": "sha256:attestation001"
},
"provenance": {
"source": "scanner.provenance.v1",
"collected_at": "2025-10-30T12:00:05Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 2103
},
"valid_from": "2025-10-30T12:00:05Z",
"valid_to": null,
"id": "ge:tenant-alpha:BUILT_FROM:HJNKVFSDSA44HRY0XAJ0GBEVPD2S82JFF58BZVRT9QF6HB2EGPJG",
"hash": "17bdb166f4ba05406ed17ec38d460fb83bd72cec60095f0966b1d79c2a55f1de"
},
{
"kind": "AFFECTED_BY",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"component_node_id": "gn:tenant-alpha:component:BQSZFXSPNGS6M8XEQZ6XX3E7775XZQABM301GFPFXCQSQSA1WHZ0",
"advisory_node_id": "gn:tenant-alpha:advisory:RFGYXZ2TG0BF117T3HCX3XYAZFXPD72991QD0JZWDVY7FXYY87R0",
"linkset_digest": "sha256:linkset001"
},
"attributes": {
"evidence_digest": "sha256:evidence004",
"matched_versions": [
"13.0.3"
],
"cvss": 8.1,
"confidence": 0.9
},
"provenance": {
"source": "concelier.overlay.v1",
"collected_at": "2025-10-30T12:05:10Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 3100
},
"valid_from": "2025-10-30T12:05:10Z",
"valid_to": null,
"id": "ge:tenant-alpha:AFFECTED_BY:1V3NRKAR6KMXAWZ89R69G8JAY3HV7DXNB16YY9X25X1TAFW9VGYG",
"hash": "45e845ee51dc2e8e8990707906bddcd3ecedf209de10b87ce8eed604dcc51ff5"
},
{
"kind": "VEX_EXEMPTS",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"component_node_id": "gn:tenant-alpha:component:BQSZFXSPNGS6M8XEQZ6XX3E7775XZQABM301GFPFXCQSQSA1WHZ0",
"vex_node_id": "gn:tenant-alpha:vex_statement:BVRF35CX6TZTHPD7YFHYTJJACPYJD86JP7C74SH07QT9JT82NDSG",
"statement_hash": "sha256:eee555"
},
"attributes": {
"status": "not_affected",
"justification": "component not present",
"impact_statement": "Library not loaded at runtime",
"evidence_digest": "sha256:evidence005"
},
"provenance": {
"source": "excititor.overlay.v1",
"collected_at": "2025-10-30T12:06:10Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 3200
},
"valid_from": "2025-10-30T12:06:10Z",
"valid_to": null,
"id": "ge:tenant-alpha:VEX_EXEMPTS:DT0BBCM9S0KJVF61KVR7D2W8DVFTKK03F3TFD4DR9DRS0T5CWZM0",
"hash": "0ae4085e510898e68ad5cb48b7385a1ae9af68fcfea9bd5c22c47d78bb1c2f2e"
},
{
"kind": "GOVERNS_WITH",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"policy_node_id": "gn:tenant-alpha:policy_version:YZSMWHHR6Y5XR1HFRBV3H5TR6GMZVN9BPDAAVQEACV7XRYP06390",
"component_node_id": "gn:tenant-alpha:component:BQSZFXSPNGS6M8XEQZ6XX3E7775XZQABM301GFPFXCQSQSA1WHZ0",
"finding_explain_hash": "sha256:explain001"
},
"attributes": {
"verdict": "fail",
"explain_hash": "sha256:explain001",
"policy_rule_id": "rule:runtime/critical-dependency",
"evaluation_timestamp": "2025-10-30T12:07:00Z"
},
"provenance": {
"source": "policy.engine.v1",
"collected_at": "2025-10-30T12:07:00Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 4200
},
"valid_from": "2025-10-30T12:07:00Z",
"valid_to": null,
"id": "ge:tenant-alpha:GOVERNS_WITH:XG3KQTYT8D4NY0BTFXWGBQY6TXR2MRYDWZBQT07T0200NQ72AFG0",
"hash": "38a05081a9b046bfd391505d47da6b7c6e3a74e114999b38a4e4e9341f2dc279"
},
{
"kind": "OBSERVED_RUNTIME",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"runtime_node_id": "gn:tenant-alpha:runtime_context:EFVARD7VM4710F8554Q3NGH0X8W7XRF3RDARE8YJWK1H3GABX8A0",
"component_node_id": "gn:tenant-alpha:component:BQSZFXSPNGS6M8XEQZ6XX3E7775XZQABM301GFPFXCQSQSA1WHZ0",
"runtime_fingerprint": "pod-abc123"
},
"attributes": {
"process_name": "dotnet",
"entrypoint_kind": "container",
"runtime_evidence_digest": "sha256:evidence006",
"confidence": 0.8
},
"provenance": {
"source": "signals.runtime.v1",
"collected_at": "2025-10-30T12:15:10Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 5200
},
"valid_from": "2025-10-30T12:15:10Z",
"valid_to": null,
"id": "ge:tenant-alpha:OBSERVED_RUNTIME:CVV4ACPPJVHWX2NRZATB8H045F71HXT59TQHEZE2QBAQGJDK1FY0",
"hash": "15d24ebdf126b6f8947d3041f8cbb291bb66e8f595737a7c7dd2683215568367"
}
]

View File

@@ -1,34 +0,0 @@
{
"tenant": "tenant-alpha",
"source": "excititor.overlay.v1",
"collectedAt": "2025-10-30T12:06:10Z",
"eventOffset": 3200,
"statement": {
"vexSource": "vendor-x",
"statementId": "statement-789",
"status": "not_affected",
"justification": "component not present",
"impactStatement": "Library not loaded at runtime",
"issuedAt": "2025-10-27T14:30:00Z",
"expiresAt": "2026-10-27T14:30:00Z",
"contentHash": "sha256:eee555",
"provenanceSource": "excititor.vex.v1",
"collectedAt": "2025-10-30T12:06:00Z",
"eventOffset": 3302
},
"exemptions": [
{
"componentPurl": "pkg:nuget/Newtonsoft.Json@13.0.3",
"componentSourceType": "inventory",
"sbomDigest": "sha256:sbom111",
"statementHash": "sha256:eee555",
"status": "not_affected",
"justification": "component not present",
"impactStatement": "Library not loaded at runtime",
"evidenceDigest": "sha256:evidence005",
"provenanceSource": "excititor.overlay.v1",
"collectedAt": "2025-10-30T12:06:10Z",
"eventOffset": 3200
}
]
}

View File

@@ -1,29 +0,0 @@
{
tenant: tenant-alpha,
source: concelier.overlay.v1,
linksetDigest: sha256:linkset001,
collectedAt: 2025-10-30T12:05:00Z,
eventOffset: 2201,
advisory: {
source: concelier.linkset.v1,
advisorySource: ghsa,
advisoryId: GHSA-1234-5678-90AB,
contentHash: sha256:ddd444,
severity: HIGH,
publishedAt: 2025-10-25T09:00:00Z
},
components: [
{
purl: pkg:nuget/Newtonsoft.Json@13.0.3,
sourceType: inventory,
sbomDigest: sha256:sbom111,
evidenceDigest: sha256:evidence004,
matchedVersions: [13.0.3],
cvss: 8.1,
confidence: 0.9,
collectedAt: 2025-10-30T12:05:10Z,
eventOffset: 3100,
source: concelier.overlay.v1
}
]
}

View File

@@ -1,280 +0,0 @@
[
{
"kind": "artifact",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"artifact_digest": "sha256:aaa111",
"sbom_digest": "sha256:sbom111"
},
"attributes": {
"display_name": "registry.example.com/team/app:1.2.3",
"artifact_digest": "sha256:aaa111",
"sbom_digest": "sha256:sbom111",
"environment": "prod",
"labels": [
"critical",
"payments"
],
"origin_registry": "registry.example.com",
"supply_chain_stage": "deploy"
},
"provenance": {
"source": "scanner.sbom.v1",
"collected_at": "2025-10-30T12:00:00Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 1182
},
"valid_from": "2025-10-30T12:00:00Z",
"valid_to": null,
"id": "gn:tenant-alpha:artifact:RX033HH7S6JXMY66QM51S89SX76B3JXJHWHPXPPBJCD05BR3GVXG",
"hash": "891601471f7dea636ec2988966b3aee3721a1faedb7e1c8e2834355eb4e31cfd"
},
{
"kind": "artifact",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"artifact_digest": "sha256:base000",
"sbom_digest": "sha256:sbom-base"
},
"attributes": {
"display_name": "registry.example.com/base/runtime:2025.09",
"artifact_digest": "sha256:base000",
"sbom_digest": "sha256:sbom-base",
"environment": "prod",
"labels": [
"base-image"
],
"origin_registry": "registry.example.com",
"supply_chain_stage": "build"
},
"provenance": {
"source": "scanner.sbom.v1",
"collected_at": "2025-10-22T08:00:00Z",
"sbom_digest": "sha256:sbom-base",
"event_offset": 800
},
"valid_from": "2025-10-22T08:00:00Z",
"valid_to": null,
"id": "gn:tenant-alpha:artifact:KD207PSJ36Q0B19CT8K8H2FQCV0HGQRNK8QWHFXE1VWAKPF9XH00",
"hash": "11593184fe6aa37a0e1d1909d4a401084a9ca452959a369590ac20d4dff77bd8"
},
{
"kind": "component",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"purl": "pkg:nuget/Newtonsoft.Json@13.0.3",
"source_type": "inventory"
},
"attributes": {
"purl": "pkg:nuget/Newtonsoft.Json@13.0.3",
"version": "13.0.3",
"ecosystem": "nuget",
"scope": "runtime",
"license_spdx": "MIT",
"usage": "direct"
},
"provenance": {
"source": "scanner.sbom.v1",
"collected_at": "2025-10-30T12:00:01Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 1183
},
"valid_from": "2025-10-30T12:00:01Z",
"valid_to": null,
"id": "gn:tenant-alpha:component:BQSZFXSPNGS6M8XEQZ6XX3E7775XZQABM301GFPFXCQSQSA1WHZ0",
"hash": "e4c22e7522573b746c654bb6bdd05d01db1bcd34db8b22e5e12d2e8528268786"
},
{
"kind": "component",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"purl": "pkg:nuget/System.Text.Encoding.Extensions@4.7.0",
"source_type": "inventory"
},
"attributes": {
"purl": "pkg:nuget/System.Text.Encoding.Extensions@4.7.0",
"version": "4.7.0",
"ecosystem": "nuget",
"scope": "runtime",
"license_spdx": "MIT",
"usage": "transitive"
},
"provenance": {
"source": "scanner.sbom.v1",
"collected_at": "2025-10-30T12:00:01Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 1184
},
"valid_from": "2025-10-30T12:00:01Z",
"valid_to": null,
"id": "gn:tenant-alpha:component:FZ9EHXFFGPDQAEKAPWZ4JX5X6KYS467PJ5D1Y4T9NFFQG2SG0DV0",
"hash": "b941ff7178451b7a0403357d08ed8996e8aea1bf40032660e18406787e57ce3f"
},
{
"kind": "file",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"artifact_digest": "sha256:aaa111",
"normalized_path": "/src/app/Program.cs",
"content_sha256": "sha256:bbb222"
},
"attributes": {
"normalized_path": "/src/app/Program.cs",
"content_sha256": "sha256:bbb222",
"language_hint": "csharp",
"size_bytes": 3472,
"scope": "build"
},
"provenance": {
"source": "scanner.layer.v1",
"collected_at": "2025-10-30T12:00:02Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 1185
},
"valid_from": "2025-10-30T12:00:02Z",
"valid_to": null,
"id": "gn:tenant-alpha:file:M1MWHCXA66MQE8FZMPK3RNRMN7Z18H4VGWX6QTNNBKABFKRACKDG",
"hash": "a0a7e7b6ff4a8357bea3273e38b3a3d801531a4f6b716513b7d4972026db3a76"
},
{
"kind": "license",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"license_spdx": "Apache-2.0",
"source_digest": "sha256:ccc333"
},
"attributes": {
"license_spdx": "Apache-2.0",
"name": "Apache License 2.0",
"classification": "permissive",
"notice_uri": "https://www.apache.org/licenses/LICENSE-2.0"
},
"provenance": {
"source": "scanner.sbom.v1",
"collected_at": "2025-10-30T12:00:03Z",
"sbom_digest": "sha256:sbom111",
"event_offset": 1186
},
"valid_from": "2025-10-30T12:00:03Z",
"valid_to": null,
"id": "gn:tenant-alpha:license:7SDDWTRKXYG9MBK89X7JFMAQRBEZHV1NFZNSN2PBRZT5H0FHZB90",
"hash": "790f1d803dd35d9f77b08977e4dd3fc9145218ee7c68524881ee13b7a2e9ede8"
},
{
"tenant": "tenant-alpha",
"kind": "advisory",
"canonical_key": {
"advisory_id": "GHSA-1234-5678-90AB",
"advisory_source": "ghsa",
"content_hash": "sha256:ddd444",
"tenant": "tenant-alpha"
},
"attributes": {
"advisory_source": "ghsa",
"advisory_id": "GHSA-1234-5678-90AB",
"severity": "HIGH",
"published_at": "2025-10-25T09:00:00Z",
"content_hash": "sha256:ddd444",
"linkset_digest": "sha256:linkset001"
},
"provenance": {
"source": "concelier.linkset.v1",
"collected_at": "2025-10-30T12:05:10Z",
"sbom_digest": null,
"event_offset": 3100
},
"valid_from": "2025-10-25T09:00:00Z",
"valid_to": null,
"id": "gn:tenant-alpha:advisory:RFGYXZ2TG0BF117T3HCX3XYAZFXPD72991QD0JZWDVY7FXYY87R0",
"hash": "df4b4087dc6bf4c8b071ce808b97025036a6d33d30ea538a279a4f55ed7ffb8e"
},
{
"tenant": "tenant-alpha",
"kind": "vex_statement",
"canonical_key": {
"content_hash": "sha256:eee555",
"statement_id": "statement-789",
"tenant": "tenant-alpha",
"vex_source": "vendor-x"
},
"attributes": {
"status": "not_affected",
"statement_id": "statement-789",
"justification": "component not present",
"issued_at": "2025-10-27T14:30:00Z",
"expires_at": "2026-10-27T14:30:00Z",
"content_hash": "sha256:eee555"
},
"provenance": {
"source": "excititor.vex.v1",
"collected_at": "2025-10-30T12:06:00Z",
"sbom_digest": null,
"event_offset": 3302
},
"valid_from": "2025-10-27T14:30:00Z",
"valid_to": null,
"id": "gn:tenant-alpha:vex_statement:BVRF35CX6TZTHPD7YFHYTJJACPYJD86JP7C74SH07QT9JT82NDSG",
"hash": "4b613e2b8460c542597bbc70b8ba3e6796c3e1d261d0c74ce30fba42f7681f25"
},
{
"kind": "policy_version",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"policy_pack_digest": "sha256:fff666",
"effective_from": "2025-10-28T00:00:00Z"
},
"attributes": {
"policy_pack_digest": "sha256:fff666",
"policy_name": "Default Runtime Policy",
"effective_from": "2025-10-28T00:00:00Z",
"expires_at": "2026-01-01T00:00:00Z",
"explain_hash": "sha256:explain001"
},
"provenance": {
"source": "policy.engine.v1",
"collected_at": "2025-10-28T00:00:05Z",
"sbom_digest": null,
"event_offset": 4100
},
"valid_from": "2025-10-28T00:00:00Z",
"valid_to": "2026-01-01T00:00:00Z",
"id": "gn:tenant-alpha:policy_version:YZSMWHHR6Y5XR1HFRBV3H5TR6GMZVN9BPDAAVQEACV7XRYP06390",
"hash": "a8539c4d611535c3afcfd406a08208ab3bbfc81f6e31f87dd727b7d8bd9c4209"
},
{
"kind": "runtime_context",
"tenant": "tenant-alpha",
"canonical_key": {
"tenant": "tenant-alpha",
"runtime_fingerprint": "pod-abc123",
"collector": "zastava.v1",
"observed_at": "2025-10-30T12:15:00Z"
},
"attributes": {
"runtime_fingerprint": "pod-abc123",
"collector": "zastava.v1",
"observed_at": "2025-10-30T12:15:00Z",
"cluster": "prod-cluster-1",
"namespace": "payments",
"workload_kind": "deployment",
"runtime_state": "Running"
},
"provenance": {
"source": "signals.runtime.v1",
"collected_at": "2025-10-30T12:15:05Z",
"sbom_digest": null,
"event_offset": 5109
},
"valid_from": "2025-10-30T12:15:00Z",
"valid_to": null,
"id": "gn:tenant-alpha:runtime_context:EFVARD7VM4710F8554Q3NGH0X8W7XRF3RDARE8YJWK1H3GABX8A0",
"hash": "0294c4131ba98d52674ca31a409488b73f47a193cf3a13cede8671e6112a5a29"
}
]

View File

@@ -1,31 +0,0 @@
{
"tenant": "tenant-alpha",
"source": "policy.engine.v1",
"collectedAt": "2025-10-30T12:07:00Z",
"eventOffset": 4200,
"policy": {
"source": "policy.engine.v1",
"policyPackDigest": "sha256:fff666",
"policyName": "Default Runtime Policy",
"effectiveFrom": "2025-10-28T00:00:00Z",
"expiresAt": "2026-01-01T00:00:00Z",
"explainHash": "sha256:explain001",
"collectedAt": "2025-10-28T00:00:05Z",
"eventOffset": 4100
},
"evaluations": [
{
"componentPurl": "pkg:nuget/Newtonsoft.Json@13.0.3",
"componentSourceType": "inventory",
"findingExplainHash": "sha256:explain001",
"explainHash": "sha256:explain001",
"policyRuleId": "rule:runtime/critical-dependency",
"verdict": "fail",
"evaluationTimestamp": "2025-10-30T12:07:00Z",
"sbomDigest": "sha256:sbom111",
"source": "policy.engine.v1",
"collectedAt": "2025-10-30T12:07:00Z",
"eventOffset": 4200
}
]
}

View File

@@ -1,110 +0,0 @@
{
"tenant": "tenant-alpha",
"source": "scanner.sbom.v1",
"artifactDigest": "sha256:aaa111",
"sbomDigest": "sha256:sbom111",
"collectedAt": "2025-10-30T12:00:00Z",
"eventOffset": 1182,
"artifact": {
"displayName": "registry.example.com/team/app:1.2.3",
"environment": "prod",
"labels": [
"critical",
"payments"
],
"originRegistry": "registry.example.com",
"supplyChainStage": "deploy"
},
"build": {
"builderId": "builder://tekton/pipeline/default",
"buildType": "https://slsa.dev/provenance/v1",
"attestationDigest": "sha256:attestation001",
"source": "scanner.provenance.v1",
"collectedAt": "2025-10-30T12:00:05Z",
"eventOffset": 2103
},
"components": [
{
"purl": "pkg:nuget/Newtonsoft.Json@13.0.3",
"version": "13.0.3",
"ecosystem": "nuget",
"scope": "runtime",
"license": {
"spdx": "MIT",
"name": "MIT License",
"classification": "permissive",
"noticeUri": "https://opensource.org/licenses/MIT",
"sourceDigest": "sha256:ccc333"
},
"usage": "direct",
"detectedBy": "sbom.analyzer.nuget",
"layerDigest": "sha256:layer123",
"evidenceDigest": "sha256:evidence001",
"collectedAt": "2025-10-30T12:00:01Z",
"eventOffset": 1183,
"source": "scanner.sbom.v1",
"files": [
{
"path": "/src/app/Program.cs",
"contentSha256": "sha256:bbb222",
"languageHint": "csharp",
"sizeBytes": 3472,
"scope": "build",
"detectedBy": "sbom.analyzer.nuget",
"evidenceDigest": "sha256:evidence003",
"collectedAt": "2025-10-30T12:00:02Z",
"eventOffset": 1185,
"source": "scanner.layer.v1"
}
],
"dependencies": [
{
"purl": "pkg:nuget/System.Text.Encoding.Extensions@4.7.0",
"version": "4.7.0",
"relationship": "direct",
"evidenceDigest": "sha256:evidence002",
"collectedAt": "2025-10-30T12:00:01Z",
"eventOffset": 1183
}
]
},
{
"purl": "pkg:nuget/System.Text.Encoding.Extensions@4.7.0",
"version": "4.7.0",
"ecosystem": "nuget",
"scope": "runtime",
"license": {
"spdx": "MIT",
"name": "MIT License",
"classification": "permissive",
"noticeUri": "https://opensource.org/licenses/MIT",
"sourceDigest": "sha256:ccc333"
},
"usage": "transitive",
"detectedBy": "sbom.analyzer.nuget",
"layerDigest": "sha256:layer123",
"evidenceDigest": "sha256:evidence001",
"collectedAt": "2025-10-30T12:00:01Z",
"eventOffset": 1184,
"source": "scanner.sbom.v1",
"files": [],
"dependencies": []
}
],
"baseArtifacts": [
{
"artifactDigest": "sha256:base000",
"sbomDigest": "sha256:sbom-base",
"displayName": "registry.example.com/base/runtime:2025.09",
"environment": "prod",
"labels": [
"base-image"
],
"originRegistry": "registry.example.com",
"supplyChainStage": "build",
"collectedAt": "2025-10-22T08:00:00Z",
"eventOffset": 800,
"source": "scanner.sbom.v1"
}
]
}

View File

@@ -1,115 +0,0 @@
{
"version": "v1",
"nodes": {
"artifact": [
"display_name",
"artifact_digest",
"sbom_digest",
"environment",
"labels",
"origin_registry",
"supply_chain_stage"
],
"component": [
"purl",
"version",
"ecosystem",
"scope",
"license_spdx",
"usage"
],
"file": [
"normalized_path",
"content_sha256",
"language_hint",
"size_bytes",
"scope"
],
"license": [
"license_spdx",
"name",
"classification",
"notice_uri"
],
"advisory": [
"advisory_source",
"advisory_id",
"severity",
"published_at",
"content_hash",
"linkset_digest"
],
"vex_statement": [
"status",
"statement_id",
"justification",
"issued_at",
"expires_at",
"content_hash"
],
"policy_version": [
"policy_pack_digest",
"policy_name",
"effective_from",
"expires_at",
"explain_hash"
],
"runtime_context": [
"runtime_fingerprint",
"collector",
"observed_at",
"cluster",
"namespace",
"workload_kind",
"runtime_state"
]
},
"edges": {
"CONTAINS": [
"detected_by",
"layer_digest",
"scope",
"evidence_digest"
],
"DEPENDS_ON": [
"dependency_purl",
"dependency_version",
"relationship",
"evidence_digest"
],
"DECLARED_IN": [
"detected_by",
"scope",
"evidence_digest"
],
"BUILT_FROM": [
"build_type",
"builder_id",
"attestation_digest"
],
"AFFECTED_BY": [
"evidence_digest",
"matched_versions",
"cvss",
"confidence"
],
"VEX_EXEMPTS": [
"status",
"justification",
"impact_statement",
"evidence_digest"
],
"GOVERNS_WITH": [
"verdict",
"explain_hash",
"policy_rule_id",
"evaluation_timestamp"
],
"OBSERVED_RUNTIME": [
"process_name",
"entrypoint_kind",
"runtime_evidence_digest",
"confidence"
]
}
}

View File

@@ -1,110 +0,0 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using FluentAssertions;
using StellaOps.Graph.Indexer.Schema;
using Xunit;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class GraphIdentityTests
{
private static readonly string FixturesRoot =
Path.Combine(AppContext.BaseDirectory, "Fixtures", "v1");
[Fact]
public void NodeIds_are_stable()
{
var nodes = LoadArray("nodes.json");
foreach (var node in nodes.Cast<JsonObject>())
{
var tenant = node["tenant"]!.GetValue<string>();
var kind = node["kind"]!.GetValue<string>();
var canonicalKey = (JsonObject)node["canonical_key"]!;
var tuple = GraphIdentity.ExtractIdentityTuple(canonicalKey);
var expectedId = node["id"]!.GetValue<string>();
var actualId = GraphIdentity.ComputeNodeId(tenant, kind, tuple);
actualId.Should()
.Be(expectedId, $"node {kind} with canonical tuple {canonicalKey.ToJsonString()} must have deterministic id");
var documentClone = JsonNode.Parse(node.ToJsonString())!.AsObject();
documentClone.Remove("hash");
var expectedHash = node["hash"]!.GetValue<string>();
var actualHash = GraphIdentity.ComputeDocumentHash(documentClone);
actualHash.Should()
.Be(expectedHash, $"node {kind}:{expectedId} must have deterministic document hash");
}
}
[Fact]
public void EdgeIds_are_stable()
{
var edges = LoadArray("edges.json");
foreach (var edge in edges.Cast<JsonObject>())
{
var tenant = edge["tenant"]!.GetValue<string>();
var kind = edge["kind"]!.GetValue<string>();
var canonicalKey = (JsonObject)edge["canonical_key"]!;
var tuple = GraphIdentity.ExtractIdentityTuple(canonicalKey);
var expectedId = edge["id"]!.GetValue<string>();
var actualId = GraphIdentity.ComputeEdgeId(tenant, kind, tuple);
actualId.Should()
.Be(expectedId, $"edge {kind} with canonical tuple {canonicalKey.ToJsonString()} must have deterministic id");
var documentClone = JsonNode.Parse(edge.ToJsonString())!.AsObject();
documentClone.Remove("hash");
var expectedHash = edge["hash"]!.GetValue<string>();
var actualHash = GraphIdentity.ComputeDocumentHash(documentClone);
actualHash.Should()
.Be(expectedHash, $"edge {kind}:{expectedId} must have deterministic document hash");
}
}
[Fact]
public void AttributeCoverage_matches_matrix()
{
var matrix = LoadObject("schema-matrix.json");
var nodeExpectations = (JsonObject)matrix["nodes"]!;
var edgeExpectations = (JsonObject)matrix["edges"]!;
var nodes = LoadArray("nodes.json");
foreach (var node in nodes.Cast<JsonObject>())
{
var kind = node["kind"]!.GetValue<string>();
var expectedAttributes = nodeExpectations[kind]!.AsArray().Select(x => x!.GetValue<string>()).OrderBy(x => x, StringComparer.Ordinal).ToArray();
var actualAttributes = ((JsonObject)node["attributes"]!).Select(pair => pair.Key).OrderBy(x => x, StringComparer.Ordinal).ToArray();
actualAttributes.Should()
.Equal(expectedAttributes, $"node kind {kind} must align with schema matrix");
}
var edges = LoadArray("edges.json");
foreach (var edge in edges.Cast<JsonObject>())
{
var kind = edge["kind"]!.GetValue<string>();
var expectedAttributes = edgeExpectations[kind]!.AsArray().Select(x => x!.GetValue<string>()).OrderBy(x => x, StringComparer.Ordinal).ToArray();
var actualAttributes = ((JsonObject)edge["attributes"]!).Select(pair => pair.Key).OrderBy(x => x, StringComparer.Ordinal).ToArray();
actualAttributes.Should()
.Equal(expectedAttributes, $"edge kind {kind} must align with schema matrix");
}
}
private static JsonArray LoadArray(string fileName)
=> (JsonArray)JsonNode.Parse(File.ReadAllText(GetFixturePath(fileName)))!;
private static JsonObject LoadObject(string fileName)
=> (JsonObject)JsonNode.Parse(File.ReadAllText(GetFixturePath(fileName)))!;
private static string GetFixturePath(string fileName)
=> Path.Combine(FixturesRoot, fileName);
}

View File

@@ -1,147 +0,0 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using FluentAssertions;
using StellaOps.Graph.Indexer.Documents;
using StellaOps.Graph.Indexer.Ingestion.Advisory;
using StellaOps.Graph.Indexer.Ingestion.Policy;
using StellaOps.Graph.Indexer.Ingestion.Sbom;
using StellaOps.Graph.Indexer.Ingestion.Vex;
using StellaOps.Graph.Indexer.Schema;
using Xunit;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class GraphSnapshotBuilderTests
{
private static readonly string FixturesRoot =
Path.Combine(AppContext.BaseDirectory, "Fixtures", "v1");
[Fact]
public void Build_creates_manifest_and_adjacency_with_lineage()
{
var sbomSnapshot = Load<SbomSnapshot>("sbom-snapshot.json");
var linksetSnapshot = Load<AdvisoryLinksetSnapshot>("concelier-linkset.json");
var vexSnapshot = Load<VexOverlaySnapshot>("excititor-vex.json");
var policySnapshot = Load<PolicyOverlaySnapshot>("policy-overlay.json");
var sbomBatch = new SbomIngestTransformer().Transform(sbomSnapshot);
var advisoryBatch = new AdvisoryLinksetTransformer().Transform(linksetSnapshot);
var vexBatch = new VexOverlayTransformer().Transform(vexSnapshot);
var policyBatch = new PolicyOverlayTransformer().Transform(policySnapshot);
var combinedBatch = MergeBatches(sbomBatch, advisoryBatch, vexBatch, policyBatch);
var builder = new GraphSnapshotBuilder();
var generatedAt = DateTimeOffset.Parse("2025-10-30T12:06:30Z");
var snapshot = builder.Build(sbomSnapshot, combinedBatch, generatedAt);
snapshot.Manifest.Tenant.Should().Be("tenant-alpha");
snapshot.Manifest.ArtifactDigest.Should().Be("sha256:aaa111");
snapshot.Manifest.SbomDigest.Should().Be("sha256:sbom111");
snapshot.Manifest.GeneratedAt.Should().Be(generatedAt);
snapshot.Manifest.NodeCount.Should().Be(combinedBatch.Nodes.Length);
snapshot.Manifest.EdgeCount.Should().Be(combinedBatch.Edges.Length);
snapshot.Manifest.Files.Nodes.Should().Be("nodes.jsonl");
snapshot.Manifest.Files.Edges.Should().Be("edges.jsonl");
snapshot.Manifest.Files.Adjacency.Should().Be("adjacency.json");
snapshot.Manifest.Lineage.DerivedFromSbomDigests.Should().BeEquivalentTo(new[] { "sha256:sbom-base" }, options => options.WithStrictOrdering());
snapshot.Manifest.Lineage.BaseArtifactDigests.Should().BeEquivalentTo(new[] { "sha256:base000" }, options => options.WithStrictOrdering());
snapshot.Manifest.Lineage.SourceSnapshotId.Should().BeNull();
var manifestJson = snapshot.Manifest.ToJson();
manifestJson.Should().NotBeNull();
manifestJson["hash"]!.GetValue<string>().Should().Be(snapshot.Manifest.Hash);
var manifestWithoutHash = (JsonObject)manifestJson.DeepClone();
manifestWithoutHash.Remove("hash");
var expectedManifestHash = GraphIdentity.ComputeDocumentHash(manifestWithoutHash);
snapshot.Manifest.Hash.Should().Be(expectedManifestHash);
var adjacency = snapshot.Adjacency;
adjacency.Tenant.Should().Be("tenant-alpha");
adjacency.SnapshotId.Should().Be(snapshot.Manifest.SnapshotId);
adjacency.GeneratedAt.Should().Be(generatedAt);
var adjacencyNodes = adjacency.Nodes.ToDictionary(node => node.NodeId, StringComparer.Ordinal);
adjacencyNodes.Should().ContainKey("gn:tenant-alpha:artifact:RX033HH7S6JXMY66QM51S89SX76B3JXJHWHPXPPBJCD05BR3GVXG");
var artifactAdjacency = adjacencyNodes["gn:tenant-alpha:artifact:RX033HH7S6JXMY66QM51S89SX76B3JXJHWHPXPPBJCD05BR3GVXG"];
artifactAdjacency.OutgoingEdges.Should().BeEquivalentTo(new[]
{
"ge:tenant-alpha:BUILT_FROM:HJNKVFSDSA44HRY0XAJ0GBEVPD2S82JFF58BZVRT9QF6HB2EGPJG",
"ge:tenant-alpha:CONTAINS:EVA5N7P029VYV9W8Q7XJC0JFTEQYFSAQ6381SNVM3T1G5290XHTG"
}, options => options.WithStrictOrdering());
artifactAdjacency.IncomingEdges.Should().BeEmpty();
var componentAdjacency = adjacencyNodes["gn:tenant-alpha:component:BQSZFXSPNGS6M8XEQZ6XX3E7775XZQABM301GFPFXCQSQSA1WHZ0"];
componentAdjacency.IncomingEdges.Should().BeEquivalentTo(new[]
{
"ge:tenant-alpha:CONTAINS:EVA5N7P029VYV9W8Q7XJC0JFTEQYFSAQ6381SNVM3T1G5290XHTG",
"ge:tenant-alpha:GOVERNS_WITH:XG3KQTYT8D4NY0BTFXWGBQY6TXR2MRYDWZBQT07T0200NQ72AFG0"
});
componentAdjacency.OutgoingEdges.Should().BeEquivalentTo(new[]
{
"ge:tenant-alpha:DEPENDS_ON:FJ7GZ9RHPKPR30XVKECD702QG20PGT3V75DY1GST8AAW9SR8TBB0",
"ge:tenant-alpha:DECLARED_IN:T7E8NQEMKXPZ3T1SWT8HXKWAHJVS9QKD87XBKAQAAQ29CDHEA47G",
"ge:tenant-alpha:AFFECTED_BY:1V3NRKAR6KMXAWZ89R69G8JAY3HV7DXNB16YY9X25X1TAFW9VGYG",
"ge:tenant-alpha:VEX_EXEMPTS:DT0BBCM9S0KJVF61KVR7D2W8DVFTKK03F3TFD4DR9DRS0T5CWZM0"
});
var dependencyComponent = adjacencyNodes["gn:tenant-alpha:component:FZ9EHXFFGPDQAEKAPWZ4JX5X6KYS467PJ5D1Y4T9NFFQG2SG0DV0"];
dependencyComponent.IncomingEdges.Should().BeEquivalentTo(new[]
{
"ge:tenant-alpha:DEPENDS_ON:FJ7GZ9RHPKPR30XVKECD702QG20PGT3V75DY1GST8AAW9SR8TBB0"
});
dependencyComponent.OutgoingEdges.Should().BeEmpty();
adjacency.Nodes.Length.Should().Be(combinedBatch.Nodes.Length);
}
private static GraphBuildBatch MergeBatches(params GraphBuildBatch[] batches)
{
var nodes = new Dictionary<string, JsonObject>(StringComparer.Ordinal);
var edges = new Dictionary<string, JsonObject>(StringComparer.Ordinal);
foreach (var batch in batches)
{
foreach (var node in batch.Nodes)
{
nodes[node["id"]!.GetValue<string>()] = node;
}
foreach (var edge in batch.Edges)
{
edges[edge["id"]!.GetValue<string>()] = edge;
}
}
var orderedNodes = nodes.Values
.OrderBy(node => node["kind"]!.GetValue<string>(), StringComparer.Ordinal)
.ThenBy(node => node["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToImmutableArray();
var orderedEdges = edges.Values
.OrderBy(edge => edge["kind"]!.GetValue<string>(), StringComparer.Ordinal)
.ThenBy(edge => edge["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToImmutableArray();
return new GraphBuildBatch(orderedNodes, orderedEdges);
}
private static T Load<T>(string fixtureFile)
{
var path = Path.Combine(FixturesRoot, fixtureFile);
var json = File.ReadAllText(path);
return JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
})!;
}
}

View File

@@ -1,136 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using StellaOps.Graph.Indexer.Ingestion.Policy;
using StellaOps.Graph.Indexer.Ingestion.Sbom;
using Xunit;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class PolicyOverlayProcessorTests
{
[Fact]
public async Task ProcessAsync_persists_overlay_and_records_success_metrics()
{
var snapshot = CreateSnapshot();
var transformer = new PolicyOverlayTransformer();
var writer = new CaptureWriter();
var metrics = new CaptureMetrics();
var processor = new PolicyOverlayProcessor(
transformer,
writer,
metrics,
NullLogger<PolicyOverlayProcessor>.Instance);
await processor.ProcessAsync(snapshot, CancellationToken.None);
writer.LastBatch.Should().NotBeNull();
metrics.LastRecord.Should().NotBeNull();
metrics.LastRecord!.Success.Should().BeTrue();
metrics.LastRecord.NodeCount.Should().Be(writer.LastBatch!.Nodes.Length);
metrics.LastRecord.EdgeCount.Should().Be(writer.LastBatch!.Edges.Length);
}
[Fact]
public async Task ProcessAsync_records_failure_when_writer_throws()
{
var snapshot = CreateSnapshot();
var transformer = new PolicyOverlayTransformer();
var writer = new CaptureWriter(shouldThrow: true);
var metrics = new CaptureMetrics();
var processor = new PolicyOverlayProcessor(
transformer,
writer,
metrics,
NullLogger<PolicyOverlayProcessor>.Instance);
var act = () => processor.ProcessAsync(snapshot, CancellationToken.None);
await act.Should().ThrowAsync<InvalidOperationException>();
metrics.LastRecord.Should().NotBeNull();
metrics.LastRecord!.Success.Should().BeFalse();
}
private static PolicyOverlaySnapshot CreateSnapshot()
{
return new PolicyOverlaySnapshot
{
Tenant = "tenant-alpha",
Source = "policy.engine.v1",
CollectedAt = DateTimeOffset.Parse("2025-10-30T12:07:00Z"),
EventOffset = 4200,
Policy = new PolicyVersionDetails
{
Source = "policy.engine.v1",
PolicyPackDigest = "sha256:fff666",
PolicyName = "Default Runtime Policy",
EffectiveFrom = DateTimeOffset.Parse("2025-10-28T00:00:00Z"),
ExpiresAt = DateTimeOffset.Parse("2026-01-01T00:00:00Z"),
ExplainHash = "sha256:explain001",
CollectedAt = DateTimeOffset.Parse("2025-10-28T00:00:05Z"),
EventOffset = 4100
},
Evaluations = new[]
{
new PolicyEvaluation
{
ComponentPurl = "pkg:nuget/Newtonsoft.Json@13.0.3",
ComponentSourceType = "inventory",
FindingExplainHash = "sha256:explain001",
ExplainHash = "sha256:explain001",
PolicyRuleId = "rule:runtime/critical-dependency",
Verdict = "fail",
EvaluationTimestamp = DateTimeOffset.Parse("2025-10-30T12:07:00Z"),
SbomDigest = "sha256:sbom111",
Source = "policy.engine.v1",
CollectedAt = DateTimeOffset.Parse("2025-10-30T12:07:00Z"),
EventOffset = 4200
}
}
};
}
private sealed class CaptureWriter : IGraphDocumentWriter
{
private readonly bool _shouldThrow;
public CaptureWriter(bool shouldThrow = false)
{
_shouldThrow = shouldThrow;
}
public GraphBuildBatch? LastBatch { get; private set; }
public Task WriteAsync(GraphBuildBatch batch, CancellationToken cancellationToken)
{
LastBatch = batch;
if (_shouldThrow)
{
throw new InvalidOperationException("Simulated persistence failure");
}
return Task.CompletedTask;
}
}
private sealed class CaptureMetrics : IPolicyOverlayMetrics
{
public MetricRecord? LastRecord { get; private set; }
public void RecordBatch(string source, string tenant, int nodeCount, int edgeCount, TimeSpan duration, bool success)
{
LastRecord = new MetricRecord(source, tenant, nodeCount, edgeCount, duration, success);
}
}
private sealed record MetricRecord(
string Source,
string Tenant,
int NodeCount,
int EdgeCount,
TimeSpan Duration,
bool Success);
}

View File

@@ -1,107 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using FluentAssertions;
using StellaOps.Graph.Indexer.Ingestion.Policy;
using Xunit;
using Xunit.Abstractions;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class PolicyOverlayTransformerTests
{
private readonly ITestOutputHelper _output;
public PolicyOverlayTransformerTests(ITestOutputHelper output)
{
_output = output;
}
private static readonly string FixturesRoot =
Path.Combine(AppContext.BaseDirectory, "Fixtures", "v1");
private static readonly HashSet<string> ExpectedNodeKinds = new(StringComparer.Ordinal)
{
"policy_version"
};
private static readonly HashSet<string> ExpectedEdgeKinds = new(StringComparer.Ordinal)
{
"GOVERNS_WITH"
};
[Fact]
public void Transform_projects_policy_nodes_and_governs_with_edges()
{
var snapshot = LoadSnapshot("policy-overlay.json");
var transformer = new PolicyOverlayTransformer();
var batch = transformer.Transform(snapshot);
var expectedNodes = LoadArray("nodes.json")
.Cast<JsonObject>()
.Where(node => ExpectedNodeKinds.Contains(node["kind"]!.GetValue<string>()))
.OrderBy(node => node["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var expectedEdges = LoadArray("edges.json")
.Cast<JsonObject>()
.Where(edge => ExpectedEdgeKinds.Contains(edge["kind"]!.GetValue<string>()))
.OrderBy(edge => edge["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var actualNodes = batch.Nodes
.Where(node => ExpectedNodeKinds.Contains(node["kind"]!.GetValue<string>()))
.OrderBy(node => node["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var actualEdges = batch.Edges
.Where(edge => ExpectedEdgeKinds.Contains(edge["kind"]!.GetValue<string>()))
.OrderBy(edge => edge["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
actualNodes.Length.Should().Be(expectedNodes.Length);
actualEdges.Length.Should().Be(expectedEdges.Length);
for (var i = 0; i < expectedNodes.Length; i++)
{
if (!JsonNode.DeepEquals(expectedNodes[i], actualNodes[i]))
{
_output.WriteLine($"Expected Node: {expectedNodes[i]}");
_output.WriteLine($"Actual Node: {actualNodes[i]}");
}
JsonNode.DeepEquals(expectedNodes[i], actualNodes[i]).Should().BeTrue();
}
for (var i = 0; i < expectedEdges.Length; i++)
{
if (!JsonNode.DeepEquals(expectedEdges[i], actualEdges[i]))
{
_output.WriteLine($"Expected Edge: {expectedEdges[i]}");
_output.WriteLine($"Actual Edge: {actualEdges[i]}");
}
JsonNode.DeepEquals(expectedEdges[i], actualEdges[i]).Should().BeTrue();
}
}
private static PolicyOverlaySnapshot LoadSnapshot(string fileName)
{
var path = Path.Combine(FixturesRoot, fileName);
var json = File.ReadAllText(path);
return JsonSerializer.Deserialize<PolicyOverlaySnapshot>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
})!;
}
private static JsonArray LoadArray(string fileName)
{
var path = Path.Combine(FixturesRoot, fileName);
return (JsonArray)JsonNode.Parse(File.ReadAllText(path))!;
}
}

View File

@@ -1,4 +0,0 @@
# StellaOps Graph Indexer Tests
The Graph Indexer tests now run entirely in-memory and no longer require MongoDB.
No special environment variables are needed to execute the suite locally or in CI.

View File

@@ -1,194 +0,0 @@
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using StellaOps.Graph.Indexer.Ingestion.Sbom;
using Xunit;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class SbomIngestProcessorTests
{
[Fact]
public async Task ProcessAsync_writes_batch_and_records_success_metrics()
{
var snapshot = CreateSnapshot();
var transformer = new SbomIngestTransformer();
var writer = new CaptureWriter();
var metrics = new CaptureMetrics();
var snapshotExporter = new CaptureSnapshotExporter();
var processor = new SbomIngestProcessor(transformer, writer, metrics, snapshotExporter, NullLogger<SbomIngestProcessor>.Instance);
await processor.ProcessAsync(snapshot, CancellationToken.None);
writer.LastBatch.Should().NotBeNull();
metrics.LastRecord.Should().NotBeNull();
metrics.LastRecord!.Success.Should().BeTrue();
metrics.LastRecord.NodeCount.Should().Be(writer.LastBatch!.Nodes.Length);
metrics.LastRecord.EdgeCount.Should().Be(writer.LastBatch!.Edges.Length);
snapshotExporter.LastSnapshot.Should().BeSameAs(snapshot);
snapshotExporter.LastBatch.Should().BeSameAs(writer.LastBatch);
}
[Fact]
public async Task ProcessAsync_records_failure_when_writer_throws()
{
var snapshot = CreateSnapshot();
var transformer = new SbomIngestTransformer();
var writer = new CaptureWriter(shouldThrow: true);
var metrics = new CaptureMetrics();
var snapshotExporter = new CaptureSnapshotExporter();
var processor = new SbomIngestProcessor(transformer, writer, metrics, snapshotExporter, NullLogger<SbomIngestProcessor>.Instance);
var act = () => processor.ProcessAsync(snapshot, CancellationToken.None);
await act.Should().ThrowAsync<InvalidOperationException>();
metrics.LastRecord.Should().NotBeNull();
metrics.LastRecord!.Success.Should().BeFalse();
snapshotExporter.LastSnapshot.Should().BeNull();
snapshotExporter.LastBatch.Should().BeNull();
}
private static SbomSnapshot CreateSnapshot()
{
return new SbomSnapshot
{
Tenant = "tenant-alpha",
Source = "scanner.sbom.v1",
ArtifactDigest = "sha256:test-artifact",
SbomDigest = "sha256:test-sbom",
CollectedAt = DateTimeOffset.Parse("2025-10-30T12:00:00Z"),
EventOffset = 1000,
Artifact = new SbomArtifactMetadata
{
DisplayName = "registry.example.com/app:latest",
Environment = "prod",
Labels = new[] { "demo" },
OriginRegistry = "registry.example.com",
SupplyChainStage = "deploy"
},
Build = new SbomBuildMetadata
{
BuilderId = "builder://tekton/default",
BuildType = "https://slsa.dev/provenance/v1",
AttestationDigest = "sha256:attestation",
Source = "scanner.build.v1",
CollectedAt = DateTimeOffset.Parse("2025-10-30T12:00:05Z"),
EventOffset = 2000
},
Components = new[]
{
new SbomComponent
{
Purl = "pkg:nuget/Example.Primary@1.0.0",
Version = "1.0.0",
Ecosystem = "nuget",
Scope = "runtime",
License = new SbomLicense
{
Spdx = "MIT",
Name = "MIT License",
Classification = "permissive",
SourceDigest = "sha256:license001"
},
Usage = "direct",
DetectedBy = "sbom.analyzer.transformer",
LayerDigest = "sha256:layer",
EvidenceDigest = "sha256:evidence",
CollectedAt = DateTimeOffset.Parse("2025-10-30T12:00:01Z"),
EventOffset = 1201,
Source = "scanner.component.v1",
Files = new[]
{
new SbomComponentFile
{
Path = "/src/app/Program.cs",
ContentSha256 = "sha256:file",
LanguageHint = "csharp",
SizeBytes = 1024,
Scope = "build",
DetectedBy = "sbom.analyzer.transformer",
EvidenceDigest = "sha256:file-evidence",
CollectedAt = DateTimeOffset.Parse("2025-10-30T12:00:02Z"),
EventOffset = 1202,
Source = "scanner.layer.v1"
}
},
Dependencies = Array.Empty<SbomDependency>(),
SourceType = "inventory"
}
},
BaseArtifacts = new[]
{
new SbomBaseArtifact
{
ArtifactDigest = "sha256:base",
SbomDigest = "sha256:base-sbom",
DisplayName = "registry.example.com/base:2025.09",
Environment = "prod",
Labels = new[] { "base-image" },
OriginRegistry = "registry.example.com",
SupplyChainStage = "build",
CollectedAt = DateTimeOffset.Parse("2025-10-22T08:00:00Z"),
EventOffset = 800,
Source = "scanner.sbom.v1"
}
}
};
}
private sealed class CaptureWriter : IGraphDocumentWriter
{
private readonly bool _shouldThrow;
public CaptureWriter(bool shouldThrow = false)
{
_shouldThrow = shouldThrow;
}
public GraphBuildBatch? LastBatch { get; private set; }
public Task WriteAsync(GraphBuildBatch batch, CancellationToken cancellationToken)
{
LastBatch = batch;
if (_shouldThrow)
{
throw new InvalidOperationException("Simulated persistence failure");
}
return Task.CompletedTask;
}
}
private sealed class CaptureMetrics : ISbomIngestMetrics
{
public MetricRecord? LastRecord { get; private set; }
public void RecordBatch(string source, string tenant, int nodeCount, int edgeCount, TimeSpan duration, bool success)
{
LastRecord = new MetricRecord(source, tenant, nodeCount, edgeCount, duration, success);
}
}
private sealed class CaptureSnapshotExporter : ISbomSnapshotExporter
{
public SbomSnapshot? LastSnapshot { get; private set; }
public GraphBuildBatch? LastBatch { get; private set; }
public Task ExportAsync(SbomSnapshot snapshot, GraphBuildBatch batch, CancellationToken cancellationToken)
{
LastSnapshot = snapshot;
LastBatch = batch;
return Task.CompletedTask;
}
}
private sealed record MetricRecord(
string Source,
string Tenant,
int NodeCount,
int EdgeCount,
TimeSpan Duration,
bool Success);
}

View File

@@ -1,125 +0,0 @@
using System;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using StellaOps.Graph.Indexer.Ingestion.Sbom;
using Xunit;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class SbomIngestServiceCollectionExtensionsTests : IDisposable
{
private static readonly string FixturesRoot =
Path.Combine(AppContext.BaseDirectory, "Fixtures", "v1");
private readonly string _tempDirectory;
public SbomIngestServiceCollectionExtensionsTests()
{
_tempDirectory = Path.Combine(Path.GetTempPath(), $"graph-indexer-{Guid.NewGuid():N}");
Directory.CreateDirectory(_tempDirectory);
}
[Fact]
public async Task AddSbomIngestPipeline_exports_snapshots_to_configured_directory()
{
var services = new ServiceCollection();
services.AddSingleton<IGraphDocumentWriter, CaptureWriter>();
services.AddSbomIngestPipeline(options => options.SnapshotRootDirectory = _tempDirectory);
using var provider = services.BuildServiceProvider();
var processor = provider.GetRequiredService<SbomIngestProcessor>();
var snapshot = LoadSnapshot();
await processor.ProcessAsync(snapshot, CancellationToken.None);
AssertSnapshotOutputs(_tempDirectory);
var writer = provider.GetRequiredService<IGraphDocumentWriter>() as CaptureWriter;
writer!.LastBatch.Should().NotBeNull();
}
[Fact]
public async Task AddSbomIngestPipeline_uses_environment_variable_when_not_configured()
{
var previous = Environment.GetEnvironmentVariable("STELLAOPS_GRAPH_SNAPSHOT_DIR");
try
{
Environment.SetEnvironmentVariable("STELLAOPS_GRAPH_SNAPSHOT_DIR", _tempDirectory);
var services = new ServiceCollection();
services.AddSingleton<IGraphDocumentWriter, CaptureWriter>();
services.AddSbomIngestPipeline();
using var provider = services.BuildServiceProvider();
var processor = provider.GetRequiredService<SbomIngestProcessor>();
var snapshot = LoadSnapshot();
await processor.ProcessAsync(snapshot, CancellationToken.None);
AssertSnapshotOutputs(_tempDirectory);
}
finally
{
Environment.SetEnvironmentVariable("STELLAOPS_GRAPH_SNAPSHOT_DIR", previous);
}
}
private static SbomSnapshot LoadSnapshot()
{
var path = Path.Combine(FixturesRoot, "sbom-snapshot.json");
var json = File.ReadAllText(path);
return JsonSerializer.Deserialize<SbomSnapshot>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
})!;
}
private static void AssertSnapshotOutputs(string root)
{
var manifestPath = Path.Combine(root, "manifest.json");
var adjacencyPath = Path.Combine(root, "adjacency.json");
var nodesPath = Path.Combine(root, "nodes.jsonl");
var edgesPath = Path.Combine(root, "edges.jsonl");
File.Exists(manifestPath).Should().BeTrue("manifest should be exported");
File.Exists(adjacencyPath).Should().BeTrue("adjacency manifest should be exported");
File.Exists(nodesPath).Should().BeTrue("node stream should be exported");
File.Exists(edgesPath).Should().BeTrue("edge stream should be exported");
new FileInfo(manifestPath).Length.Should().BeGreaterThan(0);
new FileInfo(adjacencyPath).Length.Should().BeGreaterThan(0);
new FileInfo(nodesPath).Length.Should().BeGreaterThan(0);
new FileInfo(edgesPath).Length.Should().BeGreaterThan(0);
}
public void Dispose()
{
try
{
if (Directory.Exists(_tempDirectory))
{
Directory.Delete(_tempDirectory, recursive: true);
}
}
catch
{
// Ignore cleanup failures in CI environments.
}
}
private sealed class CaptureWriter : IGraphDocumentWriter
{
public GraphBuildBatch? LastBatch { get; private set; }
public Task WriteAsync(GraphBuildBatch batch, CancellationToken cancellationToken)
{
LastBatch = batch;
return Task.CompletedTask;
}
}
}

View File

@@ -1,283 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using FluentAssertions;
using StellaOps.Graph.Indexer.Ingestion.Sbom;
using Xunit;
using Xunit.Abstractions;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class SbomIngestTransformerTests
{
private readonly ITestOutputHelper _output;
public SbomIngestTransformerTests(ITestOutputHelper output)
{
_output = output;
}
private static readonly string FixturesRoot =
Path.Combine(AppContext.BaseDirectory, "Fixtures", "v1");
private static readonly HashSet<string> ExpectedNodeKinds = new(StringComparer.Ordinal)
{
"artifact",
"component",
"file"
};
private static readonly HashSet<string> ExpectedEdgeKinds = new(StringComparer.Ordinal)
{
"CONTAINS",
"DEPENDS_ON",
"DECLARED_IN",
"BUILT_FROM"
};
[Fact]
public void Transform_produces_expected_nodes_and_edges()
{
var snapshot = LoadSnapshot("sbom-snapshot.json");
var transformer = new SbomIngestTransformer();
var batch = transformer.Transform(snapshot);
var expectedNodes = LoadArray("nodes.json")
.Cast<JsonObject>()
.Where(node => ExpectedNodeKinds.Contains(node["kind"]!.GetValue<string>()))
.OrderBy(node => node["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var expectedEdges = LoadArray("edges.json")
.Cast<JsonObject>()
.Where(edge => ExpectedEdgeKinds.Contains(edge["kind"]!.GetValue<string>()))
.OrderBy(edge => edge["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var actualNodes = batch.Nodes
.Where(node => ExpectedNodeKinds.Contains(node["kind"]!.GetValue<string>()))
.OrderBy(node => node["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var actualEdges = batch.Edges
.Where(edge => ExpectedEdgeKinds.Contains(edge["kind"]!.GetValue<string>()))
.OrderBy(edge => edge["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
actualNodes.Length.Should().Be(expectedNodes.Length);
actualEdges.Length.Should().Be(expectedEdges.Length);
for (var i = 0; i < expectedNodes.Length; i++)
{
if (!JsonNode.DeepEquals(expectedNodes[i], actualNodes[i]))
{
_output.WriteLine($"Expected Node: {expectedNodes[i]}");
_output.WriteLine($"Actual Node: {actualNodes[i]}");
}
JsonNode.DeepEquals(expectedNodes[i], actualNodes[i]).Should().BeTrue();
}
for (var i = 0; i < expectedEdges.Length; i++)
{
if (!JsonNode.DeepEquals(expectedEdges[i], actualEdges[i]))
{
_output.WriteLine($"Expected Edge: {expectedEdges[i]}");
_output.WriteLine($"Actual Edge: {actualEdges[i]}");
}
JsonNode.DeepEquals(expectedEdges[i], actualEdges[i]).Should().BeTrue();
}
}
[Fact]
public void Transform_deduplicates_license_nodes_case_insensitive()
{
var baseCollectedAt = DateTimeOffset.Parse("2025-10-30T12:00:00Z");
var components = new[]
{
CreateComponent(
purl: "pkg:nuget/Example.Primary@1.0.0",
spdx: "MIT",
sourceDigest: "sha256:license001",
collectedAt: baseCollectedAt.AddSeconds(1),
eventOffset: 1201,
source: "scanner.component.v1"),
CreateComponent(
purl: "pkg:nuget/Example.Secondary@2.0.0",
spdx: "mit",
sourceDigest: "SHA256:LICENSE001",
collectedAt: baseCollectedAt.AddSeconds(2),
eventOffset: 1202,
usage: "transitive",
source: "scanner.component.v1")
};
var snapshot = CreateSnapshot(components: components);
var transformer = new SbomIngestTransformer();
var batch = transformer.Transform(snapshot);
var licenseNodes = batch.Nodes
.Where(node => string.Equals(node["kind"]!.GetValue<string>(), "license", StringComparison.Ordinal))
.ToArray();
licenseNodes.Should().HaveCount(1);
var canonicalKey = licenseNodes[0]["canonical_key"]!.AsObject();
canonicalKey["license_spdx"]!.GetValue<string>().Should().Be("MIT");
canonicalKey["source_digest"]!.GetValue<string>().Should().Be("sha256:license001");
}
[Fact]
public void Transform_emits_built_from_edge_with_provenance()
{
var snapshot = LoadSnapshot("sbom-snapshot.json");
var transformer = new SbomIngestTransformer();
var batch = transformer.Transform(snapshot);
var builtFrom = batch.Edges.Single(edge => edge["kind"]!.GetValue<string>() == "BUILT_FROM");
var attributes = builtFrom["attributes"]!.AsObject();
attributes["build_type"]!.GetValue<string>().Should().Be(snapshot.Build.BuildType);
attributes["builder_id"]!.GetValue<string>().Should().Be(snapshot.Build.BuilderId);
attributes["attestation_digest"]!.GetValue<string>().Should().Be(snapshot.Build.AttestationDigest);
var provenance = builtFrom["provenance"]!.AsObject();
provenance["source"]!.GetValue<string>().Should().Be(snapshot.Build.Source);
provenance["collected_at"]!.GetValue<string>()
.Should().Be(snapshot.Build.CollectedAt.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ"));
var canonicalKey = builtFrom["canonical_key"]!.AsObject();
canonicalKey.ContainsKey("parent_artifact_node_id").Should().BeTrue();
canonicalKey.ContainsKey("child_artifact_digest").Should().BeTrue();
}
[Fact]
public void Transform_normalizes_valid_from_to_utc()
{
var componentCollectedAt = new DateTimeOffset(2025, 11, 1, 15, 30, 45, TimeSpan.FromHours(2));
var components = new[]
{
CreateComponent(
purl: "pkg:nuget/Example.Primary@1.0.0",
spdx: "Apache-2.0",
sourceDigest: "sha256:license002",
collectedAt: componentCollectedAt,
eventOffset: 2101,
source: "scanner.component.v1")
};
var snapshot = CreateSnapshot(
components: components,
collectedAt: componentCollectedAt.AddSeconds(-1),
eventOffset: 2000);
var transformer = new SbomIngestTransformer();
var batch = transformer.Transform(snapshot);
var componentNode = batch.Nodes.Single(node => node["kind"]!.GetValue<string>() == "component");
componentNode["valid_from"]!.GetValue<string>().Should().Be("2025-11-01T13:30:45Z");
var containsEdge = batch.Edges.Single(edge => edge["kind"]!.GetValue<string>() == "CONTAINS");
containsEdge["valid_from"]!.GetValue<string>().Should().Be("2025-11-01T13:30:46Z");
}
private static SbomSnapshot CreateSnapshot(
IEnumerable<SbomComponent>? components = null,
IEnumerable<SbomBaseArtifact>? baseArtifacts = null,
DateTimeOffset? collectedAt = null,
long eventOffset = 1000,
string? source = null,
SbomArtifactMetadata? artifact = null,
SbomBuildMetadata? build = null)
{
return new SbomSnapshot
{
Tenant = "tenant-alpha",
Source = source ?? "scanner.sbom.v1",
ArtifactDigest = "sha256:test-artifact",
SbomDigest = "sha256:test-sbom",
CollectedAt = collectedAt ?? DateTimeOffset.Parse("2025-10-30T12:00:00Z"),
EventOffset = eventOffset,
Artifact = artifact ?? new SbomArtifactMetadata
{
DisplayName = "registry.example.com/app:latest",
Environment = "prod",
Labels = new[] { "critical" },
OriginRegistry = "registry.example.com",
SupplyChainStage = "deploy"
},
Build = build ?? new SbomBuildMetadata
{
BuilderId = "builder://tekton/default",
BuildType = "https://slsa.dev/provenance/v1",
AttestationDigest = "sha256:attestation",
Source = "scanner.build.v1",
CollectedAt = (collectedAt ?? DateTimeOffset.Parse("2025-10-30T12:00:00Z")).AddSeconds(5),
EventOffset = eventOffset + 100
},
Components = (components ?? Array.Empty<SbomComponent>()).ToArray(),
BaseArtifacts = (baseArtifacts ?? Array.Empty<SbomBaseArtifact>()).ToArray()
};
}
private static SbomComponent CreateComponent(
string purl,
string spdx,
string sourceDigest,
DateTimeOffset collectedAt,
long eventOffset,
string version = "1.0.0",
string usage = "direct",
string? source = null,
string detectedBy = "sbom.analyzer.transformer",
string scope = "runtime",
IEnumerable<SbomComponentFile>? files = null,
IEnumerable<SbomDependency>? dependencies = null)
{
return new SbomComponent
{
Purl = purl,
Version = version,
Ecosystem = "nuget",
Scope = scope,
License = new SbomLicense
{
Spdx = spdx,
Name = $"{spdx} License",
Classification = "permissive",
SourceDigest = sourceDigest,
NoticeUri = null
},
Usage = usage,
DetectedBy = detectedBy,
LayerDigest = "sha256:layer",
EvidenceDigest = "sha256:evidence",
CollectedAt = collectedAt,
EventOffset = eventOffset,
Source = source ?? "scanner.component.v1",
Files = (files ?? Array.Empty<SbomComponentFile>()).ToArray(),
Dependencies = (dependencies ?? Array.Empty<SbomDependency>()).ToArray(),
SourceType = "inventory"
};
}
private static SbomSnapshot LoadSnapshot(string fileName)
{
var path = Path.Combine(FixturesRoot, fileName);
var json = File.ReadAllText(path);
return JsonSerializer.Deserialize<SbomSnapshot>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
})!;
}
private static JsonArray LoadArray(string fileName)
{
var path = Path.Combine(FixturesRoot, fileName);
return (JsonArray)JsonNode.Parse(File.ReadAllText(path))!;
}
}

View File

@@ -1,125 +0,0 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using StellaOps.Graph.Indexer.Documents;
using StellaOps.Graph.Indexer.Ingestion.Advisory;
using StellaOps.Graph.Indexer.Ingestion.Policy;
using StellaOps.Graph.Indexer.Ingestion.Sbom;
using StellaOps.Graph.Indexer.Ingestion.Vex;
using Xunit;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class SbomSnapshotExporterTests
{
private static readonly string FixturesRoot =
Path.Combine(AppContext.BaseDirectory, "Fixtures", "v1");
[Fact]
public async Task ExportAsync_writes_manifest_adjacency_nodes_and_edges()
{
var sbomSnapshot = Load<SbomSnapshot>("sbom-snapshot.json");
var linksetSnapshot = Load<AdvisoryLinksetSnapshot>("concelier-linkset.json");
var vexSnapshot = Load<VexOverlaySnapshot>("excititor-vex.json");
var policySnapshot = Load<PolicyOverlaySnapshot>("policy-overlay.json");
var sbomBatch = new SbomIngestTransformer().Transform(sbomSnapshot);
var advisoryBatch = new AdvisoryLinksetTransformer().Transform(linksetSnapshot);
var vexBatch = new VexOverlayTransformer().Transform(vexSnapshot);
var policyBatch = new PolicyOverlayTransformer().Transform(policySnapshot);
var combinedBatch = MergeBatches(sbomBatch, advisoryBatch, vexBatch, policyBatch);
var builder = new GraphSnapshotBuilder();
var writer = new InMemorySnapshotFileWriter();
var exporter = new SbomSnapshotExporter(builder, writer);
await exporter.ExportAsync(sbomSnapshot, combinedBatch, CancellationToken.None);
writer.JsonFiles.Should().ContainKey("manifest.json");
writer.JsonFiles.Should().ContainKey("adjacency.json");
writer.JsonLinesFiles.Should().ContainKey("nodes.jsonl");
writer.JsonLinesFiles.Should().ContainKey("edges.jsonl");
var manifest = writer.JsonFiles["manifest.json"];
manifest["tenant"]!.GetValue<string>().Should().Be("tenant-alpha");
manifest["node_count"]!.GetValue<int>().Should().Be(combinedBatch.Nodes.Length);
manifest["edge_count"]!.GetValue<int>().Should().Be(combinedBatch.Edges.Length);
manifest["hash"]!.GetValue<string>().Should().NotBeNullOrEmpty();
var adjacency = writer.JsonFiles["adjacency.json"];
adjacency["tenant"]!.GetValue<string>().Should().Be("tenant-alpha");
adjacency["nodes"]!.AsArray().Should().HaveCount(combinedBatch.Nodes.Length);
writer.JsonLinesFiles["nodes.jsonl"].Should().HaveCount(combinedBatch.Nodes.Length);
writer.JsonLinesFiles["edges.jsonl"].Should().HaveCount(combinedBatch.Edges.Length);
}
private static GraphBuildBatch MergeBatches(params GraphBuildBatch[] batches)
{
var nodes = new Dictionary<string, JsonObject>(StringComparer.Ordinal);
var edges = new Dictionary<string, JsonObject>(StringComparer.Ordinal);
foreach (var batch in batches)
{
foreach (var node in batch.Nodes)
{
nodes[node["id"]!.GetValue<string>()] = node;
}
foreach (var edge in batch.Edges)
{
edges[edge["id"]!.GetValue<string>()] = edge;
}
}
var orderedNodes = nodes.Values
.OrderBy(node => node["kind"]!.GetValue<string>(), StringComparer.Ordinal)
.ThenBy(node => node["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToImmutableArray();
var orderedEdges = edges.Values
.OrderBy(edge => edge["kind"]!.GetValue<string>(), StringComparer.Ordinal)
.ThenBy(edge => edge["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToImmutableArray();
return new GraphBuildBatch(orderedNodes, orderedEdges);
}
private static T Load<T>(string fixtureFile)
{
var path = Path.Combine(FixturesRoot, fixtureFile);
var json = File.ReadAllText(path);
return JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
})!;
}
private sealed class InMemorySnapshotFileWriter : ISnapshotFileWriter
{
public Dictionary<string, JsonObject> JsonFiles { get; } = new(StringComparer.Ordinal);
public Dictionary<string, List<JsonObject>> JsonLinesFiles { get; } = new(StringComparer.Ordinal);
public Task WriteJsonAsync(string relativePath, JsonObject content, CancellationToken cancellationToken)
{
JsonFiles[relativePath] = (JsonObject)content.DeepClone();
return Task.CompletedTask;
}
public Task WriteJsonLinesAsync(string relativePath, IEnumerable<JsonObject> items, CancellationToken cancellationToken)
{
JsonLinesFiles[relativePath] = items
.Select(item => (JsonObject)item.DeepClone())
.ToList();
return Task.CompletedTask;
}
}
}

View File

@@ -1,25 +0,0 @@
<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="..\\..\\..\\src\\Graph\\StellaOps.Graph.Indexer\\StellaOps.Graph.Indexer.csproj" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="xunit" Version="2.7.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="Fixtures\**\*.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -1,106 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using FluentAssertions;
using StellaOps.Graph.Indexer.Ingestion.Vex;
using Xunit;
using Xunit.Abstractions;
namespace StellaOps.Graph.Indexer.Tests;
public sealed class VexOverlayTransformerTests
{
private readonly ITestOutputHelper _output;
public VexOverlayTransformerTests(ITestOutputHelper output)
{
_output = output;
}
private static readonly string FixturesRoot =
Path.Combine(AppContext.BaseDirectory, "Fixtures", "v1");
private static readonly HashSet<string> ExpectedNodeKinds = new(StringComparer.Ordinal)
{
"vex_statement"
};
private static readonly HashSet<string> ExpectedEdgeKinds = new(StringComparer.Ordinal)
{
"VEX_EXEMPTS"
};
[Fact]
public void Transform_projects_vex_nodes_and_exempt_edges()
{
var snapshot = LoadSnapshot("excititor-vex.json");
var transformer = new VexOverlayTransformer();
var batch = transformer.Transform(snapshot);
var expectedNodes = LoadArray("nodes.json")
.Cast<JsonObject>()
.Where(node => ExpectedNodeKinds.Contains(node["kind"]!.GetValue<string>()))
.OrderBy(node => node["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var expectedEdges = LoadArray("edges.json")
.Cast<JsonObject>()
.Where(edge => ExpectedEdgeKinds.Contains(edge["kind"]!.GetValue<string>()))
.OrderBy(edge => edge["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var actualNodes = batch.Nodes
.Where(node => ExpectedNodeKinds.Contains(node["kind"]!.GetValue<string>()))
.OrderBy(node => node["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
var actualEdges = batch.Edges
.Where(edge => ExpectedEdgeKinds.Contains(edge["kind"]!.GetValue<string>()))
.OrderBy(edge => edge["id"]!.GetValue<string>(), StringComparer.Ordinal)
.ToArray();
actualNodes.Length.Should().Be(expectedNodes.Length);
actualEdges.Length.Should().Be(expectedEdges.Length);
for (var i = 0; i < expectedNodes.Length; i++)
{
if (!JsonNode.DeepEquals(expectedNodes[i], actualNodes[i]))
{
_output.WriteLine($"Expected Node: {expectedNodes[i]}");
_output.WriteLine($"Actual Node: {actualNodes[i]}");
}
JsonNode.DeepEquals(expectedNodes[i], actualNodes[i]).Should().BeTrue();
}
for (var i = 0; i < expectedEdges.Length; i++)
{
if (!JsonNode.DeepEquals(expectedEdges[i], actualEdges[i]))
{
_output.WriteLine($"Expected Edge: {expectedEdges[i]}");
_output.WriteLine($"Actual Edge: {actualEdges[i]}");
}
JsonNode.DeepEquals(expectedEdges[i], actualEdges[i]).Should().BeTrue();
}
}
private static VexOverlaySnapshot LoadSnapshot(string fileName)
{
var path = Path.Combine(FixturesRoot, fileName);
var json = File.ReadAllText(path);
return JsonSerializer.Deserialize<VexOverlaySnapshot>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
})!;
}
private static JsonArray LoadArray(string fileName)
{
var path = Path.Combine(FixturesRoot, fileName);
return (JsonArray)JsonNode.Parse(File.ReadAllText(path))!;
}
}

View File

@@ -1,51 +0,0 @@
{
"baseMetrics": {
"ac": "Low",
"at": "None",
"av": "Network",
"pr": "None",
"sa": "High",
"sc": "High",
"si": "High",
"ui": "None",
"va": "High",
"vc": "High",
"vi": "High"
},
"createdAt": "2025-12-03T00:00:00Z",
"createdBy": "policy-scorer@stella",
"environmentalMetrics": {
"ar": "Medium",
"cr": "High",
"ir": "Medium",
"mac": "Low",
"mat": "None",
"mav": "Network",
"mpr": "None",
"ms": "Unchanged",
"mui": "None",
"mva": "High",
"mvc": "High",
"mvi": "High"
},
"policyRef": {
"hash": "3c1dff9075a14da4c6ae4e8b1e2c9f7569af5f5e90e78c9a0a82f86ccb63d4f9",
"id": "cvss-policy-v1",
"version": "1.2.0"
},
"scores": {
"base": 9.8,
"environmental": 9.4,
"threat": 9.8
},
"supplementalMetrics": {
"safety": "Safe"
},
"tenantId": "tenant-acme",
"threatMetrics": {
"ad": "High",
"rs": "Unreported"
},
"vectorString": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H/AD:H/RS:X/CR:H/IR:M/AR:M/MAV:N/MAC:L/MAT:N/MPR:N/MUI:N/MVC:H/MVI:H/MVA:H/MS:U",
"vulnerabilityId": "CVE-2024-1234"
}

View File

@@ -1 +0,0 @@
bac7e113ad5a27a7fc013608ef3a3b90a3e4d98efbdedbc5953d2c29a3545fef

View File

@@ -1 +0,0 @@
AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+Pw==

View File

@@ -1,78 +0,0 @@
using System.Text;
using StellaOps.Provenance.Attestation;
using Xunit;
namespace StellaOps.Provenance.Attestation.Tests;
public sealed class PromotionAttestationBuilderTests
{
[Fact]
public async Task BuildAsync_SignsCanonicalPayloadAndAddsPredicateClaim()
{
var predicate = new PromotionPredicate(
ImageDigest: "sha256:deadbeef",
SbomDigest: "sha256:sbom",
VexDigest: "sha256:vex",
PromotionId: "promo-123",
RekorEntry: "rekor:entry",
Metadata: new Dictionary<string, string>
{
{ "z", "last" },
{ "a", "first" }
});
var signer = new RecordingSigner();
var attestation = await PromotionAttestationBuilder.BuildAsync(predicate, signer);
Assert.Equal(predicate, attestation.Predicate);
Assert.NotNull(attestation.Payload);
Assert.Equal(PromotionAttestationBuilder.ContentType, signer.LastRequest?.ContentType);
Assert.Equal(PromotionAttestationBuilder.PredicateType, signer.LastRequest?.Claims!["predicateType"]);
Assert.Equal(attestation.Payload, signer.LastRequest?.Payload);
Assert.Equal(attestation.Signature, signer.LastResult);
// verify canonical order is stable (metadata keys sorted, property names sorted)
var canonicalJson = Encoding.UTF8.GetString(attestation.Payload);
Assert.Equal(
"{\"ImageDigest\":\"sha256:deadbeef\",\"Metadata\":{\"a\":\"first\",\"z\":\"last\"},\"PromotionId\":\"promo-123\",\"RekorEntry\":\"rekor:entry\",\"SbomDigest\":\"sha256:sbom\",\"VexDigest\":\"sha256:vex\"}",
canonicalJson);
}
[Fact]
public async Task BuildAsync_MergesClaimsWithoutOverwritingPredicateType()
{
var predicate = new PromotionPredicate(
ImageDigest: "sha256:x",
SbomDigest: "sha256:y",
VexDigest: "sha256:z",
PromotionId: "p-1");
var signer = new RecordingSigner();
var customClaims = new Dictionary<string, string> { { "env", "stage" }, { "predicateType", "custom" } };
await PromotionAttestationBuilder.BuildAsync(predicate, signer, customClaims);
Assert.NotNull(signer.LastRequest);
Assert.Equal(PromotionAttestationBuilder.PredicateType, signer.LastRequest!.Claims!["predicateType"]);
Assert.Equal("stage", signer.LastRequest!.Claims!["env"]);
}
private sealed class RecordingSigner : ISigner
{
public SignRequest? LastRequest { get; private set; }
public SignResult? LastResult { get; private set; }
public Task<SignResult> SignAsync(SignRequest request, CancellationToken cancellationToken = default)
{
LastRequest = request;
LastResult = new SignResult(
Signature: Encoding.UTF8.GetBytes("sig"),
KeyId: "key-1",
SignedAt: DateTimeOffset.UtcNow,
Claims: request.Claims);
return Task.FromResult(LastResult);
}
}
}

View File

@@ -1,151 +0,0 @@
using System.Text;
using StellaOps.Provenance.Attestation;
using Xunit;
namespace StellaOps.Provenance.Attestation.Tests;
public sealed class SignersTests
{
[Fact]
public async Task HmacSigner_SignsAndAudits()
{
var key = new InMemoryKeyProvider("k1", Convert.FromHexString("0f0e0d0c0b0a09080706050403020100"));
var audit = new InMemoryAuditSink();
var time = new TestTimeProvider(new DateTimeOffset(2025, 11, 22, 12, 0, 0, TimeSpan.Zero));
var signer = new HmacSigner(key, audit, time);
var request = new SignRequest(Encoding.UTF8.GetBytes("payload"), "application/json",
Claims: new Dictionary<string, string> { { "sub", "builder" } });
var result = await signer.SignAsync(request);
Assert.Equal("k1", result.KeyId);
Assert.Equal(time.GetUtcNow(), result.SignedAt);
Assert.Equal(
Convert.FromHexString("b3ae92d9a593318d03d7c4b6dca9710c416f582e88cfc08196d8c2cdabb3c480"),
result.Signature);
Assert.Single(audit.Signed);
Assert.Empty(audit.Missing);
}
[Fact]
public async Task HmacSigner_EnforcesRequiredClaims()
{
var key = new InMemoryKeyProvider("k-claims", Encoding.UTF8.GetBytes("secret"));
var audit = new InMemoryAuditSink();
var signer = new HmacSigner(key, audit, new TestTimeProvider(DateTimeOffset.UtcNow));
var request = new SignRequest(Encoding.UTF8.GetBytes("payload"), "text/plain",
Claims: new Dictionary<string, string>(),
RequiredClaims: new[] { "sub" });
await Assert.ThrowsAsync<InvalidOperationException>(() => signer.SignAsync(request));
Assert.Contains(audit.Missing, x => x.keyId == "k-claims" && x.claim == "sub");
}
[Fact]
public async Task RotatingKeyProvider_LogsRotationWhenNewKeyBecomesActive()
{
var now = new DateTimeOffset(2025, 11, 22, 10, 0, 0, TimeSpan.Zero);
var time = new TestTimeProvider(now);
var audit = new InMemoryAuditSink();
var expiring = new InMemoryKeyProvider("old", new byte[] { 0x01 }, now.AddMinutes(5));
var longLived = new InMemoryKeyProvider("new", new byte[] { 0x02 }, now.AddHours(1));
var provider = new RotatingKeyProvider(new[] { expiring, longLived }, time, audit);
var signer = new HmacSigner(provider, audit, time);
await signer.SignAsync(new SignRequest(new byte[] { 0xAB }, "demo"));
Assert.Contains(audit.Rotations, r => r.previousKeyId == "old" && r.nextKeyId == "new");
Assert.Equal("new", provider.KeyId);
}
[Fact]
public async Task CosignSigner_UsesClientAndAudits()
{
var signatureBytes = Convert.FromBase64String(await File.ReadAllTextAsync(Path.Combine("Fixtures", "cosign.sig"))); // fixture is deterministic
var client = new FakeCosignClient(signatureBytes);
var audit = new InMemoryAuditSink();
var time = new TestTimeProvider(new DateTimeOffset(2025, 11, 22, 13, 0, 0, TimeSpan.Zero));
var signer = new CosignSigner("cosign://stella", client, audit, time);
var request = new SignRequest(Encoding.UTF8.GetBytes("subject"), "application/vnd.stella+json",
Claims: new Dictionary<string, string> { { "sub", "artifact" } },
RequiredClaims: new[] { "sub" });
var result = await signer.SignAsync(request);
Assert.Equal(signatureBytes, result.Signature);
Assert.Equal(time.GetUtcNow(), result.SignedAt);
Assert.Equal("cosign://stella", result.KeyId);
Assert.Single(audit.Signed);
Assert.Empty(audit.Missing);
var call = Assert.Single(client.Calls);
Assert.Equal("cosign://stella", call.keyRef);
Assert.Equal("application/vnd.stella+json", call.contentType);
Assert.Equal(request.Payload, call.payload);
}
[Fact]
public async Task KmsSigner_EnforcesRequiredClaims()
{
var signature = new byte[] { 0xCA, 0xFE, 0xBA, 0xBE };
var client = new FakeKmsClient(signature);
var audit = new InMemoryAuditSink();
var key = new InMemoryKeyProvider("kms-1", new byte[] { 0x00 }, DateTimeOffset.UtcNow.AddDays(1));
var signer = new KmsSigner(client, key, audit, new TestTimeProvider(DateTimeOffset.UtcNow));
var request = new SignRequest(Encoding.UTF8.GetBytes("body"), "application/json",
Claims: new Dictionary<string, string> { { "aud", "stella" } },
RequiredClaims: new[] { "sub" });
await Assert.ThrowsAsync<InvalidOperationException>(() => signer.SignAsync(request));
Assert.Contains(audit.Missing, x => x.keyId == "kms-1" && x.claim == "sub");
var validAudit = new InMemoryAuditSink();
var validSigner = new KmsSigner(client, key, validAudit, new TestTimeProvider(DateTimeOffset.UtcNow));
var validRequest = new SignRequest(Encoding.UTF8.GetBytes("body"), "application/json",
Claims: new Dictionary<string, string> { { "aud", "stella" }, { "sub", "actor" } },
RequiredClaims: new[] { "sub" });
var result = await validSigner.SignAsync(validRequest);
Assert.Equal(signature, result.Signature);
Assert.Equal("kms-1", result.KeyId);
Assert.Empty(validAudit.Missing);
}
private sealed class FakeCosignClient : ICosignClient
{
public List<(byte[] payload, string contentType, string keyRef)> Calls { get; } = new();
private readonly byte[] _signature;
public FakeCosignClient(byte[] signature)
{
_signature = signature ?? throw new ArgumentNullException(nameof(signature));
}
public Task<byte[]> SignAsync(byte[] payload, string contentType, string keyRef, CancellationToken cancellationToken)
{
Calls.Add((payload, contentType, keyRef));
return Task.FromResult(_signature);
}
}
private sealed class FakeKmsClient : IKmsClient
{
private readonly byte[] _signature;
public List<(byte[] payload, string contentType, string keyId)> Calls { get; } = new();
public FakeKmsClient(byte[] signature) => _signature = signature;
public Task<byte[]> SignAsync(byte[] payload, string contentType, string keyId, CancellationToken cancellationToken)
{
Calls.Add((payload, contentType, keyId));
return Task.FromResult(_signature);
}
}
}

View File

@@ -1,20 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../../src/Provenance/StellaOps.Provenance.Attestation/StellaOps.Provenance.Attestation.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="Fixtures/cosign.sig" CopyToOutputDirectory="Always" />
</ItemGroup>
</Project>

View File

@@ -1,16 +0,0 @@
using System;
namespace StellaOps.Provenance.Attestation.Tests;
internal sealed class TestTimeProvider : TimeProvider
{
private DateTimeOffset _now;
public TestTimeProvider(DateTimeOffset now) => _now = now;
public override DateTimeOffset GetUtcNow() => _now;
public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc;
public override long GetTimestamp() => 0L;
public void Advance(TimeSpan delta) => _now = _now.Add(delta);
}

View File

@@ -1,39 +0,0 @@
using System.Text;
using StellaOps.Provenance.Attestation;
using Xunit;
namespace StellaOps.Provenance.Attestation.Tests;
public sealed class ToolEntrypointTests
{
[Fact]
public async Task RunAsync_ReturnsInvalidOnMissingArgs()
{
var code = await ToolEntrypoint.RunAsync(Array.Empty<string>(), TextWriter.Null, new StringWriter(), new TestTimeProvider(DateTimeOffset.UtcNow));
Assert.Equal(1, code);
}
[Fact]
public async Task RunAsync_VerifiesValidSignature()
{
var payload = Encoding.UTF8.GetBytes("payload");
var key = Convert.ToHexString(Encoding.UTF8.GetBytes("secret"));
using var hmac = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes("secret"));
var sig = Convert.ToHexString(hmac.ComputeHash(payload));
var tmp = Path.GetTempFileName();
await File.WriteAllBytesAsync(tmp, payload);
var stdout = new StringWriter();
var code = await ToolEntrypoint.RunAsync(new[]
{
"--payload", tmp,
"--signature-hex", sig,
"--key-hex", key,
"--signed-at", "2025-11-22T00:00:00Z"
}, stdout, new StringWriter(), new TestTimeProvider(new DateTimeOffset(2025,11,22,0,0,0,TimeSpan.Zero)));
Assert.Equal(0, code);
Assert.Contains("\"valid\":true", stdout.ToString());
}
}

View File

@@ -1,73 +0,0 @@
using System.Text;
using StellaOps.Provenance.Attestation;
using Xunit;
namespace StellaOps.Provenance.Attestation.Tests;
public sealed class VerificationLibraryTests
{
[Fact]
public async Task HmacVerifier_FailsWhenKeyExpired()
{
var key = new InMemoryKeyProvider("k1", Encoding.UTF8.GetBytes("secret"), DateTimeOffset.UtcNow.AddMinutes(-1));
var verifier = new HmacVerifier(key, new TestTimeProvider(DateTimeOffset.UtcNow));
var request = new SignRequest(Encoding.UTF8.GetBytes("payload"), "ct");
var signer = new HmacSigner(key, timeProvider: new TestTimeProvider(DateTimeOffset.UtcNow.AddMinutes(-2)));
var signature = await signer.SignAsync(request);
var result = await verifier.VerifyAsync(request, signature);
Assert.False(result.IsValid);
Assert.Contains("time", result.Reason);
}
[Fact]
public async Task HmacVerifier_FailsWhenClockSkewTooLarge()
{
var now = new DateTimeOffset(2025, 11, 22, 12, 0, 0, TimeSpan.Zero);
var key = new InMemoryKeyProvider("k", Encoding.UTF8.GetBytes("secret"));
var signer = new HmacSigner(key, timeProvider: new TestTimeProvider(now.AddMinutes(10)));
var request = new SignRequest(Encoding.UTF8.GetBytes("payload"), "ct");
var sig = await signer.SignAsync(request);
var verifier = new HmacVerifier(key, new TestTimeProvider(now), TimeSpan.FromMinutes(5));
var result = await verifier.VerifyAsync(request, sig);
Assert.False(result.IsValid);
}
[Fact]
public void MerkleRootVerifier_DetectsMismatch()
{
var leaves = new[]
{
Encoding.UTF8.GetBytes("a"),
Encoding.UTF8.GetBytes("b"),
Encoding.UTF8.GetBytes("c")
};
var expected = Convert.FromHexString("00");
var result = MerkleRootVerifier.VerifyRoot(leaves, expected, new TestTimeProvider(DateTimeOffset.UtcNow));
Assert.False(result.IsValid);
Assert.Equal("merkle root mismatch", result.Reason);
}
[Fact]
public void ChainOfCustodyVerifier_ComputesAggregate()
{
var hops = new[]
{
Encoding.UTF8.GetBytes("hop1"),
Encoding.UTF8.GetBytes("hop2")
};
using var sha = System.Security.Cryptography.SHA256.Create();
var aggregate = sha.ComputeHash(Array.Empty<byte>().Concat(hops[0]).ToArray());
aggregate = sha.ComputeHash(aggregate.Concat(hops[1]).ToArray());
var result = ChainOfCustodyVerifier.Verify(hops, aggregate, new TestTimeProvider(DateTimeOffset.UtcNow));
Assert.True(result.IsValid);
}
}

View File

@@ -1,229 +0,0 @@
# StellaOps Test Infrastructure
This document describes the test infrastructure for StellaOps, including reachability corpus fixtures, benchmark automation, and CI integration.
## Reachability Test Fixtures
### Corpus Structure
The reachability corpus is located at `tests/reachability/` and contains:
```
tests/reachability/
├── corpus/
│ ├── manifest.json # SHA-256 hashes for all corpus files
│ ├── java/ # Java test cases
│ │ └── <case-id>/
│ │ ├── project/ # Source code
│ │ ├── callgraph.json # Expected call graph
│ │ └── ground-truth.json
│ ├── dotnet/ # .NET test cases
│ └── native/ # Native (C/C++/Rust) test cases
├── fixtures/
│ └── reachbench-2025-expanded/
│ ├── INDEX.json # Fixture index
│ └── cases/
│ └── <case-id>/
│ └── images/
│ ├── reachable/
│ │ └── reachgraph.truth.json
│ └── unreachable/
│ └── reachgraph.truth.json
└── StellaOps.Reachability.FixtureTests/
├── CorpusFixtureTests.cs
└── ReachbenchFixtureTests.cs
```
### Ground-Truth Schema
All ground-truth files follow the `reachbench.reachgraph.truth/v1` schema:
```json
{
"schema_version": "reachbench.reachgraph.truth/v1",
"case_id": "CVE-2023-38545",
"variant": "reachable",
"paths": [
{
"entry_point": "main",
"vulnerable_function": "curl_easy_perform",
"frames": ["main", "do_http_request", "curl_easy_perform"]
}
],
"metadata": {
"cve_id": "CVE-2023-38545",
"purl": "pkg:generic/curl@8.4.0"
}
}
```
### Running Fixture Tests
```bash
# Run all reachability fixture tests
dotnet test tests/reachability/StellaOps.Reachability.FixtureTests
# Run only corpus tests
dotnet test tests/reachability/StellaOps.Reachability.FixtureTests \
--filter "FullyQualifiedName~CorpusFixtureTests"
# Run only reachbench tests
dotnet test tests/reachability/StellaOps.Reachability.FixtureTests \
--filter "FullyQualifiedName~ReachbenchFixtureTests"
# Cross-platform runner scripts
./scripts/reachability/run_all.sh # Unix
./scripts/reachability/run_all.ps1 # Windows
```
### CI Integration
The reachability corpus is validated in CI via `.gitea/workflows/reachability-corpus-ci.yml`:
1. **validate-corpus**: Runs fixture tests, verifies SHA-256 hashes
2. **validate-ground-truths**: Validates schema version and structure
3. **determinism-check**: Ensures JSON files have sorted keys
Triggers:
- Push/PR to paths: `tests/reachability/**`, `scripts/reachability/**`
- Manual workflow dispatch
## CAS Layout Reference
### Content-Addressable Storage Paths
StellaOps uses BLAKE3 hashes for content-addressable storage:
| Artifact Type | CAS Path Pattern | Example |
|--------------|------------------|---------|
| Call Graph | `cas://reachability/graphs/{blake3}` | `cas://reachability/graphs/3a7f2b...` |
| Runtime Facts | `cas://reachability/runtime-facts/{blake3}` | `cas://reachability/runtime-facts/8c4d1e...` |
| Replay Manifest | `cas://reachability/replay/{blake3}` | `cas://reachability/replay/f2e9c8...` |
| Evidence Bundle | `cas://reachability/evidence/{blake3}` | `cas://reachability/evidence/a1b2c3...` |
| DSSE Envelope | `cas://attestation/dsse/{blake3}` | `cas://attestation/dsse/d4e5f6...` |
| Symbol Manifest | `cas://symbols/manifests/{blake3}` | `cas://symbols/manifests/7g8h9i...` |
### Hash Algorithm
All CAS URIs use BLAKE3 with base16 (hex) encoding:
```
cas://{namespace}/{artifact-type}/{blake3-hex}
```
Example hash computation:
```python
import hashlib
# Use BLAKE3 for CAS hashing
from blake3 import blake3
content_hash = blake3(file_content).hexdigest()
```
## Replay Workflow
### Replay Manifest v2 Schema
```json
{
"version": 2,
"hashAlg": "blake3",
"hash": "blake3:3a7f2b...",
"created_at": "2025-12-14T00:00:00Z",
"entries": [
{
"type": "callgraph",
"cas_uri": "cas://reachability/graphs/3a7f2b...",
"hash": "blake3:3a7f2b..."
},
{
"type": "runtime-facts",
"cas_uri": "cas://reachability/runtime-facts/8c4d1e...",
"hash": "blake3:8c4d1e..."
}
],
"code_id_coverage": 0.95
}
```
### Replay Steps
1. **Export replay manifest**:
```bash
stella replay export --scan-id <scan-id> --output replay-manifest.json
```
2. **Validate manifest integrity**:
```bash
stella replay validate --manifest replay-manifest.json
```
3. **Fetch CAS artifacts** (online):
```bash
stella replay fetch --manifest replay-manifest.json --output ./artifacts/
```
4. **Import for replay** (air-gapped):
```bash
stella replay import --bundle replay-bundle.tar.gz --verify
```
5. **Execute replay**:
```bash
stella replay run --manifest replay-manifest.json --compare-to <baseline-hash>
```
### Validation Error Codes
| Code | Description |
|------|-------------|
| `REPLAY_MANIFEST_MISSING_VERSION` | Manifest missing version field |
| `VERSION_MISMATCH` | Unexpected manifest version |
| `MISSING_HASH_ALG` | Hash algorithm not specified |
| `UNSORTED_ENTRIES` | CAS entries not sorted (non-deterministic) |
| `CAS_NOT_FOUND` | Referenced CAS artifact missing |
| `HASH_MISMATCH` | Computed hash differs from declared |
## Benchmark Automation
### Running Benchmarks
```bash
# Full benchmark pipeline
./scripts/bench/run-baseline.sh --all
# Individual steps
./scripts/bench/run-baseline.sh --populate # Generate findings from fixtures
./scripts/bench/run-baseline.sh --compute # Compute metrics
# Compare with baseline scanner
./scripts/bench/run-baseline.sh --compare baseline-results.json
```
### Benchmark Outputs
Results are written to `bench/results/`:
- `summary.csv`: Per-run metrics (TP, FP, TN, FN, precision, recall, F1)
- `metrics.json`: Detailed findings with evidence hashes
- `replay/`: Replay outputs for verification
### Verification Tools
```bash
# Online verification (DSSE + Rekor)
./bench/tools/verify.sh <finding-bundle>
# Offline verification
python3 bench/tools/verify.py --bundle <finding-dir> --offline
# Compare scanners
python3 bench/tools/compare.py --baseline <scanner-results> --json
```
## References
- [Function-Level Evidence Guide](../docs/reachability/function-level-evidence.md)
- [Reachability Runtime Runbook](../docs/runbooks/reachability-runtime.md)
- [Replay Manifest Specification](../docs/replay/DETERMINISTIC_REPLAY.md)
- [VEX Evidence Playbook](../docs/benchmarks/vex-evidence-playbook.md)
- [Ground-Truth Schema](../docs/reachability/ground-truth-schema.md)

View File

@@ -1,97 +0,0 @@
using System;
using FluentAssertions;
using StellaOps.Replay.Core;
using Xunit;
namespace StellaOps.Replay.Core.Tests;
public class PolicySimulationInputLockValidatorTests
{
private readonly PolicySimulationInputLock _lock = new()
{
PolicyBundleSha256 = new string('a', 64),
GraphSha256 = new string('b', 64),
SbomSha256 = new string('c', 64),
TimeAnchorSha256 = new string('d', 64),
DatasetSha256 = new string('e', 64),
GeneratedAt = DateTimeOffset.Parse("2025-12-02T00:00:00Z"),
ShadowIsolation = true,
RequiredScopes = new[] { "policy:simulate:shadow" }
};
[Fact]
public void Validate_passes_when_digests_match_and_shadow_scope_present()
{
var inputs = new PolicySimulationMaterializedInputs(
new string('a', 64),
new string('b', 64),
new string('c', 64),
new string('d', 64),
new string('e', 64),
"shadow",
new[] { "policy:simulate:shadow", "graph:read" },
DateTimeOffset.Parse("2025-12-02T01:00:00Z"));
var result = PolicySimulationInputLockValidator.Validate(_lock, inputs, TimeSpan.FromDays(2));
result.IsValid.Should().BeTrue();
result.Reason.Should().Be("ok");
}
[Fact]
public void Validate_detects_digest_drift()
{
var inputs = new PolicySimulationMaterializedInputs(
new string('0', 64),
new string('b', 64),
new string('c', 64),
new string('d', 64),
new string('e', 64),
"shadow",
new[] { "policy:simulate:shadow" },
DateTimeOffset.Parse("2025-12-02T00:10:00Z"));
var result = PolicySimulationInputLockValidator.Validate(_lock, inputs, TimeSpan.FromDays(1));
result.IsValid.Should().BeFalse();
result.Reason.Should().Be("policy-bundle-drift");
}
[Fact]
public void Validate_requires_shadow_mode_when_flagged()
{
var inputs = new PolicySimulationMaterializedInputs(
new string('a', 64),
new string('b', 64),
new string('c', 64),
new string('d', 64),
new string('e', 64),
"live",
Array.Empty<string>(),
DateTimeOffset.Parse("2025-12-02T00:10:00Z"));
var result = PolicySimulationInputLockValidator.Validate(_lock, inputs, TimeSpan.FromDays(1));
result.IsValid.Should().BeFalse();
result.Reason.Should().Be("shadow-mode-required");
}
[Fact]
public void Validate_fails_when_lock_stale()
{
var inputs = new PolicySimulationMaterializedInputs(
new string('a', 64),
new string('b', 64),
new string('c', 64),
new string('d', 64),
new string('e', 64),
"shadow",
new[] { "policy:simulate:shadow" },
DateTimeOffset.Parse("2025-12-05T00:00:00Z"));
var result = PolicySimulationInputLockValidator.Validate(_lock, inputs, TimeSpan.FromDays(1));
result.IsValid.Should().BeFalse();
result.Reason.Should().Be("inputs-lock-stale");
}
}

View File

@@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../../src/__Libraries/StellaOps.Replay.Core/StellaOps.Replay.Core.csproj" />
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.0" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
</ItemGroup>
</Project>

Some files were not shown because too many files have changed in this diff Show More