This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<OutputType>Library</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
<UseAppHost>false</UseAppHost>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../__Libraries/StellaOps.Excititor.Core/StellaOps.Excititor.Core.csproj" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.12.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" PrivateAssets="all" />
|
||||
<ProjectReference Include="../../__Libraries/StellaOps.Excititor.Storage.Mongo/StellaOps.Excititor.Storage.Mongo.csproj" />
|
||||
<ProjectReference Include="../../StellaOps.Excititor.WebService/StellaOps.Excititor.WebService.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,118 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.WebService.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.Core.UnitTests;
|
||||
|
||||
public sealed class VexEvidenceChunkServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task QueryAsync_FiltersAndLimitsResults()
|
||||
{
|
||||
var now = new DateTimeOffset(2025, 11, 16, 12, 0, 0, TimeSpan.Zero);
|
||||
var claims = new[]
|
||||
{
|
||||
CreateClaim("provider-a", VexClaimStatus.Affected, now.AddHours(-6), now.AddHours(-5), score: 0.9),
|
||||
CreateClaim("provider-b", VexClaimStatus.NotAffected, now.AddHours(-4), now.AddHours(-3), score: 0.2)
|
||||
};
|
||||
|
||||
var service = new VexEvidenceChunkService(new FakeClaimStore(claims), new FixedTimeProvider(now));
|
||||
var request = new VexEvidenceChunkRequest(
|
||||
Tenant: "tenant-a",
|
||||
VulnerabilityId: "CVE-2025-0001",
|
||||
ProductKey: "pkg:docker/demo",
|
||||
ProviderIds: ImmutableHashSet.Create("provider-b"),
|
||||
Statuses: ImmutableHashSet.Create(VexClaimStatus.NotAffected),
|
||||
Since: now.AddHours(-12),
|
||||
Limit: 1);
|
||||
|
||||
var result = await service.QueryAsync(request, CancellationToken.None);
|
||||
|
||||
result.Truncated.Should().BeFalse();
|
||||
result.TotalCount.Should().Be(1);
|
||||
result.GeneratedAtUtc.Should().Be(now);
|
||||
var chunk = result.Chunks.Single();
|
||||
chunk.ProviderId.Should().Be("provider-b");
|
||||
chunk.Status.Should().Be(VexClaimStatus.NotAffected.ToString());
|
||||
chunk.ScopeScore.Should().Be(0.2);
|
||||
chunk.ObservationId.Should().Contain("provider-b");
|
||||
chunk.Document.Digest.Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
private static VexClaim CreateClaim(string providerId, VexClaimStatus status, DateTimeOffset firstSeen, DateTimeOffset lastSeen, double? score)
|
||||
{
|
||||
var product = new VexProduct("pkg:docker/demo", "demo", "1.0.0", "pkg:docker/demo:1.0.0", null, new[] { "component-a" });
|
||||
var document = new VexClaimDocument(
|
||||
VexDocumentFormat.CycloneDx,
|
||||
digest: Guid.NewGuid().ToString("N"),
|
||||
sourceUri: new Uri("https://example.test/vex.json"),
|
||||
revision: "r1",
|
||||
signature: new VexSignatureMetadata("cosign", "demo", "issuer", keyId: "kid", verifiedAt: firstSeen, transparencyLogReference: string.Empty));
|
||||
|
||||
var signals = score.HasValue
|
||||
? new VexSignalSnapshot(new VexSeveritySignal("cvss", score, "low", vector: null), kev: false, epss: null)
|
||||
: null;
|
||||
|
||||
return new VexClaim(
|
||||
"CVE-2025-0001",
|
||||
providerId,
|
||||
product,
|
||||
status,
|
||||
document,
|
||||
firstSeen,
|
||||
lastSeen,
|
||||
justification: VexJustification.ComponentNotPresent,
|
||||
detail: "demo detail",
|
||||
confidence: null,
|
||||
signals: signals,
|
||||
additionalMetadata: ImmutableDictionary<string, string>.Empty);
|
||||
}
|
||||
|
||||
private sealed class FakeClaimStore : IVexClaimStore
|
||||
{
|
||||
private readonly IReadOnlyCollection<VexClaim> _claims;
|
||||
|
||||
public FakeClaimStore(IReadOnlyCollection<VexClaim> claims)
|
||||
{
|
||||
_claims = claims;
|
||||
}
|
||||
|
||||
public ValueTask AppendAsync(IEnumerable<VexClaim> claims, DateTimeOffset observedAt, CancellationToken cancellationToken, IClientSessionHandle? session = null)
|
||||
=> throw new NotSupportedException();
|
||||
|
||||
public ValueTask<IReadOnlyCollection<VexClaim>> FindAsync(string vulnerabilityId, string productKey, DateTimeOffset? since, CancellationToken cancellationToken, IClientSessionHandle? session = null)
|
||||
{
|
||||
var query = _claims
|
||||
.Where(claim => claim.VulnerabilityId == vulnerabilityId)
|
||||
.Where(claim => claim.Product.Key == productKey);
|
||||
|
||||
if (since.HasValue)
|
||||
{
|
||||
query = query.Where(claim => claim.LastSeen >= since.Value);
|
||||
}
|
||||
|
||||
return ValueTask.FromResult<IReadOnlyCollection<VexClaim>>(query.ToList());
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FixedTimeProvider : TimeProvider
|
||||
{
|
||||
private readonly DateTimeOffset _timestamp;
|
||||
|
||||
public FixedTimeProvider(DateTimeOffset timestamp)
|
||||
{
|
||||
_timestamp = timestamp;
|
||||
}
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => _timestamp;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Text.Json.Nodes;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.Core.UnitTests;
|
||||
|
||||
public class VexLinksetExtractionServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public void Extract_GroupsByVulnerabilityAndProduct_WithStableOrdering()
|
||||
{
|
||||
var obs1 = BuildObservation(
|
||||
id: "obs-1",
|
||||
provider: "provider-a",
|
||||
vuln: "CVE-2025-0001",
|
||||
product: "pkg:npm/leftpad",
|
||||
createdAt: DateTimeOffset.Parse("2025-11-20T10:00:00Z"));
|
||||
|
||||
var obs2 = BuildObservation(
|
||||
id: "obs-2",
|
||||
provider: "provider-b",
|
||||
vuln: "CVE-2025-0001",
|
||||
product: "pkg:npm/leftpad",
|
||||
createdAt: DateTimeOffset.Parse("2025-11-20T11:00:00Z"));
|
||||
|
||||
var obs3 = BuildObservation(
|
||||
id: "obs-3",
|
||||
provider: "provider-c",
|
||||
vuln: "CVE-2025-0002",
|
||||
product: "pkg:maven/org.example/app",
|
||||
createdAt: DateTimeOffset.Parse("2025-11-21T09:00:00Z"));
|
||||
|
||||
var service = new VexLinksetExtractionService();
|
||||
|
||||
var events = service.Extract("tenant-a", new[] { obs2, obs1, obs3 });
|
||||
|
||||
Assert.Equal(2, events.Length);
|
||||
|
||||
// First event should be CVE-2025-0001 because of ordering (vuln then product)
|
||||
var first = events[0];
|
||||
Assert.Equal("tenant-a", first.Tenant);
|
||||
Assert.Equal("cve-2025-0001", first.VulnerabilityId.ToLowerInvariant());
|
||||
Assert.Equal("pkg:npm/leftpad", first.ProductKey);
|
||||
Assert.Equal("vex:cve-2025-0001:pkg:npm/leftpad", first.LinksetId);
|
||||
// Should contain both observations, ordered by provider then observationId
|
||||
Assert.Equal(new[] { "obs-1", "obs-2" }, first.Observations.Select(o => o.ObservationId).ToArray());
|
||||
|
||||
// Second event corresponds to CVE-2025-0002
|
||||
var second = events[1];
|
||||
Assert.Equal("cve-2025-0002", second.VulnerabilityId.ToLowerInvariant());
|
||||
Assert.Equal("pkg:maven/org.example/app", second.ProductKey);
|
||||
Assert.Equal(new[] { "obs-3" }, second.Observations.Select(o => o.ObservationId).ToArray());
|
||||
// CreatedAt should reflect max CreatedAt among grouped observations
|
||||
Assert.Equal(DateTimeOffset.Parse("2025-11-21T09:00:00Z").ToUniversalTime(), second.CreatedAtUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Extract_FiltersNullsAndReturnsEmptyWhenNoObservations()
|
||||
{
|
||||
var service = new VexLinksetExtractionService();
|
||||
var events = service.Extract("tenant-a", Array.Empty<VexObservation>());
|
||||
Assert.Empty(events);
|
||||
}
|
||||
|
||||
private static VexObservation BuildObservation(string id, string provider, string vuln, string product, DateTimeOffset createdAt)
|
||||
{
|
||||
var statement = new VexObservationStatement(
|
||||
vulnerabilityId: vuln,
|
||||
productKey: product,
|
||||
status: VexClaimStatus.Affected,
|
||||
lastObserved: null,
|
||||
locator: null,
|
||||
justification: null,
|
||||
introducedVersion: null,
|
||||
fixedVersion: null,
|
||||
purl: product,
|
||||
cpe: null,
|
||||
evidence: null,
|
||||
metadata: null);
|
||||
|
||||
var upstream = new VexObservationUpstream(
|
||||
upstreamId: $"upstream-{id}",
|
||||
documentVersion: "1",
|
||||
fetchedAt: createdAt,
|
||||
receivedAt: createdAt,
|
||||
contentHash: "sha256:deadbeef",
|
||||
signature: new VexObservationSignature(false, null, null, null));
|
||||
|
||||
var content = new VexObservationContent(
|
||||
format: "openvex",
|
||||
specVersion: "1.0.0",
|
||||
raw: JsonNode.Parse("{}")!,
|
||||
metadata: null);
|
||||
|
||||
var linkset = new VexObservationLinkset(
|
||||
aliases: new[] { vuln },
|
||||
purls: new[] { product },
|
||||
cpes: Array.Empty<string>(),
|
||||
references: Array.Empty<VexObservationReference>());
|
||||
|
||||
return new VexObservation(
|
||||
observationId: id,
|
||||
tenant: "tenant-a",
|
||||
providerId: provider,
|
||||
streamId: "ingest",
|
||||
upstream: upstream,
|
||||
statements: ImmutableArray.Create(statement),
|
||||
content: content,
|
||||
linkset: linkset,
|
||||
createdAt: createdAt);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using System;
|
||||
using StellaOps.Excititor.WebService.Contracts;
|
||||
using StellaOps.Excititor.WebService.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Tests;
|
||||
|
||||
public sealed class AirgapImportValidatorTests
|
||||
{
|
||||
private readonly AirgapImportValidator _validator = new();
|
||||
private readonly DateTimeOffset _now = DateTimeOffset.UtcNow;
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenValid_ReturnsEmpty()
|
||||
{
|
||||
var req = new AirgapImportRequest
|
||||
{
|
||||
BundleId = "bundle-123",
|
||||
MirrorGeneration = "5",
|
||||
Publisher = "stellaops",
|
||||
PayloadHash = "sha256:" + new string('a', 64),
|
||||
Signature = Convert.ToBase64String(new byte[]{1,2,3}),
|
||||
SignedAt = _now
|
||||
};
|
||||
|
||||
var result = _validator.Validate(req, _now);
|
||||
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_InvalidHash_ReturnsError()
|
||||
{
|
||||
var req = Valid();
|
||||
req.PayloadHash = "not-a-hash";
|
||||
|
||||
var result = _validator.Validate(req, _now);
|
||||
|
||||
Assert.Contains(result, e => e.Code == "payload_hash_invalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_InvalidSignature_ReturnsError()
|
||||
{
|
||||
var req = Valid();
|
||||
req.Signature = "???";
|
||||
|
||||
var result = _validator.Validate(req, _now);
|
||||
|
||||
Assert.Contains(result, e => e.Code == "AIRGAP_SIGNATURE_INVALID");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_MirrorGenerationNonNumeric_ReturnsError()
|
||||
{
|
||||
var req = Valid();
|
||||
req.MirrorGeneration = "abc";
|
||||
|
||||
var result = _validator.Validate(req, _now);
|
||||
|
||||
Assert.Contains(result, e => e.Code == "mirror_generation_invalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_SignedAtTooOld_ReturnsError()
|
||||
{
|
||||
var req = Valid();
|
||||
req.SignedAt = _now.AddSeconds(-10);
|
||||
|
||||
var result = _validator.Validate(req, _now);
|
||||
|
||||
Assert.Contains(result, e => e.Code == "AIRGAP_PAYLOAD_STALE");
|
||||
}
|
||||
|
||||
private AirgapImportRequest Valid() => new()
|
||||
{
|
||||
BundleId = "bundle-123",
|
||||
MirrorGeneration = "5",
|
||||
Publisher = "stellaops",
|
||||
PayloadHash = "sha256:" + new string('b', 64),
|
||||
Signature = Convert.ToBase64String(new byte[]{5,6,7}),
|
||||
SignedAt = _now
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using StellaOps.Excititor.Connectors.Abstractions.Trust;
|
||||
using StellaOps.Excititor.WebService.Contracts;
|
||||
using StellaOps.Excititor.WebService.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Tests;
|
||||
|
||||
public class AirgapSignerTrustServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public void Validate_Allows_When_Metadata_Not_Configured()
|
||||
{
|
||||
Environment.SetEnvironmentVariable("STELLAOPS_CONNECTOR_SIGNER_METADATA_PATH", null);
|
||||
var service = new AirgapSignerTrustService(NullLogger<AirgapSignerTrustService>.Instance);
|
||||
|
||||
var ok = service.Validate(ValidRequest(), out var code, out var msg);
|
||||
|
||||
Assert.True(ok);
|
||||
Assert.Null(code);
|
||||
Assert.Null(msg);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Rejects_When_Publisher_Not_In_Metadata()
|
||||
{
|
||||
using var temp = ConnectorMetadataTempFile();
|
||||
Environment.SetEnvironmentVariable("STELLAOPS_CONNECTOR_SIGNER_METADATA_PATH", temp.Path);
|
||||
var service = new AirgapSignerTrustService(NullLogger<AirgapSignerTrustService>.Instance);
|
||||
|
||||
var req = ValidRequest();
|
||||
req.Publisher = "missing";
|
||||
var ok = service.Validate(req, out var code, out var msg);
|
||||
|
||||
Assert.False(ok);
|
||||
Assert.Equal("AIRGAP_SOURCE_UNTRUSTED", code);
|
||||
Assert.Contains("missing", msg);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Rejects_On_Digest_Mismatch()
|
||||
{
|
||||
using var temp = ConnectorMetadataTempFile();
|
||||
Environment.SetEnvironmentVariable("STELLAOPS_CONNECTOR_SIGNER_METADATA_PATH", temp.Path);
|
||||
var service = new AirgapSignerTrustService(NullLogger<AirgapSignerTrustService>.Instance);
|
||||
|
||||
var req = ValidRequest();
|
||||
req.PayloadHash = "sha256:" + new string('b', 64);
|
||||
var ok = service.Validate(req, out var code, out var msg);
|
||||
|
||||
Assert.False(ok);
|
||||
Assert.Equal("AIRGAP_PAYLOAD_MISMATCH", code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Allows_On_Metadata_Match()
|
||||
{
|
||||
using var temp = ConnectorMetadataTempFile();
|
||||
Environment.SetEnvironmentVariable("STELLAOPS_CONNECTOR_SIGNER_METADATA_PATH", temp.Path);
|
||||
var service = new AirgapSignerTrustService(NullLogger<AirgapSignerTrustService>.Instance);
|
||||
|
||||
var req = ValidRequest();
|
||||
var ok = service.Validate(req, out var code, out var msg);
|
||||
|
||||
Assert.True(ok);
|
||||
Assert.Null(code);
|
||||
Assert.Null(msg);
|
||||
}
|
||||
|
||||
private static AirgapImportRequest ValidRequest() => new()
|
||||
{
|
||||
BundleId = "bundle-1",
|
||||
MirrorGeneration = "1",
|
||||
Publisher = "connector-a",
|
||||
PayloadHash = "sha256:" + new string('a', 64),
|
||||
Signature = Convert.ToBase64String(new byte[] {1,2,3}),
|
||||
SignedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
|
||||
private sealed class TempFile : IDisposable
|
||||
{
|
||||
public string Path { get; }
|
||||
public TempFile(string path) => Path = path;
|
||||
public void Dispose() { if (System.IO.File.Exists(Path)) System.IO.File.Delete(Path); }
|
||||
}
|
||||
|
||||
private static TempFile ConnectorMetadataTempFile()
|
||||
{
|
||||
var json = @"{
|
||||
\"schemaVersion\": \"1.0.0\",
|
||||
\"generatedAt\": \"2025-11-23T00:00:00Z\",
|
||||
\"connectors\": [
|
||||
{
|
||||
\"connectorId\": \"connector-a\",
|
||||
\"provider\": { \"name\": \"Connector A\", \"slug\": \"connector-a\" },
|
||||
\"issuerTier\": \"trusted\",
|
||||
\"signers\": [ { \"usage\": \"sign\", \"fingerprints\": [ { \"alg\": \"rsa\", \"format\": \"pem\", \"value\": \"fp1\" } ] } ],
|
||||
\"bundle\": { \"kind\": \"mirror\", \"uri\": \"file:///bundle\", \"digest\": \"sha256:" + new string('a',64) + "\" }
|
||||
}
|
||||
]
|
||||
}";
|
||||
var path = System.IO.Path.GetTempFileName();
|
||||
System.IO.File.WriteAllText(path, json);
|
||||
return new TempFile(path);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
#if false
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
@@ -10,26 +9,22 @@ using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Tests;
|
||||
|
||||
public sealed class AttestationVerifyEndpointTests : IClassFixture<TestWebApplicationFactory>
|
||||
public sealed class AttestationVerifyEndpointTests
|
||||
{
|
||||
private readonly TestWebApplicationFactory _factory;
|
||||
|
||||
public AttestationVerifyEndpointTests(TestWebApplicationFactory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_ReturnsOk_WhenPayloadValid()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
using var factory = new TestWebApplicationFactory(
|
||||
configureServices: services => TestServiceOverrides.Apply(services));
|
||||
var client = factory.CreateClient();
|
||||
|
||||
var request = new AttestationVerifyRequest
|
||||
{
|
||||
ExportId = "export-123",
|
||||
QuerySignature = "purl=foo",
|
||||
ArtifactDigest = "sha256:deadbeef",
|
||||
Format = "VexJson",
|
||||
ArtifactDigest = "deadbeef",
|
||||
Format = "json",
|
||||
CreatedAt = DateTimeOffset.Parse("2025-11-20T00:00:00Z"),
|
||||
SourceProviders = new[] { "ghsa" },
|
||||
Metadata = new Dictionary<string, string> { { "foo", "bar" } },
|
||||
@@ -50,8 +45,12 @@ public sealed class AttestationVerifyEndpointTests : IClassFixture<TestWebApplic
|
||||
};
|
||||
|
||||
var response = await client.PostAsJsonAsync("/v1/attestations/verify", request);
|
||||
var raw = await response.Content.ReadAsStringAsync();
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
if (response.StatusCode != HttpStatusCode.OK)
|
||||
{
|
||||
throw new Xunit.Sdk.XunitException($"Unexpected status {(int)response.StatusCode} ({response.StatusCode}). Body: {raw}");
|
||||
}
|
||||
var body = await response.Content.ReadFromJsonAsync<AttestationVerifyResponse>();
|
||||
body.Should().NotBeNull();
|
||||
body!.Valid.Should().BeTrue();
|
||||
@@ -60,7 +59,9 @@ public sealed class AttestationVerifyEndpointTests : IClassFixture<TestWebApplic
|
||||
[Fact]
|
||||
public async Task Verify_ReturnsBadRequest_WhenFieldsMissing()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
using var factory = new TestWebApplicationFactory(
|
||||
configureServices: services => TestServiceOverrides.Apply(services));
|
||||
var client = factory.CreateClient();
|
||||
|
||||
var request = new AttestationVerifyRequest
|
||||
{
|
||||
@@ -76,5 +77,3 @@ public sealed class AttestationVerifyEndpointTests : IClassFixture<TestWebApplic
|
||||
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// Stub to satisfy Razor dev runtime dependency when running tests without VS dev tools
|
||||
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
|
||||
{
|
||||
public interface IDevRuntimeEnvironment
|
||||
{
|
||||
bool IsSupported { get; }
|
||||
}
|
||||
|
||||
internal sealed class DefaultDevRuntimeEnvironment : IDevRuntimeEnvironment
|
||||
{
|
||||
public bool IsSupported => false;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
@@ -7,8 +6,11 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<UseConcelierTestInfra>false</UseConcelierTestInfra>
|
||||
<UseAppHost>false</UseAppHost>
|
||||
<DisableRazorRuntimeCompilation>true</DisableRazorRuntimeCompilation>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentAssertions" Version="6.12.0" />
|
||||
<PackageReference Include="EphemeralMongo" Version="3.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0-rc.2.25502.107" />
|
||||
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="9.10.0" />
|
||||
@@ -27,10 +29,11 @@
|
||||
<ItemGroup>
|
||||
<Compile Remove="**/*.cs" />
|
||||
<Compile Include="AirgapImportEndpointTests.cs" />
|
||||
<Compile Include="VexEvidenceChunkServiceTests.cs" />
|
||||
<Compile Include="EvidenceTelemetryTests.cs" />
|
||||
<Compile Include="DevRuntimeEnvironmentStub.cs" />
|
||||
<Compile Include="TestAuthentication.cs" />
|
||||
<Compile Include="TestServiceOverrides.cs" />
|
||||
<Compile Include="TestWebApplicationFactory.cs" />
|
||||
<Compile Include="AttestationVerifyEndpointTests.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -11,8 +11,25 @@ namespace StellaOps.Excititor.WebService.Tests;
|
||||
|
||||
public sealed class TestWebApplicationFactory : WebApplicationFactory<Program>
|
||||
{
|
||||
private readonly Action<IConfigurationBuilder>? _configureConfiguration;
|
||||
private readonly Action<IServiceCollection>? _configureServices;
|
||||
|
||||
public TestWebApplicationFactory() : this(null, null)
|
||||
{
|
||||
}
|
||||
|
||||
internal TestWebApplicationFactory(
|
||||
Action<IConfigurationBuilder>? configureConfiguration = null,
|
||||
Action<IServiceCollection>? configureServices = null)
|
||||
{
|
||||
_configureConfiguration = configureConfiguration;
|
||||
_configureServices = configureServices;
|
||||
}
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
// Avoid loading any external hosting startup assemblies (e.g., Razor dev tools)
|
||||
builder.UseSetting(WebHostDefaults.PreventHostingStartupKey, "true");
|
||||
builder.UseEnvironment("Production");
|
||||
builder.ConfigureAppConfiguration((_, config) =>
|
||||
{
|
||||
@@ -23,11 +40,13 @@ public sealed class TestWebApplicationFactory : WebApplicationFactory<Program>
|
||||
["Excititor:Storage:Mongo:DefaultTenant"] = "test",
|
||||
};
|
||||
config.AddInMemoryCollection(defaults);
|
||||
_configureConfiguration?.Invoke(config);
|
||||
});
|
||||
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
services.RemoveAll<IHostedService>();
|
||||
_configureServices?.Invoke(services);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ namespace StellaOps.Excititor.WebService.Tests;
|
||||
public sealed class VexEvidenceChunkServiceTests
|
||||
{
|
||||
[Fact]
|
||||
[Trait("Category", "VexEvidence")]
|
||||
public async Task QueryAsync_FiltersAndLimitsResults()
|
||||
{
|
||||
var now = new DateTimeOffset(2025, 11, 16, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.Net.Http.Headers;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Excititor.Worker.Auth;
|
||||
using StellaOps.Excititor.Worker.Options;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.Worker.Tests;
|
||||
|
||||
public sealed class TenantAuthorityClientFactoryTests
|
||||
{
|
||||
[Fact]
|
||||
public void Create_WhenTenantConfigured_SetsBaseAddressAndTenantHeader()
|
||||
{
|
||||
var options = new TenantAuthorityOptions();
|
||||
options.BaseUrls.Add("tenant-a", "https://authority.example/");
|
||||
var factory = new TenantAuthorityClientFactory(Options.Create(options));
|
||||
|
||||
using var client = factory.Create("tenant-a");
|
||||
|
||||
client.BaseAddress.Should().Be(new Uri("https://authority.example/"));
|
||||
client.DefaultRequestHeaders.TryGetValues("X-Tenant", out var values).Should().BeTrue();
|
||||
values.Should().ContainSingle().Which.Should().Be("tenant-a");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_Throws_WhenTenantMissing()
|
||||
{
|
||||
var options = new TenantAuthorityOptions();
|
||||
options.BaseUrls.Add("tenant-a", "https://authority.example/");
|
||||
var factory = new TenantAuthorityClientFactory(Options.Create(options));
|
||||
|
||||
FluentActions.Invoking(() => factory.Create(string.Empty))
|
||||
.Should().Throw<ArgumentException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_Throws_WhenTenantNotConfigured()
|
||||
{
|
||||
var options = new TenantAuthorityOptions();
|
||||
options.BaseUrls.Add("tenant-a", "https://authority.example/");
|
||||
var factory = new TenantAuthorityClientFactory(Options.Create(options));
|
||||
|
||||
FluentActions.Invoking(() => factory.Create("tenant-b"))
|
||||
.Should().Throw<InvalidOperationException>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Excititor.Worker.Options;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.Worker.Tests;
|
||||
|
||||
public sealed class TenantAuthorityOptionsValidatorTests
|
||||
{
|
||||
private readonly TenantAuthorityOptionsValidator _validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_Fails_When_BaseUrls_Empty()
|
||||
{
|
||||
var options = new TenantAuthorityOptions();
|
||||
|
||||
var result = _validator.Validate(null, options);
|
||||
|
||||
result.Failed.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Fails_When_Key_Or_Value_Blank()
|
||||
{
|
||||
var options = new TenantAuthorityOptions();
|
||||
options.BaseUrls.Add("", "");
|
||||
|
||||
var result = _validator.Validate(null, options);
|
||||
|
||||
result.Failed.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Succeeds_When_Valid()
|
||||
{
|
||||
var options = new TenantAuthorityOptions();
|
||||
options.BaseUrls.Add("tenant-a", "https://authority.example");
|
||||
|
||||
var result = _validator.Validate(null, options);
|
||||
|
||||
result.Succeeded.Should().BeTrue();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user