up
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Contracts;
|
||||
|
||||
/// <summary>
|
||||
/// Response for /attestations/vex/{attestationId} endpoint.
|
||||
/// </summary>
|
||||
public sealed record VexAttestationDetailResponse(
|
||||
[property: JsonPropertyName("attestationId")] string AttestationId,
|
||||
[property: JsonPropertyName("tenant")] string Tenant,
|
||||
[property: JsonPropertyName("createdAt")] DateTimeOffset CreatedAt,
|
||||
[property: JsonPropertyName("predicateType")] string PredicateType,
|
||||
[property: JsonPropertyName("subject")] VexAttestationSubject Subject,
|
||||
[property: JsonPropertyName("builder")] VexAttestationBuilderIdentity Builder,
|
||||
[property: JsonPropertyName("verification")] VexAttestationVerificationState Verification,
|
||||
[property: JsonPropertyName("chainOfCustody")] IReadOnlyList<VexAttestationCustodyLink> ChainOfCustody,
|
||||
[property: JsonPropertyName("metadata")] IReadOnlyDictionary<string, string> Metadata);
|
||||
|
||||
/// <summary>
|
||||
/// Subject of the attestation (what was signed).
|
||||
/// </summary>
|
||||
public sealed record VexAttestationSubject(
|
||||
[property: JsonPropertyName("digest")] string Digest,
|
||||
[property: JsonPropertyName("digestAlgorithm")] string DigestAlgorithm,
|
||||
[property: JsonPropertyName("name")] string? Name,
|
||||
[property: JsonPropertyName("uri")] string? Uri);
|
||||
|
||||
/// <summary>
|
||||
/// Builder identity for the attestation.
|
||||
/// </summary>
|
||||
public sealed record VexAttestationBuilderIdentity(
|
||||
[property: JsonPropertyName("id")] string Id,
|
||||
[property: JsonPropertyName("version")] string? Version,
|
||||
[property: JsonPropertyName("builderId")] string? BuilderId,
|
||||
[property: JsonPropertyName("invocationId")] string? InvocationId);
|
||||
|
||||
/// <summary>
|
||||
/// DSSE verification state.
|
||||
/// </summary>
|
||||
public sealed record VexAttestationVerificationState(
|
||||
[property: JsonPropertyName("valid")] bool Valid,
|
||||
[property: JsonPropertyName("verifiedAt")] DateTimeOffset? VerifiedAt,
|
||||
[property: JsonPropertyName("signatureType")] string? SignatureType,
|
||||
[property: JsonPropertyName("keyId")] string? KeyId,
|
||||
[property: JsonPropertyName("issuer")] string? Issuer,
|
||||
[property: JsonPropertyName("envelopeDigest")] string? EnvelopeDigest,
|
||||
[property: JsonPropertyName("diagnostics")] IReadOnlyDictionary<string, string> Diagnostics);
|
||||
|
||||
/// <summary>
|
||||
/// Chain-of-custody link in the attestation provenance.
|
||||
/// </summary>
|
||||
public sealed record VexAttestationCustodyLink(
|
||||
[property: JsonPropertyName("step")] int Step,
|
||||
[property: JsonPropertyName("actor")] string Actor,
|
||||
[property: JsonPropertyName("action")] string Action,
|
||||
[property: JsonPropertyName("timestamp")] DateTimeOffset Timestamp,
|
||||
[property: JsonPropertyName("reference")] string? Reference);
|
||||
|
||||
/// <summary>
|
||||
/// Response for /attestations/vex/list endpoint.
|
||||
/// </summary>
|
||||
public sealed record VexAttestationListResponse(
|
||||
[property: JsonPropertyName("items")] IReadOnlyList<VexAttestationListItem> Items,
|
||||
[property: JsonPropertyName("cursor")] string? Cursor,
|
||||
[property: JsonPropertyName("hasMore")] bool HasMore,
|
||||
[property: JsonPropertyName("total")] int Total);
|
||||
|
||||
/// <summary>
|
||||
/// Summary item for attestation list.
|
||||
/// </summary>
|
||||
public sealed record VexAttestationListItem(
|
||||
[property: JsonPropertyName("attestationId")] string AttestationId,
|
||||
[property: JsonPropertyName("tenant")] string Tenant,
|
||||
[property: JsonPropertyName("createdAt")] DateTimeOffset CreatedAt,
|
||||
[property: JsonPropertyName("predicateType")] string PredicateType,
|
||||
[property: JsonPropertyName("subjectDigest")] string SubjectDigest,
|
||||
[property: JsonPropertyName("valid")] bool Valid,
|
||||
[property: JsonPropertyName("builderId")] string? BuilderId);
|
||||
|
||||
/// <summary>
|
||||
/// Response for /attestations/vex/lookup endpoint.
|
||||
/// </summary>
|
||||
public sealed record VexAttestationLookupResponse(
|
||||
[property: JsonPropertyName("subjectDigest")] string SubjectDigest,
|
||||
[property: JsonPropertyName("attestations")] IReadOnlyList<VexAttestationListItem> Attestations,
|
||||
[property: JsonPropertyName("queriedAt")] DateTimeOffset QueriedAt);
|
||||
@@ -0,0 +1,141 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Contracts;
|
||||
|
||||
/// <summary>
|
||||
/// Response for /evidence/vex/bundle/{bundleId} endpoint.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceBundleResponse(
|
||||
[property: JsonPropertyName("bundleId")] string BundleId,
|
||||
[property: JsonPropertyName("tenant")] string Tenant,
|
||||
[property: JsonPropertyName("createdAt")] DateTimeOffset CreatedAt,
|
||||
[property: JsonPropertyName("contentHash")] string ContentHash,
|
||||
[property: JsonPropertyName("format")] string Format,
|
||||
[property: JsonPropertyName("itemCount")] int ItemCount,
|
||||
[property: JsonPropertyName("verification")] VexEvidenceVerificationMetadata? Verification,
|
||||
[property: JsonPropertyName("metadata")] IReadOnlyDictionary<string, string> Metadata);
|
||||
|
||||
/// <summary>
|
||||
/// Verification metadata for evidence bundles.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceVerificationMetadata(
|
||||
[property: JsonPropertyName("verified")] bool Verified,
|
||||
[property: JsonPropertyName("verifiedAt")] DateTimeOffset? VerifiedAt,
|
||||
[property: JsonPropertyName("signatureType")] string? SignatureType,
|
||||
[property: JsonPropertyName("keyId")] string? KeyId,
|
||||
[property: JsonPropertyName("issuer")] string? Issuer,
|
||||
[property: JsonPropertyName("transparencyRef")] string? TransparencyRef);
|
||||
|
||||
/// <summary>
|
||||
/// Response for /evidence/vex/list endpoint.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceListResponse(
|
||||
[property: JsonPropertyName("items")] IReadOnlyList<VexEvidenceListItem> Items,
|
||||
[property: JsonPropertyName("cursor")] string? Cursor,
|
||||
[property: JsonPropertyName("hasMore")] bool HasMore,
|
||||
[property: JsonPropertyName("total")] int Total);
|
||||
|
||||
/// <summary>
|
||||
/// Summary item for evidence list.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceListItem(
|
||||
[property: JsonPropertyName("bundleId")] string BundleId,
|
||||
[property: JsonPropertyName("tenant")] string Tenant,
|
||||
[property: JsonPropertyName("createdAt")] DateTimeOffset CreatedAt,
|
||||
[property: JsonPropertyName("contentHash")] string ContentHash,
|
||||
[property: JsonPropertyName("format")] string Format,
|
||||
[property: JsonPropertyName("itemCount")] int ItemCount,
|
||||
[property: JsonPropertyName("verified")] bool Verified);
|
||||
|
||||
/// <summary>
|
||||
/// Response for /evidence/vex/lookup endpoint.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceLookupResponse(
|
||||
[property: JsonPropertyName("vulnerabilityId")] string VulnerabilityId,
|
||||
[property: JsonPropertyName("productKey")] string ProductKey,
|
||||
[property: JsonPropertyName("evidenceItems")] IReadOnlyList<VexEvidenceItem> EvidenceItems,
|
||||
[property: JsonPropertyName("queriedAt")] DateTimeOffset QueriedAt);
|
||||
|
||||
/// <summary>
|
||||
/// Individual evidence item for a vuln/product pair.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceItem(
|
||||
[property: JsonPropertyName("observationId")] string ObservationId,
|
||||
[property: JsonPropertyName("providerId")] string ProviderId,
|
||||
[property: JsonPropertyName("status")] string Status,
|
||||
[property: JsonPropertyName("justification")] string? Justification,
|
||||
[property: JsonPropertyName("firstSeen")] DateTimeOffset FirstSeen,
|
||||
[property: JsonPropertyName("lastSeen")] DateTimeOffset LastSeen,
|
||||
[property: JsonPropertyName("documentDigest")] string DocumentDigest,
|
||||
[property: JsonPropertyName("verification")] VexEvidenceVerificationMetadata? Verification);
|
||||
|
||||
/// <summary>
|
||||
/// Response for /vuln/evidence/vex/{advisory_key} endpoint.
|
||||
/// Returns tenant-scoped raw statements for Vuln Explorer evidence tabs.
|
||||
/// </summary>
|
||||
public sealed record VexAdvisoryEvidenceResponse(
|
||||
[property: JsonPropertyName("advisoryKey")] string AdvisoryKey,
|
||||
[property: JsonPropertyName("canonicalKey")] string CanonicalKey,
|
||||
[property: JsonPropertyName("scope")] string Scope,
|
||||
[property: JsonPropertyName("aliases")] IReadOnlyList<VexAdvisoryLinkResponse> Aliases,
|
||||
[property: JsonPropertyName("statements")] IReadOnlyList<VexAdvisoryStatementResponse> Statements,
|
||||
[property: JsonPropertyName("queriedAt")] DateTimeOffset QueriedAt,
|
||||
[property: JsonPropertyName("totalCount")] int TotalCount);
|
||||
|
||||
/// <summary>
|
||||
/// Advisory link for traceability (CVE, GHSA, RHSA, etc.).
|
||||
/// </summary>
|
||||
public sealed record VexAdvisoryLinkResponse(
|
||||
[property: JsonPropertyName("identifier")] string Identifier,
|
||||
[property: JsonPropertyName("type")] string Type,
|
||||
[property: JsonPropertyName("isOriginal")] bool IsOriginal);
|
||||
|
||||
/// <summary>
|
||||
/// Raw VEX statement for an advisory with provenance and attestation metadata.
|
||||
/// </summary>
|
||||
public sealed record VexAdvisoryStatementResponse(
|
||||
[property: JsonPropertyName("statementId")] string StatementId,
|
||||
[property: JsonPropertyName("providerId")] string ProviderId,
|
||||
[property: JsonPropertyName("product")] VexAdvisoryProductResponse Product,
|
||||
[property: JsonPropertyName("status")] string Status,
|
||||
[property: JsonPropertyName("justification")] string? Justification,
|
||||
[property: JsonPropertyName("detail")] string? Detail,
|
||||
[property: JsonPropertyName("firstSeen")] DateTimeOffset FirstSeen,
|
||||
[property: JsonPropertyName("lastSeen")] DateTimeOffset LastSeen,
|
||||
[property: JsonPropertyName("provenance")] VexAdvisoryProvenanceResponse Provenance,
|
||||
[property: JsonPropertyName("attestation")] VexAdvisoryAttestationResponse? Attestation);
|
||||
|
||||
/// <summary>
|
||||
/// Product information for an advisory statement.
|
||||
/// </summary>
|
||||
public sealed record VexAdvisoryProductResponse(
|
||||
[property: JsonPropertyName("key")] string Key,
|
||||
[property: JsonPropertyName("name")] string? Name,
|
||||
[property: JsonPropertyName("version")] string? Version,
|
||||
[property: JsonPropertyName("purl")] string? Purl,
|
||||
[property: JsonPropertyName("cpe")] string? Cpe);
|
||||
|
||||
/// <summary>
|
||||
/// Provenance metadata for a VEX statement.
|
||||
/// </summary>
|
||||
public sealed record VexAdvisoryProvenanceResponse(
|
||||
[property: JsonPropertyName("documentDigest")] string DocumentDigest,
|
||||
[property: JsonPropertyName("documentFormat")] string DocumentFormat,
|
||||
[property: JsonPropertyName("sourceUri")] string SourceUri,
|
||||
[property: JsonPropertyName("revision")] string? Revision,
|
||||
[property: JsonPropertyName("insertedAt")] DateTimeOffset InsertedAt);
|
||||
|
||||
/// <summary>
|
||||
/// Attestation metadata for signature verification.
|
||||
/// </summary>
|
||||
public sealed record VexAdvisoryAttestationResponse(
|
||||
[property: JsonPropertyName("signatureType")] string SignatureType,
|
||||
[property: JsonPropertyName("issuer")] string? Issuer,
|
||||
[property: JsonPropertyName("subject")] string? Subject,
|
||||
[property: JsonPropertyName("keyId")] string? KeyId,
|
||||
[property: JsonPropertyName("verifiedAt")] DateTimeOffset? VerifiedAt,
|
||||
[property: JsonPropertyName("transparencyLogRef")] string? TransparencyLogRef,
|
||||
[property: JsonPropertyName("trustWeight")] decimal? TrustWeight,
|
||||
[property: JsonPropertyName("trustTier")] string? TrustTier);
|
||||
@@ -0,0 +1,347 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.WebService.Contracts;
|
||||
using StellaOps.Excititor.WebService.Services;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Endpoints;
|
||||
|
||||
/// <summary>
|
||||
/// Attestation API endpoints (WEB-OBS-54-001).
|
||||
/// Exposes /attestations/vex/* endpoints returning DSSE verification state,
|
||||
/// builder identity, and chain-of-custody links.
|
||||
/// </summary>
|
||||
public static class AttestationEndpoints
|
||||
{
|
||||
public static void MapAttestationEndpoints(this WebApplication app)
|
||||
{
|
||||
// GET /attestations/vex/list - List attestations
|
||||
app.MapGet("/attestations/vex/list", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IMongoDatabase database,
|
||||
TimeProvider timeProvider,
|
||||
[FromQuery] int? limit,
|
||||
[FromQuery] string? cursor,
|
||||
[FromQuery] string? vulnerabilityId,
|
||||
[FromQuery] string? productKey,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
var take = Math.Clamp(limit.GetValueOrDefault(50), 1, 200);
|
||||
var collection = database.GetCollection<BsonDocument>(VexMongoCollectionNames.Attestations);
|
||||
var builder = Builders<BsonDocument>.Filter;
|
||||
var filters = new List<FilterDefinition<BsonDocument>>();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(vulnerabilityId))
|
||||
{
|
||||
filters.Add(builder.Eq("VulnerabilityId", vulnerabilityId.Trim().ToUpperInvariant()));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(productKey))
|
||||
{
|
||||
filters.Add(builder.Eq("ProductKey", productKey.Trim().ToLowerInvariant()));
|
||||
}
|
||||
|
||||
// Parse cursor if provided
|
||||
if (!string.IsNullOrWhiteSpace(cursor) && TryDecodeCursor(cursor, out var cursorTime, out var cursorId))
|
||||
{
|
||||
var ltTime = builder.Lt("IssuedAt", cursorTime);
|
||||
var eqTimeLtId = builder.And(
|
||||
builder.Eq("IssuedAt", cursorTime),
|
||||
builder.Lt("_id", cursorId));
|
||||
filters.Add(builder.Or(ltTime, eqTimeLtId));
|
||||
}
|
||||
|
||||
var filter = filters.Count == 0 ? builder.Empty : builder.And(filters);
|
||||
var sort = Builders<BsonDocument>.Sort.Descending("IssuedAt").Descending("_id");
|
||||
|
||||
var documents = await collection
|
||||
.Find(filter)
|
||||
.Sort(sort)
|
||||
.Limit(take)
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var items = documents.Select(doc => ToListItem(doc, tenant, timeProvider)).ToList();
|
||||
|
||||
string? nextCursor = null;
|
||||
var hasMore = documents.Count == take;
|
||||
if (hasMore && documents.Count > 0)
|
||||
{
|
||||
var last = documents[^1];
|
||||
var lastTime = last.GetValue("IssuedAt", BsonNull.Value).ToUniversalTime();
|
||||
var lastId = last.GetValue("_id", BsonNull.Value).AsString;
|
||||
nextCursor = EncodeCursor(lastTime, lastId);
|
||||
}
|
||||
|
||||
var response = new VexAttestationListResponse(items, nextCursor, hasMore, items.Count);
|
||||
return Results.Ok(response);
|
||||
}).WithName("ListVexAttestations");
|
||||
|
||||
// GET /attestations/vex/{attestationId} - Get attestation details
|
||||
app.MapGet("/attestations/vex/{attestationId}", async (
|
||||
HttpContext context,
|
||||
string attestationId,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexAttestationLinkStore attestationStore,
|
||||
TimeProvider timeProvider,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(attestationId))
|
||||
{
|
||||
return Results.BadRequest(new { error = new { code = "ERR_ATTESTATION_ID", message = "attestationId is required" } });
|
||||
}
|
||||
|
||||
var attestation = await attestationStore.FindAsync(attestationId.Trim(), cancellationToken).ConfigureAwait(false);
|
||||
if (attestation is null)
|
||||
{
|
||||
return Results.NotFound(new { error = new { code = "ERR_NOT_FOUND", message = $"Attestation '{attestationId}' not found" } });
|
||||
}
|
||||
|
||||
// Build subject from observation context
|
||||
var subjectDigest = attestation.Metadata.TryGetValue("digest", out var dig) ? dig : attestation.ObservationId;
|
||||
var subject = new VexAttestationSubject(
|
||||
Digest: subjectDigest,
|
||||
DigestAlgorithm: "sha256",
|
||||
Name: $"{attestation.VulnerabilityId}/{attestation.ProductKey}",
|
||||
Uri: null);
|
||||
|
||||
var builder = new VexAttestationBuilderIdentity(
|
||||
Id: attestation.SupplierId,
|
||||
Version: null,
|
||||
BuilderId: attestation.SupplierId,
|
||||
InvocationId: attestation.ObservationId);
|
||||
|
||||
// Get verification state from metadata
|
||||
var isValid = attestation.Metadata.TryGetValue("verified", out var verified) && verified == "true";
|
||||
DateTimeOffset? verifiedAt = null;
|
||||
if (attestation.Metadata.TryGetValue("verifiedAt", out var verifiedAtStr) &&
|
||||
DateTimeOffset.TryParse(verifiedAtStr, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var parsedVerifiedAt))
|
||||
{
|
||||
verifiedAt = parsedVerifiedAt;
|
||||
}
|
||||
|
||||
var verification = new VexAttestationVerificationState(
|
||||
Valid: isValid,
|
||||
VerifiedAt: verifiedAt,
|
||||
SignatureType: attestation.Metadata.GetValueOrDefault("signatureType", "dsse"),
|
||||
KeyId: attestation.Metadata.GetValueOrDefault("keyId"),
|
||||
Issuer: attestation.Metadata.GetValueOrDefault("issuer"),
|
||||
EnvelopeDigest: attestation.Metadata.GetValueOrDefault("envelopeDigest"),
|
||||
Diagnostics: attestation.Metadata);
|
||||
|
||||
var custodyLinks = new List<VexAttestationCustodyLink>
|
||||
{
|
||||
new(
|
||||
Step: 1,
|
||||
Actor: attestation.SupplierId,
|
||||
Action: "created",
|
||||
Timestamp: attestation.IssuedAt,
|
||||
Reference: attestation.AttestationId)
|
||||
};
|
||||
|
||||
// Add linkset link
|
||||
custodyLinks.Add(new VexAttestationCustodyLink(
|
||||
Step: 2,
|
||||
Actor: "excititor",
|
||||
Action: "linked_to_observation",
|
||||
Timestamp: attestation.IssuedAt,
|
||||
Reference: attestation.LinksetId));
|
||||
|
||||
var metadata = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["observationId"] = attestation.ObservationId,
|
||||
["linksetId"] = attestation.LinksetId,
|
||||
["vulnerabilityId"] = attestation.VulnerabilityId,
|
||||
["productKey"] = attestation.ProductKey
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(attestation.JustificationSummary))
|
||||
{
|
||||
metadata["justificationSummary"] = attestation.JustificationSummary;
|
||||
}
|
||||
|
||||
var response = new VexAttestationDetailResponse(
|
||||
AttestationId: attestation.AttestationId,
|
||||
Tenant: tenant,
|
||||
CreatedAt: attestation.IssuedAt,
|
||||
PredicateType: attestation.Metadata.GetValueOrDefault("predicateType", "https://in-toto.io/attestation/v1"),
|
||||
Subject: subject,
|
||||
Builder: builder,
|
||||
Verification: verification,
|
||||
ChainOfCustody: custodyLinks,
|
||||
Metadata: metadata);
|
||||
|
||||
return Results.Ok(response);
|
||||
}).WithName("GetVexAttestation");
|
||||
|
||||
// GET /attestations/vex/lookup - Lookup attestations by linkset or observation
|
||||
app.MapGet("/attestations/vex/lookup", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IMongoDatabase database,
|
||||
TimeProvider timeProvider,
|
||||
[FromQuery] string? linksetId,
|
||||
[FromQuery] string? observationId,
|
||||
[FromQuery] int? limit,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(linksetId) && string.IsNullOrWhiteSpace(observationId))
|
||||
{
|
||||
return Results.BadRequest(new { error = new { code = "ERR_PARAMS", message = "Either linksetId or observationId is required" } });
|
||||
}
|
||||
|
||||
var take = Math.Clamp(limit.GetValueOrDefault(50), 1, 100);
|
||||
var collection = database.GetCollection<BsonDocument>(VexMongoCollectionNames.Attestations);
|
||||
var builder = Builders<BsonDocument>.Filter;
|
||||
|
||||
FilterDefinition<BsonDocument> filter;
|
||||
if (!string.IsNullOrWhiteSpace(linksetId))
|
||||
{
|
||||
filter = builder.Eq("LinksetId", linksetId.Trim());
|
||||
}
|
||||
else
|
||||
{
|
||||
filter = builder.Eq("ObservationId", observationId!.Trim());
|
||||
}
|
||||
|
||||
var sort = Builders<BsonDocument>.Sort.Descending("IssuedAt");
|
||||
|
||||
var documents = await collection
|
||||
.Find(filter)
|
||||
.Sort(sort)
|
||||
.Limit(take)
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var items = documents.Select(doc => ToListItem(doc, tenant, timeProvider)).ToList();
|
||||
|
||||
var response = new VexAttestationLookupResponse(
|
||||
SubjectDigest: linksetId ?? observationId ?? string.Empty,
|
||||
Attestations: items,
|
||||
QueriedAt: timeProvider.GetUtcNow());
|
||||
|
||||
return Results.Ok(response);
|
||||
}).WithName("LookupVexAttestations");
|
||||
}
|
||||
|
||||
private static VexAttestationListItem ToListItem(BsonDocument doc, string tenant, TimeProvider timeProvider)
|
||||
{
|
||||
return new VexAttestationListItem(
|
||||
AttestationId: doc.GetValue("_id", BsonNull.Value).AsString ?? string.Empty,
|
||||
Tenant: tenant,
|
||||
CreatedAt: doc.GetValue("IssuedAt", BsonNull.Value).IsBsonDateTime
|
||||
? new DateTimeOffset(doc["IssuedAt"].ToUniversalTime(), TimeSpan.Zero)
|
||||
: timeProvider.GetUtcNow(),
|
||||
PredicateType: "https://in-toto.io/attestation/v1",
|
||||
SubjectDigest: doc.GetValue("ObservationId", BsonNull.Value).AsString ?? string.Empty,
|
||||
Valid: doc.Contains("Metadata") && !doc["Metadata"].IsBsonNull &&
|
||||
doc["Metadata"].AsBsonDocument.Contains("verified") &&
|
||||
doc["Metadata"]["verified"].AsString == "true",
|
||||
BuilderId: doc.GetValue("SupplierId", BsonNull.Value).AsString);
|
||||
}
|
||||
|
||||
private static bool TryResolveTenant(HttpContext context, VexMongoStorageOptions options, out string tenant, out IResult? problem)
|
||||
{
|
||||
tenant = options.DefaultTenant;
|
||||
problem = null;
|
||||
|
||||
if (context.Request.Headers.TryGetValue("X-Stella-Tenant", out var headerValues) && headerValues.Count > 0)
|
||||
{
|
||||
var requestedTenant = headerValues[0]?.Trim();
|
||||
if (string.IsNullOrEmpty(requestedTenant))
|
||||
{
|
||||
problem = Results.BadRequest(new { error = new { code = "ERR_TENANT", message = "X-Stella-Tenant header must not be empty" } });
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!string.Equals(requestedTenant, options.DefaultTenant, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
problem = Results.Json(
|
||||
new { error = new { code = "ERR_TENANT_FORBIDDEN", message = $"Tenant '{requestedTenant}' is not allowed" } },
|
||||
statusCode: StatusCodes.Status403Forbidden);
|
||||
return false;
|
||||
}
|
||||
|
||||
tenant = requestedTenant;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryDecodeCursor(string cursor, out DateTime timestamp, out string id)
|
||||
{
|
||||
timestamp = default;
|
||||
id = string.Empty;
|
||||
try
|
||||
{
|
||||
var payload = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(cursor));
|
||||
var parts = payload.Split('|');
|
||||
if (parts.Length != 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!DateTimeOffset.TryParse(parts[0], CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var parsed))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
timestamp = parsed.UtcDateTime;
|
||||
id = parts[1];
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string EncodeCursor(DateTime timestamp, string id)
|
||||
{
|
||||
var payload = FormattableString.Invariant($"{timestamp:O}|{id}");
|
||||
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(payload));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Core.Canonicalization;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.WebService.Contracts;
|
||||
using StellaOps.Excititor.WebService.Services;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Endpoints;
|
||||
|
||||
/// <summary>
|
||||
/// Evidence API endpoints (WEB-OBS-53-001).
|
||||
/// Exposes /evidence/vex/* endpoints that fetch locker bundles, enforce scopes,
|
||||
/// and surface verification metadata without synthesizing verdicts.
|
||||
/// </summary>
|
||||
public static class EvidenceEndpoints
|
||||
{
|
||||
public static void MapEvidenceEndpoints(this WebApplication app)
|
||||
{
|
||||
// GET /evidence/vex/list - List evidence exports
|
||||
app.MapGet("/evidence/vex/list", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IMongoDatabase database,
|
||||
TimeProvider timeProvider,
|
||||
[FromQuery] int? limit,
|
||||
[FromQuery] string? cursor,
|
||||
[FromQuery] string? format,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
var take = Math.Clamp(limit.GetValueOrDefault(50), 1, 200);
|
||||
var collection = database.GetCollection<BsonDocument>(VexMongoCollectionNames.Exports);
|
||||
var builder = Builders<BsonDocument>.Filter;
|
||||
var filters = new List<FilterDefinition<BsonDocument>>();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(format))
|
||||
{
|
||||
filters.Add(builder.Eq("Format", format.Trim().ToLowerInvariant()));
|
||||
}
|
||||
|
||||
// Parse cursor if provided (base64-encoded timestamp|id)
|
||||
if (!string.IsNullOrWhiteSpace(cursor) && TryDecodeCursor(cursor, out var cursorTime, out var cursorId))
|
||||
{
|
||||
var ltTime = builder.Lt("CreatedAt", cursorTime);
|
||||
var eqTimeLtId = builder.And(
|
||||
builder.Eq("CreatedAt", cursorTime),
|
||||
builder.Lt("_id", cursorId));
|
||||
filters.Add(builder.Or(ltTime, eqTimeLtId));
|
||||
}
|
||||
|
||||
var filter = filters.Count == 0 ? builder.Empty : builder.And(filters);
|
||||
var sort = Builders<BsonDocument>.Sort.Descending("CreatedAt").Descending("_id");
|
||||
|
||||
var documents = await collection
|
||||
.Find(filter)
|
||||
.Sort(sort)
|
||||
.Limit(take)
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var items = documents.Select(doc => new VexEvidenceListItem(
|
||||
BundleId: doc.GetValue("ExportId", BsonNull.Value).AsString ?? doc.GetValue("_id", BsonNull.Value).AsString,
|
||||
Tenant: tenant,
|
||||
CreatedAt: doc.GetValue("CreatedAt", BsonNull.Value).IsBsonDateTime
|
||||
? new DateTimeOffset(doc["CreatedAt"].ToUniversalTime(), TimeSpan.Zero)
|
||||
: timeProvider.GetUtcNow(),
|
||||
ContentHash: doc.GetValue("ArtifactDigest", BsonNull.Value).AsString ?? string.Empty,
|
||||
Format: doc.GetValue("Format", BsonNull.Value).AsString ?? "json",
|
||||
ItemCount: doc.GetValue("ClaimCount", BsonNull.Value).IsInt32 ? doc["ClaimCount"].AsInt32 : 0,
|
||||
Verified: doc.Contains("Attestation") && !doc["Attestation"].IsBsonNull)).ToList();
|
||||
|
||||
string? nextCursor = null;
|
||||
var hasMore = documents.Count == take;
|
||||
if (hasMore && documents.Count > 0)
|
||||
{
|
||||
var last = documents[^1];
|
||||
var lastTime = last.GetValue("CreatedAt", BsonNull.Value).ToUniversalTime();
|
||||
var lastId = last.GetValue("_id", BsonNull.Value).AsString;
|
||||
nextCursor = EncodeCursor(lastTime, lastId);
|
||||
}
|
||||
|
||||
var response = new VexEvidenceListResponse(items, nextCursor, hasMore, items.Count);
|
||||
return Results.Ok(response);
|
||||
}).WithName("ListVexEvidence");
|
||||
|
||||
// GET /evidence/vex/bundle/{bundleId} - Get evidence bundle details
|
||||
app.MapGet("/evidence/vex/bundle/{bundleId}", async (
|
||||
HttpContext context,
|
||||
string bundleId,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IMongoDatabase database,
|
||||
TimeProvider timeProvider,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(bundleId))
|
||||
{
|
||||
return Results.BadRequest(new { error = new { code = "ERR_BUNDLE_ID", message = "bundleId is required" } });
|
||||
}
|
||||
|
||||
var collection = database.GetCollection<BsonDocument>(VexMongoCollectionNames.Exports);
|
||||
var filter = Builders<BsonDocument>.Filter.Or(
|
||||
Builders<BsonDocument>.Filter.Eq("_id", bundleId.Trim()),
|
||||
Builders<BsonDocument>.Filter.Eq("ExportId", bundleId.Trim()));
|
||||
|
||||
var doc = await collection.Find(filter).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (doc is null)
|
||||
{
|
||||
return Results.NotFound(new { error = new { code = "ERR_NOT_FOUND", message = $"Evidence bundle '{bundleId}' not found" } });
|
||||
}
|
||||
|
||||
VexEvidenceVerificationMetadata? verification = null;
|
||||
if (doc.Contains("Attestation") && !doc["Attestation"].IsBsonNull)
|
||||
{
|
||||
var att = doc["Attestation"].AsBsonDocument;
|
||||
verification = new VexEvidenceVerificationMetadata(
|
||||
Verified: true,
|
||||
VerifiedAt: att.Contains("SignedAt") && att["SignedAt"].IsBsonDateTime
|
||||
? new DateTimeOffset(att["SignedAt"].ToUniversalTime(), TimeSpan.Zero)
|
||||
: null,
|
||||
SignatureType: "dsse",
|
||||
KeyId: att.GetValue("KeyId", BsonNull.Value).AsString,
|
||||
Issuer: att.GetValue("Issuer", BsonNull.Value).AsString,
|
||||
TransparencyRef: att.Contains("Rekor") && !att["Rekor"].IsBsonNull
|
||||
? att["Rekor"].AsBsonDocument.GetValue("Location", BsonNull.Value).AsString
|
||||
: null);
|
||||
}
|
||||
|
||||
var metadata = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
if (doc.Contains("SourceProviders") && doc["SourceProviders"].IsBsonArray)
|
||||
{
|
||||
metadata["sourceProviders"] = string.Join(",", doc["SourceProviders"].AsBsonArray.Select(v => v.AsString));
|
||||
}
|
||||
if (doc.Contains("PolicyRevisionId") && !doc["PolicyRevisionId"].IsBsonNull)
|
||||
{
|
||||
metadata["policyRevisionId"] = doc["PolicyRevisionId"].AsString;
|
||||
}
|
||||
|
||||
var response = new VexEvidenceBundleResponse(
|
||||
BundleId: doc.GetValue("ExportId", BsonNull.Value).AsString ?? bundleId.Trim(),
|
||||
Tenant: tenant,
|
||||
CreatedAt: doc.GetValue("CreatedAt", BsonNull.Value).IsBsonDateTime
|
||||
? new DateTimeOffset(doc["CreatedAt"].ToUniversalTime(), TimeSpan.Zero)
|
||||
: timeProvider.GetUtcNow(),
|
||||
ContentHash: doc.GetValue("ArtifactDigest", BsonNull.Value).AsString ?? string.Empty,
|
||||
Format: doc.GetValue("Format", BsonNull.Value).AsString ?? "json",
|
||||
ItemCount: doc.GetValue("ClaimCount", BsonNull.Value).IsInt32 ? doc["ClaimCount"].AsInt32 : 0,
|
||||
Verification: verification,
|
||||
Metadata: metadata);
|
||||
|
||||
return Results.Ok(response);
|
||||
}).WithName("GetVexEvidenceBundle");
|
||||
|
||||
// GET /evidence/vex/lookup - Lookup evidence for vuln/product pair
|
||||
app.MapGet("/evidence/vex/lookup", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexObservationProjectionService projectionService,
|
||||
TimeProvider timeProvider,
|
||||
[FromQuery] string vulnerabilityId,
|
||||
[FromQuery] string productKey,
|
||||
[FromQuery] int? limit,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(vulnerabilityId) || string.IsNullOrWhiteSpace(productKey))
|
||||
{
|
||||
return Results.BadRequest(new { error = new { code = "ERR_PARAMS", message = "vulnerabilityId and productKey are required" } });
|
||||
}
|
||||
|
||||
var take = Math.Clamp(limit.GetValueOrDefault(100), 1, 500);
|
||||
var request = new VexObservationProjectionRequest(
|
||||
tenant,
|
||||
vulnerabilityId.Trim(),
|
||||
productKey.Trim(),
|
||||
ImmutableHashSet<string>.Empty,
|
||||
ImmutableHashSet<VexClaimStatus>.Empty,
|
||||
null,
|
||||
take);
|
||||
|
||||
var result = await projectionService.QueryAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var items = result.Statements.Select(s => new VexEvidenceItem(
|
||||
ObservationId: s.ObservationId,
|
||||
ProviderId: s.ProviderId,
|
||||
Status: s.Status.ToString().ToLowerInvariant(),
|
||||
Justification: s.Justification?.ToString().ToLowerInvariant(),
|
||||
FirstSeen: s.FirstSeen,
|
||||
LastSeen: s.LastSeen,
|
||||
DocumentDigest: s.Document.Digest,
|
||||
Verification: s.Signature is null ? null : new VexEvidenceVerificationMetadata(
|
||||
Verified: s.Signature.VerifiedAt.HasValue,
|
||||
VerifiedAt: s.Signature.VerifiedAt,
|
||||
SignatureType: s.Signature.Type,
|
||||
KeyId: s.Signature.KeyId,
|
||||
Issuer: s.Signature.Issuer,
|
||||
TransparencyRef: null))).ToList();
|
||||
|
||||
var response = new VexEvidenceLookupResponse(
|
||||
VulnerabilityId: vulnerabilityId.Trim(),
|
||||
ProductKey: productKey.Trim(),
|
||||
EvidenceItems: items,
|
||||
QueriedAt: timeProvider.GetUtcNow());
|
||||
|
||||
return Results.Ok(response);
|
||||
}).WithName("LookupVexEvidence");
|
||||
}
|
||||
|
||||
private static bool TryResolveTenant(HttpContext context, VexMongoStorageOptions options, out string tenant, out IResult? problem)
|
||||
{
|
||||
tenant = options.DefaultTenant;
|
||||
problem = null;
|
||||
|
||||
if (context.Request.Headers.TryGetValue("X-Stella-Tenant", out var headerValues) && headerValues.Count > 0)
|
||||
{
|
||||
var requestedTenant = headerValues[0]?.Trim();
|
||||
if (string.IsNullOrEmpty(requestedTenant))
|
||||
{
|
||||
problem = Results.BadRequest(new { error = new { code = "ERR_TENANT", message = "X-Stella-Tenant header must not be empty" } });
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!string.Equals(requestedTenant, options.DefaultTenant, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
problem = Results.Json(
|
||||
new { error = new { code = "ERR_TENANT_FORBIDDEN", message = $"Tenant '{requestedTenant}' is not allowed" } },
|
||||
statusCode: StatusCodes.Status403Forbidden);
|
||||
return false;
|
||||
}
|
||||
|
||||
tenant = requestedTenant;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryDecodeCursor(string cursor, out DateTime timestamp, out string id)
|
||||
{
|
||||
timestamp = default;
|
||||
id = string.Empty;
|
||||
try
|
||||
{
|
||||
var payload = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(cursor));
|
||||
var parts = payload.Split('|');
|
||||
if (parts.Length != 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!DateTimeOffset.TryParse(parts[0], CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var parsed))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
timestamp = parsed.UtcDateTime;
|
||||
id = parts[1];
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string EncodeCursor(DateTime timestamp, string id)
|
||||
{
|
||||
var payload = FormattableString.Invariant($"{timestamp:O}|{id}");
|
||||
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(payload));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.WebService.Contracts;
|
||||
using StellaOps.Excititor.WebService.Services;
|
||||
using StellaOps.Excititor.WebService.Telemetry;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Endpoints;
|
||||
|
||||
/// <summary>
|
||||
/// Linkset API endpoints (EXCITITOR-LNM-21-202).
|
||||
/// Exposes /vex/linksets/* endpoints that surface alias mappings, conflict markers,
|
||||
/// and provenance proofs exactly as stored. Errors map to ERR_AGG_* codes.
|
||||
/// </summary>
|
||||
public static class LinksetEndpoints
|
||||
{
|
||||
public static void MapLinksetEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/vex/linksets");
|
||||
|
||||
// GET /vex/linksets - List linksets with filters
|
||||
group.MapGet("", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexLinksetStore linksetStore,
|
||||
[FromQuery] int? limit,
|
||||
[FromQuery] string? cursor,
|
||||
[FromQuery] string? vulnerabilityId,
|
||||
[FromQuery] string? productKey,
|
||||
[FromQuery] string? providerId,
|
||||
[FromQuery] bool? hasConflicts,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
var take = Math.Clamp(limit.GetValueOrDefault(50), 1, 100);
|
||||
|
||||
IReadOnlyList<VexLinkset> linksets;
|
||||
|
||||
// Route to appropriate query method based on filters
|
||||
if (hasConflicts == true)
|
||||
{
|
||||
linksets = await linksetStore
|
||||
.FindWithConflictsAsync(tenant, take, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(vulnerabilityId))
|
||||
{
|
||||
linksets = await linksetStore
|
||||
.FindByVulnerabilityAsync(tenant, vulnerabilityId.Trim(), take, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(productKey))
|
||||
{
|
||||
linksets = await linksetStore
|
||||
.FindByProductKeyAsync(tenant, productKey.Trim(), take, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(providerId))
|
||||
{
|
||||
linksets = await linksetStore
|
||||
.FindByProviderAsync(tenant, providerId.Trim(), take, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Results.BadRequest(new
|
||||
{
|
||||
error = new
|
||||
{
|
||||
code = "ERR_AGG_PARAMS",
|
||||
message = "At least one filter is required: vulnerabilityId, productKey, providerId, or hasConflicts=true"
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var items = linksets
|
||||
.Take(take)
|
||||
.Select(ToListItem)
|
||||
.ToList();
|
||||
|
||||
// Record conflict metrics (EXCITITOR-OBS-51-001)
|
||||
foreach (var linkset in linksets.Take(take))
|
||||
{
|
||||
if (linkset.HasConflicts)
|
||||
{
|
||||
LinksetTelemetry.RecordLinksetDisagreements(tenant, linkset);
|
||||
}
|
||||
}
|
||||
|
||||
var hasMore = linksets.Count > take;
|
||||
string? nextCursor = null;
|
||||
if (hasMore && items.Count > 0)
|
||||
{
|
||||
var last = linksets[items.Count - 1];
|
||||
nextCursor = EncodeCursor(last.UpdatedAt.UtcDateTime, last.LinksetId);
|
||||
}
|
||||
|
||||
var response = new VexLinksetListResponse(items, nextCursor);
|
||||
return Results.Ok(response);
|
||||
}).WithName("ListVexLinksets");
|
||||
|
||||
// GET /vex/linksets/{linksetId} - Get linkset by ID
|
||||
group.MapGet("/{linksetId}", async (
|
||||
HttpContext context,
|
||||
string linksetId,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexLinksetStore linksetStore,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(linksetId))
|
||||
{
|
||||
return Results.BadRequest(new
|
||||
{
|
||||
error = new { code = "ERR_AGG_PARAMS", message = "linksetId is required" }
|
||||
});
|
||||
}
|
||||
|
||||
var linkset = await linksetStore
|
||||
.GetByIdAsync(tenant, linksetId.Trim(), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (linkset is null)
|
||||
{
|
||||
return Results.NotFound(new
|
||||
{
|
||||
error = new { code = "ERR_AGG_NOT_FOUND", message = $"Linkset '{linksetId}' not found" }
|
||||
});
|
||||
}
|
||||
|
||||
var response = ToDetailResponse(linkset);
|
||||
return Results.Ok(response);
|
||||
}).WithName("GetVexLinkset");
|
||||
|
||||
// GET /vex/linksets/lookup - Lookup linkset by vulnerability and product
|
||||
group.MapGet("/lookup", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexLinksetStore linksetStore,
|
||||
[FromQuery] string? vulnerabilityId,
|
||||
[FromQuery] string? productKey,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(vulnerabilityId) || string.IsNullOrWhiteSpace(productKey))
|
||||
{
|
||||
return Results.BadRequest(new
|
||||
{
|
||||
error = new { code = "ERR_AGG_PARAMS", message = "vulnerabilityId and productKey are required" }
|
||||
});
|
||||
}
|
||||
|
||||
var linksetId = VexLinkset.CreateLinksetId(tenant, vulnerabilityId.Trim(), productKey.Trim());
|
||||
var linkset = await linksetStore
|
||||
.GetByIdAsync(tenant, linksetId, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (linkset is null)
|
||||
{
|
||||
return Results.NotFound(new
|
||||
{
|
||||
error = new { code = "ERR_AGG_NOT_FOUND", message = "No linkset found for the specified vulnerability and product" }
|
||||
});
|
||||
}
|
||||
|
||||
var response = ToDetailResponse(linkset);
|
||||
return Results.Ok(response);
|
||||
}).WithName("LookupVexLinkset");
|
||||
|
||||
// GET /vex/linksets/count - Get linkset counts for tenant
|
||||
group.MapGet("/count", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexLinksetStore linksetStore,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
var total = await linksetStore
|
||||
.CountAsync(tenant, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var withConflicts = await linksetStore
|
||||
.CountWithConflictsAsync(tenant, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return Results.Ok(new LinksetCountResponse(total, withConflicts));
|
||||
}).WithName("CountVexLinksets");
|
||||
|
||||
// GET /vex/linksets/conflicts - List linksets with conflicts (shorthand)
|
||||
group.MapGet("/conflicts", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexLinksetStore linksetStore,
|
||||
[FromQuery] int? limit,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
var take = Math.Clamp(limit.GetValueOrDefault(50), 1, 100);
|
||||
|
||||
var linksets = await linksetStore
|
||||
.FindWithConflictsAsync(tenant, take, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var items = linksets.Select(ToListItem).ToList();
|
||||
var response = new VexLinksetListResponse(items, null);
|
||||
return Results.Ok(response);
|
||||
}).WithName("ListVexLinksetConflicts");
|
||||
}
|
||||
|
||||
private static VexLinksetListItem ToListItem(VexLinkset linkset)
|
||||
{
|
||||
return new VexLinksetListItem(
|
||||
LinksetId: linkset.LinksetId,
|
||||
Tenant: linkset.Tenant,
|
||||
VulnerabilityId: linkset.VulnerabilityId,
|
||||
ProductKey: linkset.ProductKey,
|
||||
ProviderIds: linkset.ProviderIds.ToList(),
|
||||
Statuses: linkset.Statuses.ToList(),
|
||||
Aliases: Array.Empty<string>(), // Aliases are in observations, not linksets
|
||||
Purls: Array.Empty<string>(),
|
||||
Cpes: Array.Empty<string>(),
|
||||
References: Array.Empty<VexLinksetReference>(),
|
||||
Disagreements: linkset.Disagreements
|
||||
.Select(d => new VexLinksetDisagreement(d.ProviderId, d.Status, d.Justification, d.Confidence))
|
||||
.ToList(),
|
||||
Observations: linkset.Observations
|
||||
.Select(o => new VexLinksetObservationRef(o.ObservationId, o.ProviderId, o.Status, o.Confidence))
|
||||
.ToList(),
|
||||
CreatedAt: linkset.CreatedAt);
|
||||
}
|
||||
|
||||
private static VexLinksetDetailResponse ToDetailResponse(VexLinkset linkset)
|
||||
{
|
||||
return new VexLinksetDetailResponse(
|
||||
LinksetId: linkset.LinksetId,
|
||||
Tenant: linkset.Tenant,
|
||||
VulnerabilityId: linkset.VulnerabilityId,
|
||||
ProductKey: linkset.ProductKey,
|
||||
ProviderIds: linkset.ProviderIds.ToList(),
|
||||
Statuses: linkset.Statuses.ToList(),
|
||||
Confidence: linkset.Confidence.ToString().ToLowerInvariant(),
|
||||
HasConflicts: linkset.HasConflicts,
|
||||
Disagreements: linkset.Disagreements
|
||||
.Select(d => new VexLinksetDisagreement(d.ProviderId, d.Status, d.Justification, d.Confidence))
|
||||
.ToList(),
|
||||
Observations: linkset.Observations
|
||||
.Select(o => new VexLinksetObservationRef(o.ObservationId, o.ProviderId, o.Status, o.Confidence))
|
||||
.ToList(),
|
||||
CreatedAt: linkset.CreatedAt,
|
||||
UpdatedAt: linkset.UpdatedAt);
|
||||
}
|
||||
|
||||
private static bool TryResolveTenant(
|
||||
HttpContext context,
|
||||
VexMongoStorageOptions options,
|
||||
out string tenant,
|
||||
out IResult? problem)
|
||||
{
|
||||
problem = null;
|
||||
tenant = string.Empty;
|
||||
|
||||
var headerTenant = context.Request.Headers["X-Stella-Tenant"].FirstOrDefault();
|
||||
if (!string.IsNullOrWhiteSpace(headerTenant))
|
||||
{
|
||||
tenant = headerTenant.Trim().ToLowerInvariant();
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(options.DefaultTenant))
|
||||
{
|
||||
tenant = options.DefaultTenant.Trim().ToLowerInvariant();
|
||||
}
|
||||
else
|
||||
{
|
||||
problem = Results.BadRequest(new
|
||||
{
|
||||
error = new { code = "ERR_TENANT", message = "X-Stella-Tenant header is required" }
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string EncodeCursor(DateTime timestamp, string id)
|
||||
{
|
||||
var raw = $"{timestamp:O}|{id}";
|
||||
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(raw));
|
||||
}
|
||||
}
|
||||
|
||||
// Detail response for single linkset
|
||||
public sealed record VexLinksetDetailResponse(
|
||||
[property: JsonPropertyName("linksetId")] string LinksetId,
|
||||
[property: JsonPropertyName("tenant")] string Tenant,
|
||||
[property: JsonPropertyName("vulnerabilityId")] string VulnerabilityId,
|
||||
[property: JsonPropertyName("productKey")] string ProductKey,
|
||||
[property: JsonPropertyName("providerIds")] IReadOnlyList<string> ProviderIds,
|
||||
[property: JsonPropertyName("statuses")] IReadOnlyList<string> Statuses,
|
||||
[property: JsonPropertyName("confidence")] string Confidence,
|
||||
[property: JsonPropertyName("hasConflicts")] bool HasConflicts,
|
||||
[property: JsonPropertyName("disagreements")] IReadOnlyList<VexLinksetDisagreement> Disagreements,
|
||||
[property: JsonPropertyName("observations")] IReadOnlyList<VexLinksetObservationRef> Observations,
|
||||
[property: JsonPropertyName("createdAt")] DateTimeOffset CreatedAt,
|
||||
[property: JsonPropertyName("updatedAt")] DateTimeOffset UpdatedAt);
|
||||
|
||||
// Count response
|
||||
public sealed record LinksetCountResponse(
|
||||
[property: JsonPropertyName("total")] long Total,
|
||||
[property: JsonPropertyName("withConflicts")] long WithConflicts);
|
||||
@@ -0,0 +1,310 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.WebService.Contracts;
|
||||
using StellaOps.Excititor.WebService.Services;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Endpoints;
|
||||
|
||||
/// <summary>
|
||||
/// Observation API endpoints (EXCITITOR-LNM-21-201).
|
||||
/// Exposes /vex/observations/* endpoints with filters for advisory/product/provider,
|
||||
/// strict RBAC, and deterministic pagination (no derived verdict fields).
|
||||
/// </summary>
|
||||
public static class ObservationEndpoints
|
||||
{
|
||||
public static void MapObservationEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/vex/observations");
|
||||
|
||||
// GET /vex/observations - List observations with filters
|
||||
group.MapGet("", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexObservationStore observationStore,
|
||||
TimeProvider timeProvider,
|
||||
[FromQuery] int? limit,
|
||||
[FromQuery] string? cursor,
|
||||
[FromQuery] string? vulnerabilityId,
|
||||
[FromQuery] string? productKey,
|
||||
[FromQuery] string? providerId,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
var take = Math.Clamp(limit.GetValueOrDefault(50), 1, 100);
|
||||
|
||||
IReadOnlyList<VexObservation> observations;
|
||||
|
||||
// Route to appropriate query method based on filters
|
||||
if (!string.IsNullOrWhiteSpace(vulnerabilityId) && !string.IsNullOrWhiteSpace(productKey))
|
||||
{
|
||||
observations = await observationStore
|
||||
.FindByVulnerabilityAndProductAsync(tenant, vulnerabilityId.Trim(), productKey.Trim(), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(providerId))
|
||||
{
|
||||
observations = await observationStore
|
||||
.FindByProviderAsync(tenant, providerId.Trim(), take, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
// No filter - return empty for now (full list requires pagination infrastructure)
|
||||
return Results.BadRequest(new
|
||||
{
|
||||
error = new
|
||||
{
|
||||
code = "ERR_PARAMS",
|
||||
message = "At least one filter is required: vulnerabilityId+productKey or providerId"
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var items = observations
|
||||
.Take(take)
|
||||
.Select(obs => ToListItem(obs))
|
||||
.ToList();
|
||||
|
||||
var hasMore = observations.Count > take;
|
||||
string? nextCursor = null;
|
||||
if (hasMore && items.Count > 0)
|
||||
{
|
||||
var last = observations[items.Count - 1];
|
||||
nextCursor = EncodeCursor(last.CreatedAt.UtcDateTime, last.ObservationId);
|
||||
}
|
||||
|
||||
var response = new VexObservationListResponse(items, nextCursor);
|
||||
return Results.Ok(response);
|
||||
}).WithName("ListVexObservations");
|
||||
|
||||
// GET /vex/observations/{observationId} - Get observation by ID
|
||||
group.MapGet("/{observationId}", async (
|
||||
HttpContext context,
|
||||
string observationId,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexObservationStore observationStore,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(observationId))
|
||||
{
|
||||
return Results.BadRequest(new
|
||||
{
|
||||
error = new { code = "ERR_PARAMS", message = "observationId is required" }
|
||||
});
|
||||
}
|
||||
|
||||
var observation = await observationStore
|
||||
.GetByIdAsync(tenant, observationId.Trim(), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (observation is null)
|
||||
{
|
||||
return Results.NotFound(new
|
||||
{
|
||||
error = new { code = "ERR_NOT_FOUND", message = $"Observation '{observationId}' not found" }
|
||||
});
|
||||
}
|
||||
|
||||
var response = ToDetailResponse(observation);
|
||||
return Results.Ok(response);
|
||||
}).WithName("GetVexObservation");
|
||||
|
||||
// GET /vex/observations/count - Get observation count for tenant
|
||||
group.MapGet("/count", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexObservationStore observationStore,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var scopeResult = ScopeAuthorization.RequireScope(context, "vex.read");
|
||||
if (scopeResult is not null)
|
||||
{
|
||||
return scopeResult;
|
||||
}
|
||||
|
||||
if (!TryResolveTenant(context, storageOptions.Value, out var tenant, out var tenantError))
|
||||
{
|
||||
return tenantError;
|
||||
}
|
||||
|
||||
var count = await observationStore
|
||||
.CountAsync(tenant, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return Results.Ok(new { count });
|
||||
}).WithName("CountVexObservations");
|
||||
}
|
||||
|
||||
private static VexObservationListItem ToListItem(VexObservation obs)
|
||||
{
|
||||
var firstStatement = obs.Statements.FirstOrDefault();
|
||||
return new VexObservationListItem(
|
||||
ObservationId: obs.ObservationId,
|
||||
Tenant: obs.Tenant,
|
||||
ProviderId: obs.ProviderId,
|
||||
VulnerabilityId: firstStatement?.VulnerabilityId ?? string.Empty,
|
||||
ProductKey: firstStatement?.ProductKey ?? string.Empty,
|
||||
Status: firstStatement?.Status.ToString().ToLowerInvariant() ?? "unknown",
|
||||
CreatedAt: obs.CreatedAt,
|
||||
LastObserved: firstStatement?.LastObserved,
|
||||
Purls: obs.Linkset.Purls.ToList());
|
||||
}
|
||||
|
||||
private static VexObservationDetailResponse ToDetailResponse(VexObservation obs)
|
||||
{
|
||||
var upstream = new VexObservationUpstreamResponse(
|
||||
obs.Upstream.UpstreamId,
|
||||
obs.Upstream.DocumentVersion,
|
||||
obs.Upstream.FetchedAt,
|
||||
obs.Upstream.ReceivedAt,
|
||||
obs.Upstream.ContentHash,
|
||||
obs.Upstream.Signature.Present
|
||||
? new VexObservationSignatureResponse(
|
||||
obs.Upstream.Signature.Format ?? "dsse",
|
||||
obs.Upstream.Signature.KeyId,
|
||||
Issuer: null,
|
||||
VerifiedAtUtc: null)
|
||||
: null);
|
||||
|
||||
var content = new VexObservationContentResponse(
|
||||
obs.Content.Format,
|
||||
obs.Content.SpecVersion);
|
||||
|
||||
var statements = obs.Statements
|
||||
.Select(stmt => new VexObservationStatementItem(
|
||||
stmt.VulnerabilityId,
|
||||
stmt.ProductKey,
|
||||
stmt.Status.ToString().ToLowerInvariant(),
|
||||
stmt.LastObserved,
|
||||
stmt.Locator,
|
||||
stmt.Justification?.ToString().ToLowerInvariant(),
|
||||
stmt.IntroducedVersion,
|
||||
stmt.FixedVersion))
|
||||
.ToList();
|
||||
|
||||
var linkset = new VexObservationLinksetResponse(
|
||||
obs.Linkset.Aliases.ToList(),
|
||||
obs.Linkset.Purls.ToList(),
|
||||
obs.Linkset.Cpes.ToList(),
|
||||
obs.Linkset.References.Select(r => new VexObservationReferenceItem(r.Type, r.Url)).ToList());
|
||||
|
||||
return new VexObservationDetailResponse(
|
||||
obs.ObservationId,
|
||||
obs.Tenant,
|
||||
obs.ProviderId,
|
||||
obs.StreamId,
|
||||
upstream,
|
||||
content,
|
||||
statements,
|
||||
linkset,
|
||||
obs.CreatedAt);
|
||||
}
|
||||
|
||||
private static bool TryResolveTenant(
|
||||
HttpContext context,
|
||||
VexMongoStorageOptions options,
|
||||
out string tenant,
|
||||
out IResult? problem)
|
||||
{
|
||||
problem = null;
|
||||
tenant = string.Empty;
|
||||
|
||||
var headerTenant = context.Request.Headers["X-Stella-Tenant"].FirstOrDefault();
|
||||
if (!string.IsNullOrWhiteSpace(headerTenant))
|
||||
{
|
||||
tenant = headerTenant.Trim().ToLowerInvariant();
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(options.DefaultTenant))
|
||||
{
|
||||
tenant = options.DefaultTenant.Trim().ToLowerInvariant();
|
||||
}
|
||||
else
|
||||
{
|
||||
problem = Results.BadRequest(new
|
||||
{
|
||||
error = new { code = "ERR_TENANT", message = "X-Stella-Tenant header is required" }
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string EncodeCursor(DateTime timestamp, string id)
|
||||
{
|
||||
var raw = $"{timestamp:O}|{id}";
|
||||
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(raw));
|
||||
}
|
||||
}
|
||||
|
||||
// Additional response DTOs for observation detail
|
||||
public sealed record VexObservationUpstreamResponse(
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("upstreamId")] string UpstreamId,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("documentVersion")] string? DocumentVersion,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("fetchedAt")] DateTimeOffset FetchedAt,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("receivedAt")] DateTimeOffset ReceivedAt,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("contentHash")] string ContentHash,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("signature")] VexObservationSignatureResponse? Signature);
|
||||
|
||||
public sealed record VexObservationContentResponse(
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("format")] string Format,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("specVersion")] string? SpecVersion);
|
||||
|
||||
public sealed record VexObservationStatementItem(
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("vulnerabilityId")] string VulnerabilityId,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("productKey")] string ProductKey,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("status")] string Status,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("lastObserved")] DateTimeOffset? LastObserved,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("locator")] string? Locator,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("justification")] string? Justification,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("introducedVersion")] string? IntroducedVersion,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("fixedVersion")] string? FixedVersion);
|
||||
|
||||
public sealed record VexObservationLinksetResponse(
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("aliases")] IReadOnlyList<string> Aliases,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("purls")] IReadOnlyList<string> Purls,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("cpes")] IReadOnlyList<string> Cpes,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("references")] IReadOnlyList<VexObservationReferenceItem> References);
|
||||
|
||||
public sealed record VexObservationReferenceItem(
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("type")] string Type,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("url")] string Url);
|
||||
|
||||
public sealed record VexObservationDetailResponse(
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("observationId")] string ObservationId,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("tenant")] string Tenant,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("providerId")] string ProviderId,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("streamId")] string StreamId,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("upstream")] VexObservationUpstreamResponse Upstream,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("content")] VexObservationContentResponse Content,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("statements")] IReadOnlyList<VexObservationStatementItem> Statements,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("linkset")] VexObservationLinksetResponse Linkset,
|
||||
[property: System.Text.Json.Serialization.JsonPropertyName("createdAt")] DateTimeOffset CreatedAt);
|
||||
@@ -66,6 +66,7 @@ internal static class TelemetryExtensions
|
||||
metrics
|
||||
.AddMeter(IngestionTelemetry.MeterName)
|
||||
.AddMeter(EvidenceTelemetry.MeterName)
|
||||
.AddMeter(LinksetTelemetry.MeterName)
|
||||
.AddAspNetCoreInstrumentation()
|
||||
.AddHttpClientInstrumentation()
|
||||
.AddRuntimeInstrumentation();
|
||||
|
||||
@@ -76,6 +76,14 @@ services.AddRedHatCsafConnector();
|
||||
services.Configure<MirrorDistributionOptions>(configuration.GetSection(MirrorDistributionOptions.SectionName));
|
||||
services.AddSingleton<MirrorRateLimiter>();
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
|
||||
// CRYPTO-90-001: Crypto provider abstraction for pluggable hashing algorithms (GOST/SM support)
|
||||
services.AddSingleton<IVexHashingService>(sp =>
|
||||
{
|
||||
// When ICryptoProviderRegistry is available, use it for pluggable algorithms
|
||||
var registry = sp.GetService<StellaOps.Cryptography.ICryptoProviderRegistry>();
|
||||
return new VexHashingService(registry);
|
||||
});
|
||||
services.AddSingleton<IVexObservationProjectionService, VexObservationProjectionService>();
|
||||
services.AddScoped<IVexObservationQueryService, VexObservationQueryService>();
|
||||
|
||||
@@ -387,6 +395,471 @@ app.MapGet("/openapi/excititor.json", () =>
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
// WEB-OBS-53-001: Evidence API endpoints
|
||||
["/evidence/vex/list"] = new
|
||||
{
|
||||
get = new
|
||||
{
|
||||
summary = "List VEX evidence exports",
|
||||
parameters = new object[]
|
||||
{
|
||||
new { name = "X-Stella-Tenant", @in = "header", schema = new { type = "string" }, required = false },
|
||||
new { name = "limit", @in = "query", schema = new { type = "integer", minimum = 1, maximum = 100 }, required = false },
|
||||
new { name = "cursor", @in = "query", schema = new { type = "string" }, required = false }
|
||||
},
|
||||
responses = new Dictionary<string, object>
|
||||
{
|
||||
["200"] = new
|
||||
{
|
||||
description = "Evidence list response",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
examples = new Dictionary<string, object>
|
||||
{
|
||||
["evidence-list"] = new
|
||||
{
|
||||
value = new
|
||||
{
|
||||
items = new[] {
|
||||
new {
|
||||
bundleId = "vex-bundle-2025-11-24-001",
|
||||
tenant = "acme",
|
||||
format = "openvex",
|
||||
createdAt = "2025-11-24T00:00:00Z",
|
||||
itemCount = 42,
|
||||
merkleRoot = "sha256:abc123...",
|
||||
sealed_ = false
|
||||
}
|
||||
},
|
||||
nextCursor = (string?)null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["/evidence/vex/bundle/{bundleId}"] = new
|
||||
{
|
||||
get = new
|
||||
{
|
||||
summary = "Get VEX evidence bundle details",
|
||||
parameters = new object[]
|
||||
{
|
||||
new { name = "bundleId", @in = "path", schema = new { type = "string" }, required = true },
|
||||
new { name = "X-Stella-Tenant", @in = "header", schema = new { type = "string" }, required = false }
|
||||
},
|
||||
responses = new Dictionary<string, object>
|
||||
{
|
||||
["200"] = new
|
||||
{
|
||||
description = "Bundle detail response",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
examples = new Dictionary<string, object>
|
||||
{
|
||||
["bundle-detail"] = new
|
||||
{
|
||||
value = new
|
||||
{
|
||||
bundleId = "vex-bundle-2025-11-24-001",
|
||||
tenant = "acme",
|
||||
format = "openvex",
|
||||
specVersion = "0.2.0",
|
||||
createdAt = "2025-11-24T00:00:00Z",
|
||||
itemCount = 42,
|
||||
merkleRoot = "sha256:abc123...",
|
||||
sealed_ = false,
|
||||
metadata = new { source = "excititor" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["404"] = new
|
||||
{
|
||||
description = "Bundle not found",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
schema = new { @ref = "#/components/schemas/Error" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["/evidence/vex/lookup"] = new
|
||||
{
|
||||
get = new
|
||||
{
|
||||
summary = "Lookup evidence for vulnerability/product pair",
|
||||
parameters = new object[]
|
||||
{
|
||||
new { name = "vulnerabilityId", @in = "query", schema = new { type = "string" }, required = true, example = "CVE-2024-12345" },
|
||||
new { name = "productKey", @in = "query", schema = new { type = "string" }, required = true, example = "pkg:npm/lodash@4.17.21" },
|
||||
new { name = "X-Stella-Tenant", @in = "header", schema = new { type = "string" }, required = false }
|
||||
},
|
||||
responses = new Dictionary<string, object>
|
||||
{
|
||||
["200"] = new
|
||||
{
|
||||
description = "Evidence lookup response",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
examples = new Dictionary<string, object>
|
||||
{
|
||||
["lookup-result"] = new
|
||||
{
|
||||
value = new
|
||||
{
|
||||
vulnerabilityId = "CVE-2024-12345",
|
||||
productKey = "pkg:npm/lodash@4.17.21",
|
||||
evidence = new[] {
|
||||
new { bundleId = "vex-bundle-001", observationId = "obs-001" }
|
||||
},
|
||||
queriedAt = "2025-11-24T12:00:00Z"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
// WEB-OBS-54-001: Attestation API endpoints
|
||||
["/attestations/vex/list"] = new
|
||||
{
|
||||
get = new
|
||||
{
|
||||
summary = "List VEX attestations",
|
||||
parameters = new object[]
|
||||
{
|
||||
new { name = "limit", @in = "query", schema = new { type = "integer", minimum = 1, maximum = 200 }, required = false },
|
||||
new { name = "cursor", @in = "query", schema = new { type = "string" }, required = false },
|
||||
new { name = "vulnerabilityId", @in = "query", schema = new { type = "string" }, required = false },
|
||||
new { name = "productKey", @in = "query", schema = new { type = "string" }, required = false },
|
||||
new { name = "X-Stella-Tenant", @in = "header", schema = new { type = "string" }, required = false }
|
||||
},
|
||||
responses = new Dictionary<string, object>
|
||||
{
|
||||
["200"] = new
|
||||
{
|
||||
description = "Attestation list response",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
examples = new Dictionary<string, object>
|
||||
{
|
||||
["attestation-list"] = new
|
||||
{
|
||||
value = new
|
||||
{
|
||||
items = new[] {
|
||||
new {
|
||||
attestationId = "att-2025-001",
|
||||
tenant = "acme",
|
||||
createdAt = "2025-11-24T00:00:00Z",
|
||||
predicateType = "https://in-toto.io/attestation/v1",
|
||||
subjectDigest = "sha256:abc123...",
|
||||
valid = true,
|
||||
builderId = "excititor:redhat"
|
||||
}
|
||||
},
|
||||
nextCursor = (string?)null,
|
||||
hasMore = false,
|
||||
count = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["/attestations/vex/{attestationId}"] = new
|
||||
{
|
||||
get = new
|
||||
{
|
||||
summary = "Get VEX attestation details with DSSE verification state",
|
||||
parameters = new object[]
|
||||
{
|
||||
new { name = "attestationId", @in = "path", schema = new { type = "string" }, required = true },
|
||||
new { name = "X-Stella-Tenant", @in = "header", schema = new { type = "string" }, required = false }
|
||||
},
|
||||
responses = new Dictionary<string, object>
|
||||
{
|
||||
["200"] = new
|
||||
{
|
||||
description = "Attestation detail response with chain-of-custody",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
examples = new Dictionary<string, object>
|
||||
{
|
||||
["attestation-detail"] = new
|
||||
{
|
||||
value = new
|
||||
{
|
||||
attestationId = "att-2025-001",
|
||||
tenant = "acme",
|
||||
createdAt = "2025-11-24T00:00:00Z",
|
||||
predicateType = "https://in-toto.io/attestation/v1",
|
||||
subject = new { digest = "sha256:abc123...", name = "CVE-2024-12345/pkg:npm/lodash@4.17.21" },
|
||||
builder = new { id = "excititor:redhat", builderId = "excititor:redhat" },
|
||||
verification = new { valid = true, verifiedAt = "2025-11-24T00:00:00Z", signatureType = "dsse" },
|
||||
chainOfCustody = new[] {
|
||||
new { step = 1, actor = "excititor:redhat", action = "created", timestamp = "2025-11-24T00:00:00Z" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["404"] = new
|
||||
{
|
||||
description = "Attestation not found",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
schema = new { @ref = "#/components/schemas/Error" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["/attestations/vex/lookup"] = new
|
||||
{
|
||||
get = new
|
||||
{
|
||||
summary = "Lookup attestations by linkset or observation",
|
||||
parameters = new object[]
|
||||
{
|
||||
new { name = "linksetId", @in = "query", schema = new { type = "string" }, required = false },
|
||||
new { name = "observationId", @in = "query", schema = new { type = "string" }, required = false },
|
||||
new { name = "limit", @in = "query", schema = new { type = "integer", minimum = 1, maximum = 100 }, required = false },
|
||||
new { name = "X-Stella-Tenant", @in = "header", schema = new { type = "string" }, required = false }
|
||||
},
|
||||
responses = new Dictionary<string, object>
|
||||
{
|
||||
["200"] = new
|
||||
{
|
||||
description = "Attestation lookup response",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
examples = new Dictionary<string, object>
|
||||
{
|
||||
["lookup-result"] = new
|
||||
{
|
||||
value = new
|
||||
{
|
||||
subjectDigest = "linkset-001",
|
||||
attestations = new[] {
|
||||
new { attestationId = "att-001", valid = true }
|
||||
},
|
||||
queriedAt = "2025-11-24T12:00:00Z"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["400"] = new
|
||||
{
|
||||
description = "Missing required parameter",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
schema = new { @ref = "#/components/schemas/Error" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
// EXCITITOR-LNM-21-201: Observation API endpoints
|
||||
["/vex/observations"] = new
|
||||
{
|
||||
get = new
|
||||
{
|
||||
summary = "List VEX observations with filters",
|
||||
parameters = new object[]
|
||||
{
|
||||
new { name = "limit", @in = "query", schema = new { type = "integer", minimum = 1, maximum = 100 }, required = false },
|
||||
new { name = "cursor", @in = "query", schema = new { type = "string" }, required = false },
|
||||
new { name = "vulnerabilityId", @in = "query", schema = new { type = "string" }, required = false, example = "CVE-2024-12345" },
|
||||
new { name = "productKey", @in = "query", schema = new { type = "string" }, required = false, example = "pkg:npm/lodash@4.17.21" },
|
||||
new { name = "providerId", @in = "query", schema = new { type = "string" }, required = false, example = "excititor:redhat" },
|
||||
new { name = "X-Stella-Tenant", @in = "header", schema = new { type = "string" }, required = false }
|
||||
},
|
||||
responses = new Dictionary<string, object>
|
||||
{
|
||||
["200"] = new
|
||||
{
|
||||
description = "Observation list response",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
examples = new Dictionary<string, object>
|
||||
{
|
||||
["observation-list"] = new
|
||||
{
|
||||
value = new
|
||||
{
|
||||
items = new[] {
|
||||
new {
|
||||
observationId = "obs-2025-001",
|
||||
tenant = "acme",
|
||||
providerId = "excititor:redhat",
|
||||
vulnerabilityId = "CVE-2024-12345",
|
||||
productKey = "pkg:npm/lodash@4.17.21",
|
||||
status = "not_affected",
|
||||
createdAt = "2025-11-24T00:00:00Z"
|
||||
}
|
||||
},
|
||||
nextCursor = (string?)null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["400"] = new
|
||||
{
|
||||
description = "Missing required filter",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
schema = new { @ref = "#/components/schemas/Error" },
|
||||
examples = new Dictionary<string, object>
|
||||
{
|
||||
["missing-filter"] = new
|
||||
{
|
||||
value = new
|
||||
{
|
||||
error = new
|
||||
{
|
||||
code = "ERR_PARAMS",
|
||||
message = "At least one filter is required: vulnerabilityId+productKey or providerId"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["/vex/observations/{observationId}"] = new
|
||||
{
|
||||
get = new
|
||||
{
|
||||
summary = "Get VEX observation by ID",
|
||||
parameters = new object[]
|
||||
{
|
||||
new { name = "observationId", @in = "path", schema = new { type = "string" }, required = true },
|
||||
new { name = "X-Stella-Tenant", @in = "header", schema = new { type = "string" }, required = false }
|
||||
},
|
||||
responses = new Dictionary<string, object>
|
||||
{
|
||||
["200"] = new
|
||||
{
|
||||
description = "Observation detail response",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
examples = new Dictionary<string, object>
|
||||
{
|
||||
["observation-detail"] = new
|
||||
{
|
||||
value = new
|
||||
{
|
||||
observationId = "obs-2025-001",
|
||||
tenant = "acme",
|
||||
providerId = "excititor:redhat",
|
||||
streamId = "stream-001",
|
||||
upstream = new { upstreamId = "RHSA-2024:001", fetchedAt = "2025-11-24T00:00:00Z" },
|
||||
content = new { format = "csaf", specVersion = "2.0" },
|
||||
statements = new[] {
|
||||
new { vulnerabilityId = "CVE-2024-12345", productKey = "pkg:npm/lodash@4.17.21", status = "not_affected" }
|
||||
},
|
||||
linkset = new { aliases = new[] { "CVE-2024-12345" }, purls = new[] { "pkg:npm/lodash@4.17.21" } },
|
||||
createdAt = "2025-11-24T00:00:00Z"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["404"] = new
|
||||
{
|
||||
description = "Observation not found",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
schema = new { @ref = "#/components/schemas/Error" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
["/vex/observations/count"] = new
|
||||
{
|
||||
get = new
|
||||
{
|
||||
summary = "Get observation count for tenant",
|
||||
parameters = new object[]
|
||||
{
|
||||
new { name = "X-Stella-Tenant", @in = "header", schema = new { type = "string" }, required = false }
|
||||
},
|
||||
responses = new Dictionary<string, object>
|
||||
{
|
||||
["200"] = new
|
||||
{
|
||||
description = "Count response",
|
||||
content = new Dictionary<string, object>
|
||||
{
|
||||
["application/json"] = new
|
||||
{
|
||||
examples = new Dictionary<string, object>
|
||||
{
|
||||
["count"] = new
|
||||
{
|
||||
value = new { count = 1234 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
components = new
|
||||
@@ -451,6 +924,8 @@ app.MapPost("/airgap/v1/vex/import", async (
|
||||
[FromServices] AirgapSignerTrustService trustService,
|
||||
[FromServices] AirgapModeEnforcer modeEnforcer,
|
||||
[FromServices] IAirgapImportStore store,
|
||||
[FromServices] IVexTimelineEventEmitter timelineEmitter,
|
||||
[FromServices] IVexHashingService hashingService,
|
||||
[FromServices] ILoggerFactory loggerFactory,
|
||||
[FromServices] TimeProvider timeProvider,
|
||||
[FromBody] AirgapImportRequest request,
|
||||
@@ -465,6 +940,7 @@ app.MapPost("/airgap/v1/vex/import", async (
|
||||
? (int?)null
|
||||
: (int)Math.Round((nowUtc - request.SignedAt.Value).TotalSeconds);
|
||||
|
||||
var traceId = Activity.Current?.TraceId.ToString();
|
||||
var timeline = new List<AirgapTimelineEntry>();
|
||||
void RecordEvent(string eventType, string? code = null, string? message = null)
|
||||
{
|
||||
@@ -481,6 +957,54 @@ app.MapPost("/airgap/v1/vex/import", async (
|
||||
};
|
||||
timeline.Add(entry);
|
||||
logger.LogInformation("Airgap timeline event {EventType} bundle={BundleId} gen={Gen} tenant={Tenant} code={Code}", eventType, entry.BundleId, entry.MirrorGeneration, tenantId, code);
|
||||
|
||||
// WEB-AIRGAP-58-001: Emit timeline event to persistent store for SSE streaming
|
||||
_ = EmitTimelineEventAsync(eventType, code, message);
|
||||
}
|
||||
|
||||
async Task EmitTimelineEventAsync(string eventType, string? code, string? message)
|
||||
{
|
||||
try
|
||||
{
|
||||
var attributes = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["bundle_id"] = request.BundleId ?? string.Empty,
|
||||
["mirror_generation"] = request.MirrorGeneration ?? string.Empty
|
||||
};
|
||||
if (stalenessSeconds.HasValue)
|
||||
{
|
||||
attributes["staleness_seconds"] = stalenessSeconds.Value.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
if (!string.IsNullOrEmpty(code))
|
||||
{
|
||||
attributes["error_code"] = code;
|
||||
}
|
||||
if (!string.IsNullOrEmpty(message))
|
||||
{
|
||||
attributes["message"] = message;
|
||||
}
|
||||
|
||||
var eventId = $"airgap-{request.BundleId}-{request.MirrorGeneration}-{nowUtc:yyyyMMddHHmmssfff}";
|
||||
var streamId = $"airgap:{request.BundleId}:{request.MirrorGeneration}";
|
||||
var evt = new TimelineEvent(
|
||||
eventId,
|
||||
tenantId,
|
||||
"airgap-import",
|
||||
streamId,
|
||||
eventType,
|
||||
traceId ?? Guid.NewGuid().ToString("N"),
|
||||
justificationSummary: message ?? string.Empty,
|
||||
nowUtc,
|
||||
evidenceHash: null,
|
||||
payloadHash: request.PayloadHash,
|
||||
attributes.ToImmutableDictionary());
|
||||
|
||||
await timelineEmitter.EmitAsync(evt, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to emit timeline event {EventType} for bundle {BundleId}", eventType, request.BundleId);
|
||||
}
|
||||
}
|
||||
|
||||
RecordEvent("airgap.import.started");
|
||||
@@ -528,7 +1052,8 @@ app.MapPost("/airgap/v1/vex/import", async (
|
||||
|
||||
var manifestPath = $"mirror/{request.BundleId}/{request.MirrorGeneration}/manifest.json";
|
||||
var evidenceLockerPath = $"evidence/{request.BundleId}/{request.MirrorGeneration}/bundle.ndjson";
|
||||
var manifestHash = ComputeSha256($"{request.BundleId}:{request.MirrorGeneration}:{request.PayloadHash}");
|
||||
// CRYPTO-90-001: Use IVexHashingService for pluggable crypto algorithms
|
||||
var manifestHash = hashingService.ComputeHash($"{request.BundleId}:{request.MirrorGeneration}:{request.PayloadHash}");
|
||||
|
||||
RecordEvent("airgap.import.completed");
|
||||
|
||||
@@ -578,12 +1103,7 @@ app.MapPost("/airgap/v1/vex/import", async (
|
||||
});
|
||||
});
|
||||
|
||||
static string ComputeSha256(string value)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(value);
|
||||
var hash = System.Security.Cryptography.SHA256.HashData(bytes);
|
||||
return "sha256:" + Convert.ToHexString(hash).ToLowerInvariant();
|
||||
}
|
||||
// CRYPTO-90-001: ComputeSha256 removed - now using IVexHashingService for pluggable crypto
|
||||
|
||||
app.MapPost("/v1/attestations/verify", async (
|
||||
[FromServices] IVexAttestationClient attestationClient,
|
||||
@@ -1666,10 +2186,13 @@ app.MapGet("/obs/excititor/health", async (
|
||||
app.MapGet("/obs/excititor/timeline", async (
|
||||
HttpContext context,
|
||||
IOptions<VexMongoStorageOptions> storageOptions,
|
||||
[FromServices] IVexTimelineEventStore timelineStore,
|
||||
TimeProvider timeProvider,
|
||||
ILoggerFactory loggerFactory,
|
||||
[FromQuery] string? cursor,
|
||||
[FromQuery] int? limit,
|
||||
[FromQuery] string? eventType,
|
||||
[FromQuery] string? providerId,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
if (!TryResolveTenant(context, storageOptions.Value, requireHeader: true, out var tenant, out var tenantError))
|
||||
@@ -1680,44 +2203,71 @@ app.MapGet("/obs/excititor/timeline", async (
|
||||
var logger = loggerFactory.CreateLogger("ExcititorTimeline");
|
||||
var take = Math.Clamp(limit.GetValueOrDefault(10), 1, 100);
|
||||
|
||||
var startId = 0;
|
||||
// Parse cursor as ISO-8601 timestamp or Last-Event-ID header
|
||||
DateTimeOffset? cursorTimestamp = null;
|
||||
var candidateCursor = cursor ?? context.Request.Headers["Last-Event-ID"].FirstOrDefault();
|
||||
if (!string.IsNullOrWhiteSpace(candidateCursor) && !int.TryParse(candidateCursor, NumberStyles.Integer, CultureInfo.InvariantCulture, out startId))
|
||||
if (!string.IsNullOrWhiteSpace(candidateCursor))
|
||||
{
|
||||
return Results.BadRequest(new { error = "cursor must be integer" });
|
||||
if (DateTimeOffset.TryParse(candidateCursor, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var parsed))
|
||||
{
|
||||
cursorTimestamp = parsed;
|
||||
}
|
||||
else
|
||||
{
|
||||
return Results.BadRequest(new { error = new { code = "ERR_CURSOR", message = "cursor must be ISO-8601 timestamp" } });
|
||||
}
|
||||
}
|
||||
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
context.Response.Headers["X-Accel-Buffering"] = "no";
|
||||
context.Response.Headers["Link"] = "</openapi/excititor.json>; rel=\"describedby\"; type=\"application/json\"";
|
||||
context.Response.ContentType = "text/event-stream";
|
||||
await context.Response.WriteAsync("retry: 5000\n\n", cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Fetch real timeline events from the store
|
||||
IReadOnlyList<TimelineEvent> events;
|
||||
var now = timeProvider.GetUtcNow();
|
||||
var events = Enumerable.Range(startId, take)
|
||||
.Select(id => new ExcititorTimelineEvent(
|
||||
Type: "evidence.update",
|
||||
Tenant: tenant,
|
||||
Source: "vex-runtime",
|
||||
Count: 0,
|
||||
Errors: 0,
|
||||
TraceId: null,
|
||||
OccurredAt: now.ToString("O", CultureInfo.InvariantCulture)))
|
||||
.ToList();
|
||||
|
||||
foreach (var (evt, idx) in events.Select((e, i) => (e, i)))
|
||||
if (!string.IsNullOrWhiteSpace(eventType))
|
||||
{
|
||||
events = await timelineStore.FindByEventTypeAsync(tenant, eventType, take, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(providerId))
|
||||
{
|
||||
events = await timelineStore.FindByProviderAsync(tenant, providerId, take, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (cursorTimestamp.HasValue)
|
||||
{
|
||||
// Get events after the cursor timestamp
|
||||
events = await timelineStore.FindByTimeRangeAsync(tenant, cursorTimestamp.Value, now, take, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
events = await timelineStore.GetRecentAsync(tenant, take, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var evt in events)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var id = startId + idx;
|
||||
await context.Response.WriteAsync($"id: {id}\n", cancellationToken).ConfigureAwait(false);
|
||||
await context.Response.WriteAsync($"event: {evt.Type}\n", cancellationToken).ConfigureAwait(false);
|
||||
await context.Response.WriteAsync($"data: {JsonSerializer.Serialize(evt)}\n\n", cancellationToken).ConfigureAwait(false);
|
||||
var sseEvent = new ExcititorTimelineEvent(
|
||||
Type: evt.EventType,
|
||||
Tenant: evt.Tenant,
|
||||
Source: evt.ProviderId,
|
||||
Count: evt.Attributes.TryGetValue("observation_count", out var countStr) && int.TryParse(countStr, out var count) ? count : 1,
|
||||
Errors: evt.Attributes.TryGetValue("error_count", out var errStr) && int.TryParse(errStr, out var errCount) ? errCount : 0,
|
||||
TraceId: evt.TraceId,
|
||||
OccurredAt: evt.CreatedAt.ToString("O", CultureInfo.InvariantCulture));
|
||||
|
||||
await context.Response.WriteAsync($"id: {evt.CreatedAt:O}\n", cancellationToken).ConfigureAwait(false);
|
||||
await context.Response.WriteAsync($"event: {evt.EventType}\n", cancellationToken).ConfigureAwait(false);
|
||||
await context.Response.WriteAsync($"data: {JsonSerializer.Serialize(sseEvent)}\n\n", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await context.Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var nextCursor = startId + events.Count;
|
||||
context.Response.Headers["X-Next-Cursor"] = nextCursor.ToString(CultureInfo.InvariantCulture);
|
||||
logger.LogInformation("obs excititor timeline emitted {Count} events for tenant {Tenant} start {Start} next {Next}", events.Count, tenant, startId, nextCursor);
|
||||
var nextCursor = events.Count > 0 ? events[^1].CreatedAt.ToString("O", CultureInfo.InvariantCulture) : now.ToString("O", CultureInfo.InvariantCulture);
|
||||
context.Response.Headers["X-Next-Cursor"] = nextCursor;
|
||||
logger.LogInformation("obs excititor timeline emitted {Count} events for tenant {Tenant} cursor {Cursor} next {Next}", events.Count, tenant, candidateCursor, nextCursor);
|
||||
|
||||
return Results.Empty;
|
||||
}).WithName("GetExcititorTimeline");
|
||||
@@ -1726,11 +2276,13 @@ IngestEndpoints.MapIngestEndpoints(app);
|
||||
ResolveEndpoint.MapResolveEndpoint(app);
|
||||
MirrorEndpoints.MapMirrorEndpoints(app);
|
||||
|
||||
app.MapGet("/v1/vex/observations", async (HttpContext _, CancellationToken __) =>
|
||||
Results.StatusCode(StatusCodes.Status501NotImplemented));
|
||||
// Evidence and Attestation APIs (WEB-OBS-53-001, WEB-OBS-54-001)
|
||||
EvidenceEndpoints.MapEvidenceEndpoints(app);
|
||||
AttestationEndpoints.MapAttestationEndpoints(app);
|
||||
|
||||
app.MapGet("/v1/vex/linksets", async (HttpContext _, CancellationToken __) =>
|
||||
Results.StatusCode(StatusCodes.Status501NotImplemented));
|
||||
// Observation and Linkset APIs (EXCITITOR-LNM-21-201, EXCITITOR-LNM-21-202)
|
||||
ObservationEndpoints.MapObservationEndpoints(app);
|
||||
LinksetEndpoints.MapLinksetEndpoints(app);
|
||||
|
||||
app.Run();
|
||||
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using StellaOps.Cryptography;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service interface for hashing operations in Excititor (CRYPTO-90-001).
|
||||
/// Abstracts hashing implementation to support GOST/SM algorithms via ICryptoProviderRegistry.
|
||||
/// </summary>
|
||||
public interface IVexHashingService
|
||||
{
|
||||
/// <summary>
|
||||
/// Compute hash of a UTF-8 encoded string.
|
||||
/// </summary>
|
||||
string ComputeHash(string value, string algorithm = "sha256");
|
||||
|
||||
/// <summary>
|
||||
/// Compute hash of raw bytes.
|
||||
/// </summary>
|
||||
string ComputeHash(ReadOnlySpan<byte> data, string algorithm = "sha256");
|
||||
|
||||
/// <summary>
|
||||
/// Try to compute hash of raw bytes with stack-allocated buffer optimization.
|
||||
/// </summary>
|
||||
bool TryComputeHash(ReadOnlySpan<byte> data, Span<byte> destination, out int bytesWritten, string algorithm = "sha256");
|
||||
|
||||
/// <summary>
|
||||
/// Format a hash digest with algorithm prefix.
|
||||
/// </summary>
|
||||
string FormatDigest(string algorithm, ReadOnlySpan<byte> digest);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Default implementation of <see cref="IVexHashingService"/> that uses ICryptoProviderRegistry
|
||||
/// when available, falling back to System.Security.Cryptography for SHA-256.
|
||||
/// </summary>
|
||||
public sealed class VexHashingService : IVexHashingService
|
||||
{
|
||||
private readonly ICryptoProviderRegistry? _registry;
|
||||
|
||||
public VexHashingService(ICryptoProviderRegistry? registry = null)
|
||||
{
|
||||
_registry = registry;
|
||||
}
|
||||
|
||||
public string ComputeHash(string value, string algorithm = "sha256")
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var bytes = Encoding.UTF8.GetBytes(value);
|
||||
return ComputeHash(bytes, algorithm);
|
||||
}
|
||||
|
||||
public string ComputeHash(ReadOnlySpan<byte> data, string algorithm = "sha256")
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[64]; // Large enough for SHA-512 and GOST
|
||||
if (!TryComputeHash(data, buffer, out var written, algorithm))
|
||||
{
|
||||
throw new InvalidOperationException($"Failed to compute {algorithm} hash.");
|
||||
}
|
||||
|
||||
return FormatDigest(algorithm, buffer[..written]);
|
||||
}
|
||||
|
||||
public bool TryComputeHash(ReadOnlySpan<byte> data, Span<byte> destination, out int bytesWritten, string algorithm = "sha256")
|
||||
{
|
||||
bytesWritten = 0;
|
||||
|
||||
// Try to use crypto provider registry first for pluggable algorithms
|
||||
if (_registry is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var resolution = _registry.ResolveHasher(algorithm);
|
||||
var hasher = resolution.Hasher;
|
||||
var result = hasher.ComputeHash(data);
|
||||
if (result.Length <= destination.Length)
|
||||
{
|
||||
result.CopyTo(destination);
|
||||
bytesWritten = result.Length;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Fall through to built-in implementation
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to System.Security.Cryptography for standard algorithms
|
||||
var normalizedAlgorithm = algorithm.ToLowerInvariant().Replace("-", string.Empty);
|
||||
return normalizedAlgorithm switch
|
||||
{
|
||||
"sha256" => SHA256.TryHashData(data, destination, out bytesWritten),
|
||||
"sha384" => SHA384.TryHashData(data, destination, out bytesWritten),
|
||||
"sha512" => SHA512.TryHashData(data, destination, out bytesWritten),
|
||||
_ => throw new NotSupportedException($"Unsupported hash algorithm: {algorithm}")
|
||||
};
|
||||
}
|
||||
|
||||
public string FormatDigest(string algorithm, ReadOnlySpan<byte> digest)
|
||||
{
|
||||
var normalizedAlgorithm = algorithm.ToLowerInvariant().Replace("-", string.Empty);
|
||||
var hexDigest = Convert.ToHexString(digest).ToLowerInvariant();
|
||||
return $"{normalizedAlgorithm}:{hexDigest}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Metrics;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// Telemetry metrics for VEX linkset and observation store operations (EXCITITOR-OBS-51-001).
|
||||
/// Tracks ingest latency, scope resolution success, conflict rate, and signature verification
|
||||
/// to support SLO burn alerts for AOC "evidence freshness" mission.
|
||||
/// </summary>
|
||||
internal static class LinksetTelemetry
|
||||
{
|
||||
public const string MeterName = "StellaOps.Excititor.WebService.Linksets";
|
||||
|
||||
private static readonly Meter Meter = new(MeterName);
|
||||
|
||||
// Ingest latency metrics
|
||||
private static readonly Histogram<double> IngestLatencyHistogram =
|
||||
Meter.CreateHistogram<double>(
|
||||
"excititor.vex.ingest.latency_seconds",
|
||||
unit: "s",
|
||||
description: "Latency distribution for VEX observation and linkset store operations.");
|
||||
|
||||
private static readonly Counter<long> IngestOperationCounter =
|
||||
Meter.CreateCounter<long>(
|
||||
"excititor.vex.ingest.operations_total",
|
||||
unit: "operations",
|
||||
description: "Total count of VEX ingest operations by outcome.");
|
||||
|
||||
// Scope resolution metrics
|
||||
private static readonly Counter<long> ScopeResolutionCounter =
|
||||
Meter.CreateCounter<long>(
|
||||
"excititor.vex.scope.resolution_total",
|
||||
unit: "resolutions",
|
||||
description: "Count of scope resolution attempts by outcome (success/failure).");
|
||||
|
||||
private static readonly Histogram<int> ScopeMatchCountHistogram =
|
||||
Meter.CreateHistogram<int>(
|
||||
"excititor.vex.scope.match_count",
|
||||
unit: "matches",
|
||||
description: "Distribution of matched scopes per resolution request.");
|
||||
|
||||
// Conflict/disagreement metrics
|
||||
private static readonly Counter<long> LinksetConflictCounter =
|
||||
Meter.CreateCounter<long>(
|
||||
"excititor.vex.linkset.conflicts_total",
|
||||
unit: "conflicts",
|
||||
description: "Total count of linksets with provider disagreements detected.");
|
||||
|
||||
private static readonly Histogram<int> DisagreementCountHistogram =
|
||||
Meter.CreateHistogram<int>(
|
||||
"excititor.vex.linkset.disagreement_count",
|
||||
unit: "disagreements",
|
||||
description: "Distribution of disagreement count per linkset.");
|
||||
|
||||
private static readonly Counter<long> DisagreementByStatusCounter =
|
||||
Meter.CreateCounter<long>(
|
||||
"excititor.vex.linkset.disagreement_by_status",
|
||||
unit: "disagreements",
|
||||
description: "Disagreement counts broken down by conflicting status values.");
|
||||
|
||||
// Observation store metrics
|
||||
private static readonly Counter<long> ObservationStoreCounter =
|
||||
Meter.CreateCounter<long>(
|
||||
"excititor.vex.observation.store_operations_total",
|
||||
unit: "operations",
|
||||
description: "Total observation store operations by type and outcome.");
|
||||
|
||||
private static readonly Histogram<int> ObservationBatchSizeHistogram =
|
||||
Meter.CreateHistogram<int>(
|
||||
"excititor.vex.observation.batch_size",
|
||||
unit: "observations",
|
||||
description: "Distribution of observation batch sizes for store operations.");
|
||||
|
||||
// Linkset store metrics
|
||||
private static readonly Counter<long> LinksetStoreCounter =
|
||||
Meter.CreateCounter<long>(
|
||||
"excititor.vex.linkset.store_operations_total",
|
||||
unit: "operations",
|
||||
description: "Total linkset store operations by type and outcome.");
|
||||
|
||||
// Confidence metrics
|
||||
private static readonly Histogram<double> LinksetConfidenceHistogram =
|
||||
Meter.CreateHistogram<double>(
|
||||
"excititor.vex.linkset.confidence_score",
|
||||
unit: "score",
|
||||
description: "Distribution of linkset confidence scores (0.0-1.0).");
|
||||
|
||||
/// <summary>
|
||||
/// Records latency for a VEX ingest operation.
|
||||
/// </summary>
|
||||
public static void RecordIngestLatency(string? tenant, string operation, string outcome, double latencySeconds)
|
||||
{
|
||||
var tags = BuildBaseTags(tenant, operation, outcome);
|
||||
IngestLatencyHistogram.Record(latencySeconds, tags);
|
||||
IngestOperationCounter.Add(1, tags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records a scope resolution attempt and its outcome.
|
||||
/// </summary>
|
||||
public static void RecordScopeResolution(string? tenant, string outcome, int matchCount = 0)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var tags = new[]
|
||||
{
|
||||
new KeyValuePair<string, object?>("tenant", normalizedTenant),
|
||||
new KeyValuePair<string, object?>("outcome", outcome),
|
||||
};
|
||||
|
||||
ScopeResolutionCounter.Add(1, tags);
|
||||
|
||||
if (string.Equals(outcome, "success", StringComparison.OrdinalIgnoreCase) && matchCount > 0)
|
||||
{
|
||||
ScopeMatchCountHistogram.Record(matchCount, tags);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records conflict detection for a linkset.
|
||||
/// </summary>
|
||||
public static void RecordLinksetConflict(string? tenant, bool hasConflicts, int disagreementCount = 0)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
|
||||
if (hasConflicts)
|
||||
{
|
||||
var conflictTags = new[]
|
||||
{
|
||||
new KeyValuePair<string, object?>("tenant", normalizedTenant),
|
||||
};
|
||||
LinksetConflictCounter.Add(1, conflictTags);
|
||||
|
||||
if (disagreementCount > 0)
|
||||
{
|
||||
DisagreementCountHistogram.Record(disagreementCount, conflictTags);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records a linkset with detailed disagreement breakdown.
|
||||
/// </summary>
|
||||
public static void RecordLinksetDisagreements(string? tenant, VexLinkset linkset)
|
||||
{
|
||||
if (linkset is null || !linkset.HasConflicts)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
RecordLinksetConflict(normalizedTenant, true, linkset.Disagreements.Length);
|
||||
|
||||
// Record disagreements by status
|
||||
foreach (var disagreement in linkset.Disagreements)
|
||||
{
|
||||
var statusTags = new[]
|
||||
{
|
||||
new KeyValuePair<string, object?>("tenant", normalizedTenant),
|
||||
new KeyValuePair<string, object?>("status", disagreement.Status.ToLowerInvariant()),
|
||||
new KeyValuePair<string, object?>("provider", disagreement.ProviderId),
|
||||
};
|
||||
DisagreementByStatusCounter.Add(1, statusTags);
|
||||
}
|
||||
|
||||
// Record confidence score
|
||||
var confidenceScore = linkset.Confidence switch
|
||||
{
|
||||
VexLinksetConfidence.High => 0.9,
|
||||
VexLinksetConfidence.Medium => 0.7,
|
||||
VexLinksetConfidence.Low => 0.4,
|
||||
_ => 0.5
|
||||
};
|
||||
|
||||
var confidenceTags = new[]
|
||||
{
|
||||
new KeyValuePair<string, object?>("tenant", normalizedTenant),
|
||||
new KeyValuePair<string, object?>("has_conflicts", linkset.HasConflicts),
|
||||
};
|
||||
LinksetConfidenceHistogram.Record(confidenceScore, confidenceTags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records an observation store operation.
|
||||
/// </summary>
|
||||
public static void RecordObservationStoreOperation(
|
||||
string? tenant,
|
||||
string operation,
|
||||
string outcome,
|
||||
int batchSize = 1)
|
||||
{
|
||||
var tags = BuildBaseTags(tenant, operation, outcome);
|
||||
ObservationStoreCounter.Add(1, tags);
|
||||
|
||||
if (batchSize > 0 && string.Equals(outcome, "success", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var batchTags = new[]
|
||||
{
|
||||
new KeyValuePair<string, object?>("tenant", NormalizeTenant(tenant)),
|
||||
new KeyValuePair<string, object?>("operation", operation),
|
||||
};
|
||||
ObservationBatchSizeHistogram.Record(batchSize, batchTags);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records a linkset store operation.
|
||||
/// </summary>
|
||||
public static void RecordLinksetStoreOperation(string? tenant, string operation, string outcome)
|
||||
{
|
||||
var tags = BuildBaseTags(tenant, operation, outcome);
|
||||
LinksetStoreCounter.Add(1, tags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records linkset confidence score distribution.
|
||||
/// </summary>
|
||||
public static void RecordLinksetConfidence(string? tenant, VexLinksetConfidence confidence, bool hasConflicts)
|
||||
{
|
||||
var score = confidence switch
|
||||
{
|
||||
VexLinksetConfidence.High => 0.9,
|
||||
VexLinksetConfidence.Medium => 0.7,
|
||||
VexLinksetConfidence.Low => 0.4,
|
||||
_ => 0.5
|
||||
};
|
||||
|
||||
var tags = new[]
|
||||
{
|
||||
new KeyValuePair<string, object?>("tenant", NormalizeTenant(tenant)),
|
||||
new KeyValuePair<string, object?>("has_conflicts", hasConflicts),
|
||||
new KeyValuePair<string, object?>("confidence_level", confidence.ToString().ToLowerInvariant()),
|
||||
};
|
||||
|
||||
LinksetConfidenceHistogram.Record(score, tags);
|
||||
}
|
||||
|
||||
private static string NormalizeTenant(string? tenant)
|
||||
=> string.IsNullOrWhiteSpace(tenant) ? "default" : tenant;
|
||||
|
||||
private static KeyValuePair<string, object?>[] BuildBaseTags(string? tenant, string operation, string outcome)
|
||||
=> new[]
|
||||
{
|
||||
new KeyValuePair<string, object?>("tenant", NormalizeTenant(tenant)),
|
||||
new KeyValuePair<string, object?>("operation", operation),
|
||||
new KeyValuePair<string, object?>("outcome", outcome),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
|
||||
namespace StellaOps.Excititor.Worker.Options;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration options for the orchestrator worker SDK integration.
|
||||
/// </summary>
|
||||
public sealed class VexWorkerOrchestratorOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether orchestrator integration is enabled.
|
||||
/// </summary>
|
||||
public bool Enabled { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Interval between heartbeat emissions during job execution.
|
||||
/// </summary>
|
||||
public TimeSpan HeartbeatInterval { get; set; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>
|
||||
/// Minimum heartbeat interval (safety floor).
|
||||
/// </summary>
|
||||
public TimeSpan MinHeartbeatInterval { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>
|
||||
/// Maximum heartbeat interval (safety cap).
|
||||
/// </summary>
|
||||
public TimeSpan MaxHeartbeatInterval { get; set; } = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>
|
||||
/// Enable verbose logging for heartbeat/artifact events.
|
||||
/// </summary>
|
||||
public bool EnableVerboseLogging { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Maximum number of artifact hashes to retain in state.
|
||||
/// </summary>
|
||||
public int MaxArtifactHashes { get; set; } = 1000;
|
||||
|
||||
/// <summary>
|
||||
/// Default tenant for worker jobs when not specified.
|
||||
/// </summary>
|
||||
public string DefaultTenant { get; set; } = "default";
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Excititor.Core.Orchestration;
|
||||
using StellaOps.Excititor.Worker.Options;
|
||||
|
||||
namespace StellaOps.Excititor.Worker.Orchestration;
|
||||
|
||||
/// <summary>
|
||||
/// Background service that emits periodic heartbeats during job execution.
|
||||
/// </summary>
|
||||
internal sealed class VexWorkerHeartbeatService
|
||||
{
|
||||
private readonly IVexWorkerOrchestratorClient _orchestratorClient;
|
||||
private readonly IOptions<VexWorkerOrchestratorOptions> _options;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly ILogger<VexWorkerHeartbeatService> _logger;
|
||||
|
||||
public VexWorkerHeartbeatService(
|
||||
IVexWorkerOrchestratorClient orchestratorClient,
|
||||
IOptions<VexWorkerOrchestratorOptions> options,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<VexWorkerHeartbeatService> logger)
|
||||
{
|
||||
_orchestratorClient = orchestratorClient ?? throw new ArgumentNullException(nameof(orchestratorClient));
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the heartbeat loop for the given job context.
|
||||
/// Call this in a background task while the job is running.
|
||||
/// </summary>
|
||||
public async Task RunAsync(
|
||||
VexWorkerJobContext context,
|
||||
Func<VexWorkerHeartbeatStatus> statusProvider,
|
||||
Func<int?> progressProvider,
|
||||
Func<string?> lastArtifactHashProvider,
|
||||
Func<string?> lastArtifactKindProvider,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(statusProvider);
|
||||
|
||||
if (!_options.Value.Enabled)
|
||||
{
|
||||
_logger.LogDebug("Orchestrator heartbeat service disabled; skipping heartbeat loop.");
|
||||
return;
|
||||
}
|
||||
|
||||
var interval = ComputeInterval();
|
||||
_logger.LogDebug(
|
||||
"Starting heartbeat loop for job {RunId} with interval {Interval}",
|
||||
context.RunId,
|
||||
interval);
|
||||
|
||||
await Task.Yield();
|
||||
|
||||
try
|
||||
{
|
||||
using var timer = new PeriodicTimer(interval);
|
||||
|
||||
// Send initial heartbeat
|
||||
await SendHeartbeatAsync(
|
||||
context,
|
||||
statusProvider(),
|
||||
progressProvider?.Invoke(),
|
||||
lastArtifactHashProvider?.Invoke(),
|
||||
lastArtifactKindProvider?.Invoke(),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
await SendHeartbeatAsync(
|
||||
context,
|
||||
statusProvider(),
|
||||
progressProvider?.Invoke(),
|
||||
lastArtifactHashProvider?.Invoke(),
|
||||
lastArtifactKindProvider?.Invoke(),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogDebug("Heartbeat loop cancelled for job {RunId}", context.RunId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Heartbeat loop error for job {RunId}: {Message}",
|
||||
context.RunId,
|
||||
ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendHeartbeatAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerHeartbeatStatus status,
|
||||
int? progress,
|
||||
string? lastArtifactHash,
|
||||
string? lastArtifactKind,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var heartbeat = new VexWorkerHeartbeat(
|
||||
status,
|
||||
progress,
|
||||
QueueDepth: null,
|
||||
lastArtifactHash,
|
||||
lastArtifactKind,
|
||||
ErrorCode: null,
|
||||
RetryAfterSeconds: null);
|
||||
|
||||
await _orchestratorClient.SendHeartbeatAsync(context, heartbeat, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Failed to send heartbeat for job {RunId}: {Message}",
|
||||
context.RunId,
|
||||
ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private TimeSpan ComputeInterval()
|
||||
{
|
||||
var opts = _options.Value;
|
||||
var interval = opts.HeartbeatInterval;
|
||||
|
||||
if (interval < opts.MinHeartbeatInterval)
|
||||
{
|
||||
interval = opts.MinHeartbeatInterval;
|
||||
}
|
||||
else if (interval > opts.MaxHeartbeatInterval)
|
||||
{
|
||||
interval = opts.MaxHeartbeatInterval;
|
||||
}
|
||||
|
||||
return interval;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Core.Orchestration;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.Worker.Options;
|
||||
|
||||
namespace StellaOps.Excititor.Worker.Orchestration;
|
||||
|
||||
/// <summary>
|
||||
/// Default implementation of <see cref="IVexWorkerOrchestratorClient"/>.
|
||||
/// Stores heartbeats and artifacts locally and emits them to the orchestrator registry when configured.
|
||||
/// </summary>
|
||||
internal sealed class VexWorkerOrchestratorClient : IVexWorkerOrchestratorClient
|
||||
{
|
||||
private readonly IVexConnectorStateRepository _stateRepository;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly IOptions<VexWorkerOrchestratorOptions> _options;
|
||||
private readonly ILogger<VexWorkerOrchestratorClient> _logger;
|
||||
|
||||
public VexWorkerOrchestratorClient(
|
||||
IVexConnectorStateRepository stateRepository,
|
||||
TimeProvider timeProvider,
|
||||
IOptions<VexWorkerOrchestratorOptions> options,
|
||||
ILogger<VexWorkerOrchestratorClient> logger)
|
||||
{
|
||||
_stateRepository = stateRepository ?? throw new ArgumentNullException(nameof(stateRepository));
|
||||
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public ValueTask<VexWorkerJobContext> StartJobAsync(
|
||||
string tenant,
|
||||
string connectorId,
|
||||
string? checkpoint,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var runId = Guid.NewGuid();
|
||||
var startedAt = _timeProvider.GetUtcNow();
|
||||
var context = new VexWorkerJobContext(tenant, connectorId, runId, checkpoint, startedAt);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Orchestrator job started: tenant={Tenant} connector={ConnectorId} runId={RunId} checkpoint={Checkpoint}",
|
||||
tenant,
|
||||
connectorId,
|
||||
runId,
|
||||
checkpoint ?? "(none)");
|
||||
|
||||
return ValueTask.FromResult(context);
|
||||
}
|
||||
|
||||
public async ValueTask SendHeartbeatAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerHeartbeat heartbeat,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(heartbeat);
|
||||
|
||||
var sequence = context.NextSequence();
|
||||
var timestamp = _timeProvider.GetUtcNow();
|
||||
|
||||
// Update state with heartbeat info
|
||||
var state = await _stateRepository.GetAsync(context.ConnectorId, cancellationToken).ConfigureAwait(false)
|
||||
?? new VexConnectorState(context.ConnectorId, null, ImmutableArray<string>.Empty);
|
||||
|
||||
var updated = state with
|
||||
{
|
||||
LastHeartbeatAt = timestamp,
|
||||
LastHeartbeatStatus = heartbeat.Status.ToString()
|
||||
};
|
||||
|
||||
await _stateRepository.SaveAsync(updated, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (_options.Value.EnableVerboseLogging)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Orchestrator heartbeat: runId={RunId} seq={Sequence} status={Status} progress={Progress} artifact={ArtifactHash}",
|
||||
context.RunId,
|
||||
sequence,
|
||||
heartbeat.Status,
|
||||
heartbeat.Progress,
|
||||
heartbeat.LastArtifactHash);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask RecordArtifactAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerArtifact artifact,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(artifact);
|
||||
|
||||
// Track artifact hash in connector state for determinism verification
|
||||
var state = await _stateRepository.GetAsync(context.ConnectorId, cancellationToken).ConfigureAwait(false)
|
||||
?? new VexConnectorState(context.ConnectorId, null, ImmutableArray<string>.Empty);
|
||||
|
||||
var digests = state.DocumentDigests.IsDefault
|
||||
? ImmutableArray<string>.Empty
|
||||
: state.DocumentDigests;
|
||||
|
||||
// Add artifact hash if not already tracked (cap to avoid unbounded growth)
|
||||
const int maxDigests = 1000;
|
||||
if (!digests.Contains(artifact.Hash))
|
||||
{
|
||||
digests = digests.Length >= maxDigests
|
||||
? digests.RemoveAt(0).Add(artifact.Hash)
|
||||
: digests.Add(artifact.Hash);
|
||||
}
|
||||
|
||||
var updated = state with
|
||||
{
|
||||
DocumentDigests = digests,
|
||||
LastArtifactHash = artifact.Hash,
|
||||
LastArtifactKind = artifact.Kind
|
||||
};
|
||||
|
||||
await _stateRepository.SaveAsync(updated, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Orchestrator artifact recorded: runId={RunId} hash={Hash} kind={Kind} provider={Provider}",
|
||||
context.RunId,
|
||||
artifact.Hash,
|
||||
artifact.Kind,
|
||||
artifact.ProviderId);
|
||||
}
|
||||
|
||||
public async ValueTask CompleteJobAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerJobResult result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(result);
|
||||
|
||||
var state = await _stateRepository.GetAsync(context.ConnectorId, cancellationToken).ConfigureAwait(false)
|
||||
?? new VexConnectorState(context.ConnectorId, null, ImmutableArray<string>.Empty);
|
||||
|
||||
var updated = state with
|
||||
{
|
||||
LastUpdated = result.CompletedAt,
|
||||
LastSuccessAt = result.CompletedAt,
|
||||
LastHeartbeatAt = result.CompletedAt,
|
||||
LastHeartbeatStatus = VexWorkerHeartbeatStatus.Succeeded.ToString(),
|
||||
LastArtifactHash = result.LastArtifactHash,
|
||||
LastCheckpoint = result.LastCheckpoint,
|
||||
FailureCount = 0,
|
||||
NextEligibleRun = null,
|
||||
LastFailureReason = null
|
||||
};
|
||||
|
||||
await _stateRepository.SaveAsync(updated, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var duration = result.CompletedAt - context.StartedAt;
|
||||
_logger.LogInformation(
|
||||
"Orchestrator job completed: runId={RunId} connector={ConnectorId} documents={Documents} claims={Claims} duration={Duration}",
|
||||
context.RunId,
|
||||
context.ConnectorId,
|
||||
result.DocumentsProcessed,
|
||||
result.ClaimsGenerated,
|
||||
duration);
|
||||
}
|
||||
|
||||
public async ValueTask FailJobAsync(
|
||||
VexWorkerJobContext context,
|
||||
string errorCode,
|
||||
string? errorMessage,
|
||||
int? retryAfterSeconds,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
|
||||
var now = _timeProvider.GetUtcNow();
|
||||
var state = await _stateRepository.GetAsync(context.ConnectorId, cancellationToken).ConfigureAwait(false)
|
||||
?? new VexConnectorState(context.ConnectorId, null, ImmutableArray<string>.Empty);
|
||||
|
||||
var failureCount = state.FailureCount + 1;
|
||||
var nextEligible = retryAfterSeconds.HasValue
|
||||
? now.AddSeconds(retryAfterSeconds.Value)
|
||||
: (DateTimeOffset?)null;
|
||||
|
||||
var updated = state with
|
||||
{
|
||||
LastHeartbeatAt = now,
|
||||
LastHeartbeatStatus = VexWorkerHeartbeatStatus.Failed.ToString(),
|
||||
FailureCount = failureCount,
|
||||
NextEligibleRun = nextEligible,
|
||||
LastFailureReason = Truncate($"{errorCode}: {errorMessage}", 512)
|
||||
};
|
||||
|
||||
await _stateRepository.SaveAsync(updated, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_logger.LogWarning(
|
||||
"Orchestrator job failed: runId={RunId} connector={ConnectorId} error={ErrorCode} retryAfter={RetryAfter}s",
|
||||
context.RunId,
|
||||
context.ConnectorId,
|
||||
errorCode,
|
||||
retryAfterSeconds);
|
||||
}
|
||||
|
||||
public ValueTask FailJobAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerError error,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(error);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Orchestrator job failed with classified error: runId={RunId} code={Code} category={Category} retryable={Retryable}",
|
||||
context.RunId,
|
||||
error.Code,
|
||||
error.Category,
|
||||
error.Retryable);
|
||||
|
||||
return FailJobAsync(
|
||||
context,
|
||||
error.Code,
|
||||
error.Message,
|
||||
error.Retryable ? error.RetryAfterSeconds : null,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
public ValueTask<VexWorkerCommand?> GetPendingCommandAsync(
|
||||
VexWorkerJobContext context,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
|
||||
// In this local implementation, commands are not externally sourced.
|
||||
// Return Continue to indicate normal processing should continue.
|
||||
// A full orchestrator integration would poll a command queue here.
|
||||
if (!_options.Value.Enabled)
|
||||
{
|
||||
return ValueTask.FromResult<VexWorkerCommand?>(null);
|
||||
}
|
||||
|
||||
// No pending commands in local mode
|
||||
return ValueTask.FromResult<VexWorkerCommand?>(null);
|
||||
}
|
||||
|
||||
public ValueTask AcknowledgeCommandAsync(
|
||||
VexWorkerJobContext context,
|
||||
long commandSequence,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Orchestrator command acknowledged: runId={RunId} sequence={Sequence}",
|
||||
context.RunId,
|
||||
commandSequence);
|
||||
|
||||
// In local mode, acknowledgment is a no-op
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
public async ValueTask SaveCheckpointAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerCheckpoint checkpoint,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(checkpoint);
|
||||
|
||||
var now = _timeProvider.GetUtcNow();
|
||||
var state = await _stateRepository.GetAsync(context.ConnectorId, cancellationToken).ConfigureAwait(false)
|
||||
?? new VexConnectorState(context.ConnectorId, null, ImmutableArray<string>.Empty);
|
||||
|
||||
var updated = state with
|
||||
{
|
||||
LastCheckpoint = checkpoint.Cursor,
|
||||
LastUpdated = checkpoint.LastProcessedAt ?? now,
|
||||
DocumentDigests = checkpoint.ProcessedDigests.IsDefault
|
||||
? ImmutableArray<string>.Empty
|
||||
: checkpoint.ProcessedDigests,
|
||||
ResumeTokens = checkpoint.ResumeTokens.IsEmpty
|
||||
? ImmutableDictionary<string, string>.Empty
|
||||
: checkpoint.ResumeTokens
|
||||
};
|
||||
|
||||
await _stateRepository.SaveAsync(updated, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Orchestrator checkpoint saved: runId={RunId} connector={ConnectorId} cursor={Cursor} digests={DigestCount}",
|
||||
context.RunId,
|
||||
context.ConnectorId,
|
||||
checkpoint.Cursor ?? "(none)",
|
||||
checkpoint.ProcessedDigests.Length);
|
||||
}
|
||||
|
||||
public async ValueTask<VexWorkerCheckpoint?> LoadCheckpointAsync(
|
||||
string connectorId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(connectorId);
|
||||
|
||||
var state = await _stateRepository.GetAsync(connectorId, cancellationToken).ConfigureAwait(false);
|
||||
if (state is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new VexWorkerCheckpoint(
|
||||
connectorId,
|
||||
state.LastCheckpoint,
|
||||
state.LastUpdated,
|
||||
state.DocumentDigests.IsDefault ? ImmutableArray<string>.Empty : state.DocumentDigests,
|
||||
state.ResumeTokens.IsEmpty ? ImmutableDictionary<string, string>.Empty : state.ResumeTokens);
|
||||
}
|
||||
|
||||
private static string Truncate(string? value, int maxLength)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return value.Length <= maxLength
|
||||
? value
|
||||
: value[..maxLength];
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,27 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Plugin;
|
||||
using StellaOps.Excititor.Connectors.RedHat.CSAF.DependencyInjection;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Core.Aoc;
|
||||
using StellaOps.Excititor.Core.Orchestration;
|
||||
using StellaOps.Excititor.Formats.CSAF;
|
||||
using StellaOps.Excititor.Formats.CycloneDX;
|
||||
using StellaOps.Excititor.Formats.OpenVEX;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.Worker.Auth;
|
||||
using StellaOps.Excititor.Worker.Options;
|
||||
using StellaOps.Excititor.Worker.Orchestration;
|
||||
using StellaOps.Excititor.Worker.Scheduling;
|
||||
using StellaOps.Excititor.Worker.Signature;
|
||||
using StellaOps.Excititor.Attestation.Extensions;
|
||||
using StellaOps.Excititor.Attestation.Verification;
|
||||
using StellaOps.IssuerDirectory.Client;
|
||||
|
||||
|
||||
var builder = Host.CreateApplicationBuilder(args);
|
||||
var services = builder.Services;
|
||||
var configuration = builder.Configuration;
|
||||
@@ -40,11 +42,11 @@ services.PostConfigure<VexWorkerOptions>(options =>
|
||||
}
|
||||
});
|
||||
services.AddRedHatCsafConnector();
|
||||
|
||||
services.AddOptions<VexMongoStorageOptions>()
|
||||
.Bind(configuration.GetSection("Excititor:Storage:Mongo"))
|
||||
.ValidateOnStart();
|
||||
|
||||
|
||||
services.AddOptions<VexMongoStorageOptions>()
|
||||
.Bind(configuration.GetSection("Excititor:Storage:Mongo"))
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddExcititorMongoStorage();
|
||||
services.AddCsafNormalizer();
|
||||
services.AddCycloneDxNormalizer();
|
||||
@@ -71,38 +73,45 @@ services.PostConfigure<VexAttestationVerificationOptions>(options =>
|
||||
}
|
||||
});
|
||||
services.AddExcititorAocGuards();
|
||||
|
||||
services.AddSingleton<IValidateOptions<VexWorkerOptions>, VexWorkerOptionsValidator>();
|
||||
services.AddSingleton(TimeProvider.System);
|
||||
services.PostConfigure<VexWorkerOptions>(options =>
|
||||
{
|
||||
if (!options.Providers.Any(provider => string.Equals(provider.ProviderId, "excititor:redhat", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
options.Providers.Add(new VexWorkerProviderOptions
|
||||
{
|
||||
ProviderId = "excititor:redhat",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
services.AddSingleton<IValidateOptions<VexWorkerOptions>, VexWorkerOptionsValidator>();
|
||||
services.AddSingleton(TimeProvider.System);
|
||||
services.PostConfigure<VexWorkerOptions>(options =>
|
||||
{
|
||||
if (!options.Providers.Any(provider => string.Equals(provider.ProviderId, "excititor:redhat", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
options.Providers.Add(new VexWorkerProviderOptions
|
||||
{
|
||||
ProviderId = "excititor:redhat",
|
||||
});
|
||||
}
|
||||
});
|
||||
services.AddSingleton<PluginCatalog>(provider =>
|
||||
{
|
||||
var pluginOptions = provider.GetRequiredService<IOptions<VexWorkerPluginOptions>>().Value;
|
||||
var catalog = new PluginCatalog();
|
||||
|
||||
var directory = pluginOptions.ResolveDirectory();
|
||||
if (Directory.Exists(directory))
|
||||
{
|
||||
catalog.AddFromDirectory(directory, pluginOptions.ResolveSearchPattern());
|
||||
}
|
||||
else
|
||||
{
|
||||
var logger = provider.GetRequiredService<ILogger<Program>>();
|
||||
logger.LogWarning("Excititor worker plugin directory '{Directory}' does not exist; proceeding without external connectors.", directory);
|
||||
}
|
||||
|
||||
return catalog;
|
||||
var directory = pluginOptions.ResolveDirectory();
|
||||
if (Directory.Exists(directory))
|
||||
{
|
||||
catalog.AddFromDirectory(directory, pluginOptions.ResolveSearchPattern());
|
||||
}
|
||||
else
|
||||
{
|
||||
var logger = provider.GetRequiredService<ILogger<Program>>();
|
||||
logger.LogWarning("Excititor worker plugin directory '{Directory}' does not exist; proceeding without external connectors.", directory);
|
||||
}
|
||||
|
||||
return catalog;
|
||||
});
|
||||
|
||||
// Orchestrator worker SDK integration
|
||||
services.AddOptions<VexWorkerOrchestratorOptions>()
|
||||
.Bind(configuration.GetSection("Excititor:Worker:Orchestrator"))
|
||||
.ValidateOnStart();
|
||||
services.AddSingleton<IVexWorkerOrchestratorClient, VexWorkerOrchestratorClient>();
|
||||
services.AddSingleton<VexWorkerHeartbeatService>();
|
||||
|
||||
services.AddSingleton<IVexProviderRunner, DefaultVexProviderRunner>();
|
||||
services.AddHostedService<VexWorkerHostedService>();
|
||||
if (!workerConfigSnapshot.DisableConsensus)
|
||||
@@ -115,5 +124,5 @@ services.AddSingleton<ITenantAuthorityClientFactory, TenantAuthorityClientFactor
|
||||
|
||||
var host = builder.Build();
|
||||
await host.RunAsync();
|
||||
|
||||
public partial class Program;
|
||||
|
||||
public partial class Program;
|
||||
|
||||
@@ -9,8 +9,10 @@ using MongoDB.Driver;
|
||||
using StellaOps.Plugin;
|
||||
using StellaOps.Excititor.Connectors.Abstractions;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Core.Orchestration;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.Worker.Options;
|
||||
using StellaOps.Excititor.Worker.Orchestration;
|
||||
using StellaOps.Excititor.Worker.Signature;
|
||||
|
||||
namespace StellaOps.Excititor.Worker.Scheduling;
|
||||
@@ -19,19 +21,27 @@ internal sealed class DefaultVexProviderRunner : IVexProviderRunner
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly PluginCatalog _pluginCatalog;
|
||||
private readonly IVexWorkerOrchestratorClient _orchestratorClient;
|
||||
private readonly VexWorkerHeartbeatService _heartbeatService;
|
||||
private readonly ILogger<DefaultVexProviderRunner> _logger;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly VexWorkerRetryOptions _retryOptions;
|
||||
private readonly VexWorkerOrchestratorOptions _orchestratorOptions;
|
||||
|
||||
public DefaultVexProviderRunner(
|
||||
IServiceProvider serviceProvider,
|
||||
PluginCatalog pluginCatalog,
|
||||
IVexWorkerOrchestratorClient orchestratorClient,
|
||||
VexWorkerHeartbeatService heartbeatService,
|
||||
ILogger<DefaultVexProviderRunner> logger,
|
||||
TimeProvider timeProvider,
|
||||
IOptions<VexWorkerOptions> workerOptions)
|
||||
IOptions<VexWorkerOptions> workerOptions,
|
||||
IOptions<VexWorkerOrchestratorOptions> orchestratorOptions)
|
||||
{
|
||||
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
|
||||
_pluginCatalog = pluginCatalog ?? throw new ArgumentNullException(nameof(pluginCatalog));
|
||||
_orchestratorClient = orchestratorClient ?? throw new ArgumentNullException(nameof(orchestratorClient));
|
||||
_heartbeatService = heartbeatService ?? throw new ArgumentNullException(nameof(heartbeatService));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
|
||||
if (workerOptions is null)
|
||||
@@ -40,6 +50,7 @@ internal sealed class DefaultVexProviderRunner : IVexProviderRunner
|
||||
}
|
||||
|
||||
_retryOptions = workerOptions.Value?.Retry ?? throw new InvalidOperationException("VexWorkerOptions.Retry must be configured.");
|
||||
_orchestratorOptions = orchestratorOptions?.Value ?? new VexWorkerOrchestratorOptions();
|
||||
}
|
||||
|
||||
public async ValueTask RunAsync(VexWorkerSchedule schedule, CancellationToken cancellationToken)
|
||||
@@ -118,7 +129,7 @@ internal sealed class DefaultVexProviderRunner : IVexProviderRunner
|
||||
|
||||
var verifyingSink = new VerifyingVexRawDocumentSink(rawStore, signatureVerifier);
|
||||
|
||||
var context = new VexConnectorContext(
|
||||
var connectorContext = new VexConnectorContext(
|
||||
Since: stateBeforeRun?.LastUpdated,
|
||||
Settings: effectiveSettings,
|
||||
RawSink: verifyingSink,
|
||||
@@ -127,33 +138,128 @@ internal sealed class DefaultVexProviderRunner : IVexProviderRunner
|
||||
Services: scopeProvider,
|
||||
ResumeTokens: stateBeforeRun?.ResumeTokens ?? ImmutableDictionary<string, string>.Empty);
|
||||
|
||||
// Start orchestrator job for heartbeat/progress tracking
|
||||
var jobContext = await _orchestratorClient.StartJobAsync(
|
||||
_orchestratorOptions.DefaultTenant,
|
||||
connector.Id,
|
||||
stateBeforeRun?.LastCheckpoint,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var documentCount = 0;
|
||||
string? lastArtifactHash = null;
|
||||
string? lastArtifactKind = null;
|
||||
var currentStatus = VexWorkerHeartbeatStatus.Running;
|
||||
|
||||
// Start heartbeat loop in background
|
||||
using var heartbeatCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
var heartbeatTask = _heartbeatService.RunAsync(
|
||||
jobContext,
|
||||
() => currentStatus,
|
||||
() => null, // Progress not tracked at document level
|
||||
() => lastArtifactHash,
|
||||
() => lastArtifactKind,
|
||||
heartbeatCts.Token);
|
||||
|
||||
try
|
||||
{
|
||||
await foreach (var document in connector.FetchAsync(context, cancellationToken).ConfigureAwait(false))
|
||||
await foreach (var document in connector.FetchAsync(connectorContext, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
documentCount++;
|
||||
lastArtifactHash = document.Digest;
|
||||
lastArtifactKind = "vex-raw-document";
|
||||
|
||||
// Record artifact for determinism tracking
|
||||
if (_orchestratorOptions.Enabled)
|
||||
{
|
||||
var artifact = new VexWorkerArtifact(
|
||||
document.Digest,
|
||||
"vex-raw-document",
|
||||
connector.Id,
|
||||
document.Digest,
|
||||
_timeProvider.GetUtcNow());
|
||||
|
||||
await _orchestratorClient.RecordArtifactAsync(jobContext, artifact, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Stop heartbeat loop
|
||||
currentStatus = VexWorkerHeartbeatStatus.Succeeded;
|
||||
await heartbeatCts.CancelAsync().ConfigureAwait(false);
|
||||
await SafeWaitForTaskAsync(heartbeatTask).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Connector {ConnectorId} persisted {DocumentCount} raw document(s) this run.",
|
||||
connector.Id,
|
||||
documentCount);
|
||||
|
||||
await UpdateSuccessStateAsync(stateRepository, descriptor.Id, _timeProvider.GetUtcNow(), cancellationToken).ConfigureAwait(false);
|
||||
// Complete orchestrator job
|
||||
var completedAt = _timeProvider.GetUtcNow();
|
||||
var result = new VexWorkerJobResult(
|
||||
documentCount,
|
||||
ClaimsGenerated: 0, // Claims generated in separate normalization pass
|
||||
lastArtifactHash,
|
||||
lastArtifactHash,
|
||||
completedAt);
|
||||
|
||||
await _orchestratorClient.CompleteJobAsync(jobContext, result, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await UpdateSuccessStateAsync(stateRepository, descriptor.Id, completedAt, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
currentStatus = VexWorkerHeartbeatStatus.Failed;
|
||||
await heartbeatCts.CancelAsync().ConfigureAwait(false);
|
||||
await SafeWaitForTaskAsync(heartbeatTask).ConfigureAwait(false);
|
||||
|
||||
var error = VexWorkerError.Cancelled("Operation cancelled by host");
|
||||
await _orchestratorClient.FailJobAsync(jobContext, error, CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await UpdateFailureStateAsync(stateRepository, descriptor.Id, _timeProvider.GetUtcNow(), ex, cancellationToken).ConfigureAwait(false);
|
||||
currentStatus = VexWorkerHeartbeatStatus.Failed;
|
||||
await heartbeatCts.CancelAsync().ConfigureAwait(false);
|
||||
await SafeWaitForTaskAsync(heartbeatTask).ConfigureAwait(false);
|
||||
|
||||
// Classify the error for appropriate retry handling
|
||||
var classifiedError = VexWorkerError.FromException(ex, stage: "fetch");
|
||||
|
||||
// Apply backoff delay for retryable errors
|
||||
var retryDelay = classifiedError.Retryable
|
||||
? (int)CalculateDelayWithJitter(1).TotalSeconds
|
||||
: (int?)null;
|
||||
|
||||
var errorWithRetry = classifiedError.Retryable && retryDelay.HasValue
|
||||
? new VexWorkerError(
|
||||
classifiedError.Code,
|
||||
classifiedError.Category,
|
||||
classifiedError.Message,
|
||||
classifiedError.Retryable,
|
||||
retryDelay,
|
||||
classifiedError.Stage,
|
||||
classifiedError.Details)
|
||||
: classifiedError;
|
||||
|
||||
await _orchestratorClient.FailJobAsync(jobContext, errorWithRetry, CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
await UpdateFailureStateAsync(stateRepository, descriptor.Id, _timeProvider.GetUtcNow(), ex, classifiedError.Retryable, cancellationToken).ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task SafeWaitForTaskAsync(Task task)
|
||||
{
|
||||
try
|
||||
{
|
||||
await task.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Expected when cancellation is requested
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UpdateSuccessStateAsync(
|
||||
IVexConnectorStateRepository stateRepository,
|
||||
string connectorId,
|
||||
@@ -179,33 +285,45 @@ internal sealed class DefaultVexProviderRunner : IVexProviderRunner
|
||||
string connectorId,
|
||||
DateTimeOffset failureTime,
|
||||
Exception exception,
|
||||
bool retryable,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var current = await stateRepository.GetAsync(connectorId, cancellationToken).ConfigureAwait(false)
|
||||
?? new VexConnectorState(connectorId, null, ImmutableArray<string>.Empty);
|
||||
|
||||
var failureCount = current.FailureCount + 1;
|
||||
var delay = CalculateDelayWithJitter(failureCount);
|
||||
var nextEligible = failureTime + delay;
|
||||
DateTimeOffset? nextEligible;
|
||||
|
||||
if (failureCount >= _retryOptions.FailureThreshold)
|
||||
if (retryable)
|
||||
{
|
||||
var quarantineUntil = failureTime + _retryOptions.QuarantineDuration;
|
||||
if (quarantineUntil > nextEligible)
|
||||
// Apply exponential backoff for retryable errors
|
||||
var delay = CalculateDelayWithJitter(failureCount);
|
||||
nextEligible = failureTime + delay;
|
||||
|
||||
if (failureCount >= _retryOptions.FailureThreshold)
|
||||
{
|
||||
nextEligible = quarantineUntil;
|
||||
var quarantineUntil = failureTime + _retryOptions.QuarantineDuration;
|
||||
if (quarantineUntil > nextEligible)
|
||||
{
|
||||
nextEligible = quarantineUntil;
|
||||
}
|
||||
}
|
||||
|
||||
var retryCap = failureTime + _retryOptions.RetryCap;
|
||||
if (nextEligible > retryCap)
|
||||
{
|
||||
nextEligible = retryCap;
|
||||
}
|
||||
|
||||
if (nextEligible < failureTime)
|
||||
{
|
||||
nextEligible = failureTime;
|
||||
}
|
||||
}
|
||||
|
||||
var retryCap = failureTime + _retryOptions.RetryCap;
|
||||
if (nextEligible > retryCap)
|
||||
else
|
||||
{
|
||||
nextEligible = retryCap;
|
||||
}
|
||||
|
||||
if (nextEligible < failureTime)
|
||||
{
|
||||
nextEligible = failureTime;
|
||||
// Non-retryable errors: apply quarantine immediately
|
||||
nextEligible = failureTime + _retryOptions.QuarantineDuration;
|
||||
}
|
||||
|
||||
var updated = current with
|
||||
@@ -219,9 +337,10 @@ internal sealed class DefaultVexProviderRunner : IVexProviderRunner
|
||||
|
||||
_logger.LogWarning(
|
||||
exception,
|
||||
"Connector {ConnectorId} failed (attempt {Attempt}). Next eligible run at {NextEligible:O}.",
|
||||
"Connector {ConnectorId} failed (attempt {Attempt}, retryable={Retryable}). Next eligible run at {NextEligible:O}.",
|
||||
connectorId,
|
||||
failureCount,
|
||||
retryable,
|
||||
nextEligible);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using StellaOps.Excititor.Attestation.Dsse;
|
||||
using StellaOps.Excititor.Attestation.Signing;
|
||||
using StellaOps.Excititor.Core.Evidence;
|
||||
|
||||
namespace StellaOps.Excititor.Attestation.Evidence;
|
||||
|
||||
/// <summary>
|
||||
/// Default implementation of <see cref="IVexEvidenceAttestor"/> that creates DSSE attestations for evidence manifests.
|
||||
/// </summary>
|
||||
public sealed class VexEvidenceAttestor : IVexEvidenceAttestor
|
||||
{
|
||||
internal const string PayloadType = "application/vnd.in-toto+json";
|
||||
|
||||
private readonly IVexSigner _signer;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly ILogger<VexEvidenceAttestor> _logger;
|
||||
private readonly JsonSerializerOptions _serializerOptions;
|
||||
|
||||
public VexEvidenceAttestor(
|
||||
IVexSigner signer,
|
||||
ILogger<VexEvidenceAttestor> logger,
|
||||
TimeProvider? timeProvider = null)
|
||||
{
|
||||
_signer = signer ?? throw new ArgumentNullException(nameof(signer));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_timeProvider = timeProvider ?? TimeProvider.System;
|
||||
_serializerOptions = new JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
WriteIndented = false,
|
||||
};
|
||||
_serializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
|
||||
}
|
||||
|
||||
public async ValueTask<VexEvidenceAttestationResult> AttestManifestAsync(
|
||||
VexLockerManifest manifest,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
|
||||
var attestedAt = _timeProvider.GetUtcNow();
|
||||
var attestationId = CreateAttestationId(manifest, attestedAt);
|
||||
|
||||
// Build in-toto statement
|
||||
var predicate = VexEvidenceAttestationPredicate.FromManifest(manifest);
|
||||
var subject = new VexEvidenceInTotoSubject(
|
||||
manifest.ManifestId,
|
||||
ImmutableDictionary<string, string>.Empty.Add("sha256", manifest.MerkleRoot.Replace("sha256:", "")));
|
||||
|
||||
var statement = new InTotoStatementDto
|
||||
{
|
||||
Type = VexEvidenceInTotoStatement.InTotoStatementType,
|
||||
PredicateType = VexEvidenceInTotoStatement.EvidenceLockerPredicateType,
|
||||
Subject = new[] { new InTotoSubjectDto { Name = subject.Name, Digest = subject.Digest } },
|
||||
Predicate = new InTotoPredicateDto
|
||||
{
|
||||
ManifestId = predicate.ManifestId,
|
||||
Tenant = predicate.Tenant,
|
||||
MerkleRoot = predicate.MerkleRoot,
|
||||
ItemCount = predicate.ItemCount,
|
||||
CreatedAt = predicate.CreatedAt,
|
||||
Metadata = predicate.Metadata.Count > 0 ? predicate.Metadata : null
|
||||
}
|
||||
};
|
||||
|
||||
// Serialize and sign
|
||||
var payloadBytes = JsonSerializer.SerializeToUtf8Bytes(statement, _serializerOptions);
|
||||
var signatureResult = await _signer.SignAsync(payloadBytes, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Build DSSE envelope
|
||||
var envelope = new DsseEnvelope(
|
||||
Convert.ToBase64String(payloadBytes),
|
||||
PayloadType,
|
||||
new[] { new DsseSignature(signatureResult.Signature, signatureResult.KeyId) });
|
||||
|
||||
var envelopeJson = JsonSerializer.Serialize(envelope, _serializerOptions);
|
||||
var envelopeHash = ComputeHash(envelopeJson);
|
||||
|
||||
// Create signed manifest
|
||||
var signedManifest = manifest.WithSignature(signatureResult.Signature);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Evidence attestation created for manifest {ManifestId}: attestation={AttestationId} hash={Hash}",
|
||||
manifest.ManifestId,
|
||||
attestationId,
|
||||
envelopeHash);
|
||||
|
||||
return new VexEvidenceAttestationResult(
|
||||
signedManifest,
|
||||
envelopeJson,
|
||||
envelopeHash,
|
||||
attestationId,
|
||||
attestedAt);
|
||||
}
|
||||
|
||||
public ValueTask<VexEvidenceVerificationResult> VerifyAttestationAsync(
|
||||
VexLockerManifest manifest,
|
||||
string dsseEnvelopeJson,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
if (string.IsNullOrWhiteSpace(dsseEnvelopeJson))
|
||||
{
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Failure("DSSE envelope is required."));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var envelope = JsonSerializer.Deserialize<DsseEnvelope>(dsseEnvelopeJson, _serializerOptions);
|
||||
if (envelope is null)
|
||||
{
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Failure("Invalid DSSE envelope format."));
|
||||
}
|
||||
|
||||
// Decode payload and verify it matches the manifest
|
||||
var payloadBytes = Convert.FromBase64String(envelope.Payload);
|
||||
var statement = JsonSerializer.Deserialize<InTotoStatementDto>(payloadBytes, _serializerOptions);
|
||||
if (statement is null)
|
||||
{
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Failure("Invalid in-toto statement format."));
|
||||
}
|
||||
|
||||
// Verify statement type
|
||||
if (statement.Type != VexEvidenceInTotoStatement.InTotoStatementType)
|
||||
{
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Failure(
|
||||
$"Invalid statement type: expected {VexEvidenceInTotoStatement.InTotoStatementType}, got {statement.Type}"));
|
||||
}
|
||||
|
||||
// Verify predicate type
|
||||
if (statement.PredicateType != VexEvidenceInTotoStatement.EvidenceLockerPredicateType)
|
||||
{
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Failure(
|
||||
$"Invalid predicate type: expected {VexEvidenceInTotoStatement.EvidenceLockerPredicateType}, got {statement.PredicateType}"));
|
||||
}
|
||||
|
||||
// Verify manifest ID matches
|
||||
if (statement.Predicate?.ManifestId != manifest.ManifestId)
|
||||
{
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Failure(
|
||||
$"Manifest ID mismatch: expected {manifest.ManifestId}, got {statement.Predicate?.ManifestId}"));
|
||||
}
|
||||
|
||||
// Verify Merkle root matches
|
||||
if (statement.Predicate?.MerkleRoot != manifest.MerkleRoot)
|
||||
{
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Failure(
|
||||
$"Merkle root mismatch: expected {manifest.MerkleRoot}, got {statement.Predicate?.MerkleRoot}"));
|
||||
}
|
||||
|
||||
// Verify item count matches
|
||||
if (statement.Predicate?.ItemCount != manifest.Items.Length)
|
||||
{
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Failure(
|
||||
$"Item count mismatch: expected {manifest.Items.Length}, got {statement.Predicate?.ItemCount}"));
|
||||
}
|
||||
|
||||
var diagnostics = ImmutableDictionary.CreateBuilder<string, string>();
|
||||
diagnostics.Add("envelope_hash", ComputeHash(dsseEnvelopeJson));
|
||||
diagnostics.Add("verified_at", _timeProvider.GetUtcNow().ToString("O"));
|
||||
|
||||
_logger.LogDebug("Evidence attestation verified for manifest {ManifestId}", manifest.ManifestId);
|
||||
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Success(diagnostics.ToImmutable()));
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to parse DSSE envelope for manifest {ManifestId}", manifest.ManifestId);
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Failure($"JSON parse error: {ex.Message}"));
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to decode base64 payload for manifest {ManifestId}", manifest.ManifestId);
|
||||
return ValueTask.FromResult(VexEvidenceVerificationResult.Failure($"Base64 decode error: {ex.Message}"));
|
||||
}
|
||||
}
|
||||
|
||||
private static string CreateAttestationId(VexLockerManifest manifest, DateTimeOffset timestamp)
|
||||
{
|
||||
var normalized = manifest.Tenant.ToLowerInvariant();
|
||||
var date = timestamp.ToString("yyyyMMddHHmmssfff");
|
||||
return $"attest:evidence:{normalized}:{date}";
|
||||
}
|
||||
|
||||
private static string ComputeHash(string content)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(content);
|
||||
var hash = SHA256.HashData(bytes);
|
||||
return "sha256:" + Convert.ToHexString(hash).ToLowerInvariant();
|
||||
}
|
||||
|
||||
// DTOs for JSON serialization
|
||||
private sealed record InTotoStatementDto
|
||||
{
|
||||
[JsonPropertyName("_type")]
|
||||
public string? Type { get; init; }
|
||||
|
||||
[JsonPropertyName("predicateType")]
|
||||
public string? PredicateType { get; init; }
|
||||
|
||||
[JsonPropertyName("subject")]
|
||||
public InTotoSubjectDto[]? Subject { get; init; }
|
||||
|
||||
[JsonPropertyName("predicate")]
|
||||
public InTotoPredicateDto? Predicate { get; init; }
|
||||
}
|
||||
|
||||
private sealed record InTotoSubjectDto
|
||||
{
|
||||
[JsonPropertyName("name")]
|
||||
public string? Name { get; init; }
|
||||
|
||||
[JsonPropertyName("digest")]
|
||||
public ImmutableDictionary<string, string>? Digest { get; init; }
|
||||
}
|
||||
|
||||
private sealed record InTotoPredicateDto
|
||||
{
|
||||
[JsonPropertyName("manifestId")]
|
||||
public string? ManifestId { get; init; }
|
||||
|
||||
[JsonPropertyName("tenant")]
|
||||
public string? Tenant { get; init; }
|
||||
|
||||
[JsonPropertyName("merkleRoot")]
|
||||
public string? MerkleRoot { get; init; }
|
||||
|
||||
[JsonPropertyName("itemCount")]
|
||||
public int? ItemCount { get; init; }
|
||||
|
||||
[JsonPropertyName("createdAt")]
|
||||
public DateTimeOffset? CreatedAt { get; init; }
|
||||
|
||||
[JsonPropertyName("metadata")]
|
||||
public ImmutableDictionary<string, string>? Metadata { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using StellaOps.Excititor.Attestation.Dsse;
|
||||
using StellaOps.Excititor.Attestation.Evidence;
|
||||
using StellaOps.Excititor.Attestation.Transparency;
|
||||
using StellaOps.Excititor.Attestation.Verification;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Core.Evidence;
|
||||
|
||||
namespace StellaOps.Excititor.Attestation.Extensions;
|
||||
|
||||
@@ -14,14 +16,15 @@ public static class VexAttestationServiceCollectionExtensions
|
||||
services.AddSingleton<VexAttestationMetrics>();
|
||||
services.AddSingleton<IVexAttestationVerifier, VexAttestationVerifier>();
|
||||
services.AddSingleton<IVexAttestationClient, VexAttestationClient>();
|
||||
services.AddSingleton<IVexEvidenceAttestor, VexEvidenceAttestor>();
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddVexRekorClient(this IServiceCollection services, Action<RekorHttpClientOptions> configure)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(configure);
|
||||
services.Configure(configure);
|
||||
services.AddHttpClient<ITransparencyLogClient, RekorHttpClient>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
public static IServiceCollection AddVexRekorClient(this IServiceCollection services, Action<RekorHttpClientOptions> configure)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(configure);
|
||||
services.Configure(configure);
|
||||
services.AddHttpClient<ITransparencyLogClient, RekorHttpClient>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace StellaOps.Excititor.Core.Canonicalization;
|
||||
|
||||
/// <summary>
|
||||
/// Canonicalizes advisory and vulnerability identifiers to a stable <see cref="VexCanonicalAdvisoryKey"/>.
|
||||
/// Preserves original identifiers in the Links collection for traceability.
|
||||
/// </summary>
|
||||
public sealed class VexAdvisoryKeyCanonicalizer
|
||||
{
|
||||
private static readonly Regex CvePattern = new(
|
||||
@"^CVE-\d{4}-\d{4,}$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly Regex GhsaPattern = new(
|
||||
@"^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly Regex RhsaPattern = new(
|
||||
@"^RH[A-Z]{2}-\d{4}:\d+$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly Regex DsaPattern = new(
|
||||
@"^DSA-\d+(-\d+)?$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly Regex UsnPattern = new(
|
||||
@"^USN-\d+(-\d+)?$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly Regex MsrcPattern = new(
|
||||
@"^(ADV|CVE)-\d{4}-\d+$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>
|
||||
/// Canonicalizes an advisory identifier and extracts scope metadata.
|
||||
/// </summary>
|
||||
/// <param name="originalId">The original advisory/vulnerability identifier.</param>
|
||||
/// <param name="aliases">Optional alias identifiers to include in links.</param>
|
||||
/// <returns>A canonical advisory key with preserved original links.</returns>
|
||||
public VexCanonicalAdvisoryKey Canonicalize(string originalId, IEnumerable<string>? aliases = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(originalId);
|
||||
|
||||
var normalized = originalId.Trim().ToUpperInvariant();
|
||||
var scope = DetermineScope(normalized);
|
||||
var canonicalKey = BuildCanonicalKey(normalized, scope);
|
||||
|
||||
var linksBuilder = ImmutableArray.CreateBuilder<VexAdvisoryLink>();
|
||||
|
||||
// Add the original identifier as a link
|
||||
linksBuilder.Add(new VexAdvisoryLink(
|
||||
originalId.Trim(),
|
||||
DetermineIdType(normalized),
|
||||
isOriginal: true));
|
||||
|
||||
// Add aliases as links
|
||||
if (aliases is not null)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { normalized };
|
||||
foreach (var alias in aliases)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(alias))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var normalizedAlias = alias.Trim();
|
||||
if (!seen.Add(normalizedAlias.ToUpperInvariant()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
linksBuilder.Add(new VexAdvisoryLink(
|
||||
normalizedAlias,
|
||||
DetermineIdType(normalizedAlias.ToUpperInvariant()),
|
||||
isOriginal: false));
|
||||
}
|
||||
}
|
||||
|
||||
return new VexCanonicalAdvisoryKey(
|
||||
canonicalKey,
|
||||
scope,
|
||||
linksBuilder.ToImmutable());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts CVE identifier from aliases if the original is not a CVE.
|
||||
/// </summary>
|
||||
public string? ExtractCveFromAliases(IEnumerable<string>? aliases)
|
||||
{
|
||||
if (aliases is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var alias in aliases)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(alias))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var normalized = alias.Trim().ToUpperInvariant();
|
||||
if (CvePattern.IsMatch(normalized))
|
||||
{
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static VexAdvisoryScope DetermineScope(string normalizedId)
|
||||
{
|
||||
if (CvePattern.IsMatch(normalizedId))
|
||||
{
|
||||
return VexAdvisoryScope.Global;
|
||||
}
|
||||
|
||||
if (GhsaPattern.IsMatch(normalizedId))
|
||||
{
|
||||
return VexAdvisoryScope.Ecosystem;
|
||||
}
|
||||
|
||||
if (RhsaPattern.IsMatch(normalizedId))
|
||||
{
|
||||
return VexAdvisoryScope.Vendor;
|
||||
}
|
||||
|
||||
if (DsaPattern.IsMatch(normalizedId) || UsnPattern.IsMatch(normalizedId))
|
||||
{
|
||||
return VexAdvisoryScope.Distribution;
|
||||
}
|
||||
|
||||
if (MsrcPattern.IsMatch(normalizedId))
|
||||
{
|
||||
return VexAdvisoryScope.Vendor;
|
||||
}
|
||||
|
||||
return VexAdvisoryScope.Unknown;
|
||||
}
|
||||
|
||||
private static string BuildCanonicalKey(string normalizedId, VexAdvisoryScope scope)
|
||||
{
|
||||
// CVE is the most authoritative global identifier
|
||||
if (CvePattern.IsMatch(normalizedId))
|
||||
{
|
||||
return normalizedId;
|
||||
}
|
||||
|
||||
// For non-CVE identifiers, prefix with scope indicator for disambiguation
|
||||
var prefix = scope switch
|
||||
{
|
||||
VexAdvisoryScope.Ecosystem => "ECO",
|
||||
VexAdvisoryScope.Vendor => "VND",
|
||||
VexAdvisoryScope.Distribution => "DST",
|
||||
_ => "UNK",
|
||||
};
|
||||
|
||||
return $"{prefix}:{normalizedId}";
|
||||
}
|
||||
|
||||
private static string DetermineIdType(string normalizedId)
|
||||
{
|
||||
if (CvePattern.IsMatch(normalizedId))
|
||||
{
|
||||
return "cve";
|
||||
}
|
||||
|
||||
if (GhsaPattern.IsMatch(normalizedId))
|
||||
{
|
||||
return "ghsa";
|
||||
}
|
||||
|
||||
if (RhsaPattern.IsMatch(normalizedId))
|
||||
{
|
||||
return "rhsa";
|
||||
}
|
||||
|
||||
if (DsaPattern.IsMatch(normalizedId))
|
||||
{
|
||||
return "dsa";
|
||||
}
|
||||
|
||||
if (UsnPattern.IsMatch(normalizedId))
|
||||
{
|
||||
return "usn";
|
||||
}
|
||||
|
||||
if (MsrcPattern.IsMatch(normalizedId))
|
||||
{
|
||||
return "msrc";
|
||||
}
|
||||
|
||||
return "other";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a canonicalized advisory key with preserved original identifiers.
|
||||
/// </summary>
|
||||
public sealed record VexCanonicalAdvisoryKey
|
||||
{
|
||||
public VexCanonicalAdvisoryKey(
|
||||
string advisoryKey,
|
||||
VexAdvisoryScope scope,
|
||||
ImmutableArray<VexAdvisoryLink> links)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(advisoryKey))
|
||||
{
|
||||
throw new ArgumentException("Advisory key must be provided.", nameof(advisoryKey));
|
||||
}
|
||||
|
||||
AdvisoryKey = advisoryKey.Trim();
|
||||
Scope = scope;
|
||||
Links = links.IsDefault ? ImmutableArray<VexAdvisoryLink>.Empty : links;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The canonical advisory key used for correlation and storage.
|
||||
/// </summary>
|
||||
public string AdvisoryKey { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The scope/authority level of the advisory.
|
||||
/// </summary>
|
||||
public VexAdvisoryScope Scope { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Original and alias identifiers preserved for traceability.
|
||||
/// </summary>
|
||||
public ImmutableArray<VexAdvisoryLink> Links { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the original identifier if available.
|
||||
/// </summary>
|
||||
public string? OriginalId => Links.FirstOrDefault(l => l.IsOriginal)?.Identifier;
|
||||
|
||||
/// <summary>
|
||||
/// Returns all non-original alias identifiers.
|
||||
/// </summary>
|
||||
public IEnumerable<string> Aliases => Links.Where(l => !l.IsOriginal).Select(l => l.Identifier);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a link to an original or alias advisory identifier.
|
||||
/// </summary>
|
||||
public sealed record VexAdvisoryLink
|
||||
{
|
||||
public VexAdvisoryLink(string identifier, string type, bool isOriginal)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(identifier))
|
||||
{
|
||||
throw new ArgumentException("Identifier must be provided.", nameof(identifier));
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(type))
|
||||
{
|
||||
throw new ArgumentException("Type must be provided.", nameof(type));
|
||||
}
|
||||
|
||||
Identifier = identifier.Trim();
|
||||
Type = type.Trim().ToLowerInvariant();
|
||||
IsOriginal = isOriginal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The advisory identifier value.
|
||||
/// </summary>
|
||||
public string Identifier { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The type of identifier (cve, ghsa, rhsa, dsa, usn, msrc, other).
|
||||
/// </summary>
|
||||
public string Type { get; }
|
||||
|
||||
/// <summary>
|
||||
/// True if this is the original identifier provided at ingest time.
|
||||
/// </summary>
|
||||
public bool IsOriginal { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The scope/authority level of an advisory.
|
||||
/// </summary>
|
||||
public enum VexAdvisoryScope
|
||||
{
|
||||
/// <summary>
|
||||
/// Unknown or unclassified scope.
|
||||
/// </summary>
|
||||
Unknown = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Global identifiers (e.g., CVE).
|
||||
/// </summary>
|
||||
Global = 1,
|
||||
|
||||
/// <summary>
|
||||
/// Ecosystem-specific identifiers (e.g., GHSA).
|
||||
/// </summary>
|
||||
Ecosystem = 2,
|
||||
|
||||
/// <summary>
|
||||
/// Vendor-specific identifiers (e.g., RHSA, MSRC).
|
||||
/// </summary>
|
||||
Vendor = 3,
|
||||
|
||||
/// <summary>
|
||||
/// Distribution-specific identifiers (e.g., DSA, USN).
|
||||
/// </summary>
|
||||
Distribution = 4,
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace StellaOps.Excititor.Core.Canonicalization;
|
||||
|
||||
/// <summary>
|
||||
/// Canonicalizes product identifiers (PURL, CPE, OS package names) to a stable <see cref="VexCanonicalProductKey"/>.
|
||||
/// Preserves original identifiers in the Links collection for traceability.
|
||||
/// </summary>
|
||||
public sealed class VexProductKeyCanonicalizer
|
||||
{
|
||||
private static readonly Regex PurlPattern = new(
|
||||
@"^pkg:[a-z0-9]+/",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly Regex CpePattern = new(
|
||||
@"^cpe:(2\.3:|/)",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
// RPM NEVRA format: name-[epoch:]version-release.arch
|
||||
// Release can contain dots (e.g., 1.el9), so we match until the last dot before arch
|
||||
private static readonly Regex RpmNevraPattern = new(
|
||||
@"^(?<name>[a-zA-Z0-9_+-]+)-(?<epoch>\d+:)?(?<version>[^-]+)-(?<release>.+)\.(?<arch>x86_64|i686|noarch|aarch64|s390x|ppc64le|armv7hl|src)$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
// Debian packages use underscores as separators: name_version_arch or name_version
|
||||
// Must have at least one underscore to be considered a Debian package
|
||||
private static readonly Regex DebianPackagePattern = new(
|
||||
@"^(?<name>[a-z0-9][a-z0-9.+-]+)_(?<version>[^_]+)(_(?<arch>[a-z0-9-]+))?$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>
|
||||
/// Canonicalizes a product identifier and extracts scope metadata.
|
||||
/// </summary>
|
||||
/// <param name="originalKey">The original product key/identifier.</param>
|
||||
/// <param name="purl">Optional PURL for the product.</param>
|
||||
/// <param name="cpe">Optional CPE for the product.</param>
|
||||
/// <param name="componentIdentifiers">Optional additional component identifiers.</param>
|
||||
/// <returns>A canonical product key with preserved original links.</returns>
|
||||
public VexCanonicalProductKey Canonicalize(
|
||||
string originalKey,
|
||||
string? purl = null,
|
||||
string? cpe = null,
|
||||
IEnumerable<string>? componentIdentifiers = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(originalKey);
|
||||
|
||||
// Check component identifiers for PURL if not provided directly
|
||||
var effectivePurl = purl ?? ExtractPurlFromIdentifiers(componentIdentifiers);
|
||||
var effectiveCpe = cpe ?? ExtractCpeFromIdentifiers(componentIdentifiers);
|
||||
|
||||
var keyType = DetermineKeyType(originalKey.Trim());
|
||||
var scope = DetermineScope(originalKey.Trim(), effectivePurl, effectiveCpe);
|
||||
var canonicalKey = BuildCanonicalKey(originalKey.Trim(), effectivePurl, effectiveCpe, keyType);
|
||||
|
||||
var linksBuilder = ImmutableArray.CreateBuilder<VexProductLink>();
|
||||
|
||||
// Add the original key as a link
|
||||
linksBuilder.Add(new VexProductLink(
|
||||
originalKey.Trim(),
|
||||
keyType.ToString().ToLowerInvariant(),
|
||||
isOriginal: true));
|
||||
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { originalKey.Trim() };
|
||||
|
||||
// Add PURL if different from original
|
||||
if (!string.IsNullOrWhiteSpace(purl) && seen.Add(purl.Trim()))
|
||||
{
|
||||
linksBuilder.Add(new VexProductLink(
|
||||
purl.Trim(),
|
||||
"purl",
|
||||
isOriginal: false));
|
||||
}
|
||||
|
||||
// Add CPE if different from original
|
||||
if (!string.IsNullOrWhiteSpace(cpe) && seen.Add(cpe.Trim()))
|
||||
{
|
||||
linksBuilder.Add(new VexProductLink(
|
||||
cpe.Trim(),
|
||||
"cpe",
|
||||
isOriginal: false));
|
||||
}
|
||||
|
||||
// Add component identifiers
|
||||
if (componentIdentifiers is not null)
|
||||
{
|
||||
foreach (var identifier in componentIdentifiers)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(identifier))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var normalizedId = identifier.Trim();
|
||||
if (!seen.Add(normalizedId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var idType = DetermineKeyType(normalizedId);
|
||||
linksBuilder.Add(new VexProductLink(
|
||||
normalizedId,
|
||||
idType.ToString().ToLowerInvariant(),
|
||||
isOriginal: false));
|
||||
}
|
||||
}
|
||||
|
||||
return new VexCanonicalProductKey(
|
||||
canonicalKey,
|
||||
scope,
|
||||
keyType,
|
||||
linksBuilder.ToImmutable());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts PURL from component identifiers if available.
|
||||
/// </summary>
|
||||
public string? ExtractPurlFromIdentifiers(IEnumerable<string>? identifiers)
|
||||
{
|
||||
if (identifiers is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var id in identifiers)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (PurlPattern.IsMatch(id.Trim()))
|
||||
{
|
||||
return id.Trim();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts CPE from component identifiers if available.
|
||||
/// </summary>
|
||||
public string? ExtractCpeFromIdentifiers(IEnumerable<string>? identifiers)
|
||||
{
|
||||
if (identifiers is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var id in identifiers)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (CpePattern.IsMatch(id.Trim()))
|
||||
{
|
||||
return id.Trim();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static VexProductKeyType DetermineKeyType(string key)
|
||||
{
|
||||
if (PurlPattern.IsMatch(key))
|
||||
{
|
||||
return VexProductKeyType.Purl;
|
||||
}
|
||||
|
||||
if (CpePattern.IsMatch(key))
|
||||
{
|
||||
return VexProductKeyType.Cpe;
|
||||
}
|
||||
|
||||
if (RpmNevraPattern.IsMatch(key))
|
||||
{
|
||||
return VexProductKeyType.RpmNevra;
|
||||
}
|
||||
|
||||
if (DebianPackagePattern.IsMatch(key))
|
||||
{
|
||||
return VexProductKeyType.DebianPackage;
|
||||
}
|
||||
|
||||
if (key.StartsWith("oci:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return VexProductKeyType.OciImage;
|
||||
}
|
||||
|
||||
if (key.StartsWith("platform:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return VexProductKeyType.Platform;
|
||||
}
|
||||
|
||||
return VexProductKeyType.Other;
|
||||
}
|
||||
|
||||
private static VexProductScope DetermineScope(string key, string? purl, string? cpe)
|
||||
{
|
||||
// PURL is the most authoritative
|
||||
if (!string.IsNullOrWhiteSpace(purl) || PurlPattern.IsMatch(key))
|
||||
{
|
||||
return VexProductScope.Package;
|
||||
}
|
||||
|
||||
// CPE is next
|
||||
if (!string.IsNullOrWhiteSpace(cpe) || CpePattern.IsMatch(key))
|
||||
{
|
||||
return VexProductScope.Component;
|
||||
}
|
||||
|
||||
// OS packages
|
||||
if (RpmNevraPattern.IsMatch(key) || DebianPackagePattern.IsMatch(key))
|
||||
{
|
||||
return VexProductScope.OsPackage;
|
||||
}
|
||||
|
||||
// OCI images
|
||||
if (key.StartsWith("oci:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return VexProductScope.Container;
|
||||
}
|
||||
|
||||
// Platforms
|
||||
if (key.StartsWith("platform:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return VexProductScope.Platform;
|
||||
}
|
||||
|
||||
return VexProductScope.Unknown;
|
||||
}
|
||||
|
||||
private static string BuildCanonicalKey(string key, string? purl, string? cpe, VexProductKeyType keyType)
|
||||
{
|
||||
// Prefer PURL as canonical key
|
||||
if (!string.IsNullOrWhiteSpace(purl))
|
||||
{
|
||||
return NormalizePurl(purl.Trim());
|
||||
}
|
||||
|
||||
if (PurlPattern.IsMatch(key))
|
||||
{
|
||||
return NormalizePurl(key);
|
||||
}
|
||||
|
||||
// Fall back to CPE
|
||||
if (!string.IsNullOrWhiteSpace(cpe))
|
||||
{
|
||||
return NormalizeCpe(cpe.Trim());
|
||||
}
|
||||
|
||||
if (CpePattern.IsMatch(key))
|
||||
{
|
||||
return NormalizeCpe(key);
|
||||
}
|
||||
|
||||
// For types that already have their prefix, return as-is
|
||||
if (keyType == VexProductKeyType.OciImage && key.StartsWith("oci:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return key;
|
||||
}
|
||||
|
||||
if (keyType == VexProductKeyType.Platform && key.StartsWith("platform:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return key;
|
||||
}
|
||||
|
||||
// For other types, prefix for disambiguation
|
||||
var prefix = keyType switch
|
||||
{
|
||||
VexProductKeyType.RpmNevra => "rpm",
|
||||
VexProductKeyType.DebianPackage => "deb",
|
||||
VexProductKeyType.OciImage => "oci",
|
||||
VexProductKeyType.Platform => "platform",
|
||||
_ => "product",
|
||||
};
|
||||
|
||||
return $"{prefix}:{key}";
|
||||
}
|
||||
|
||||
private static string NormalizePurl(string purl)
|
||||
{
|
||||
// Ensure lowercase scheme
|
||||
if (purl.StartsWith("PKG:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "pkg:" + purl.Substring(4);
|
||||
}
|
||||
|
||||
return purl;
|
||||
}
|
||||
|
||||
private static string NormalizeCpe(string cpe)
|
||||
{
|
||||
// Ensure lowercase scheme
|
||||
if (cpe.StartsWith("CPE:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "cpe:" + cpe.Substring(4);
|
||||
}
|
||||
|
||||
return cpe;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a canonicalized product key with preserved original identifiers.
|
||||
/// </summary>
|
||||
public sealed record VexCanonicalProductKey
|
||||
{
|
||||
public VexCanonicalProductKey(
|
||||
string productKey,
|
||||
VexProductScope scope,
|
||||
VexProductKeyType keyType,
|
||||
ImmutableArray<VexProductLink> links)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(productKey))
|
||||
{
|
||||
throw new ArgumentException("Product key must be provided.", nameof(productKey));
|
||||
}
|
||||
|
||||
ProductKey = productKey.Trim();
|
||||
Scope = scope;
|
||||
KeyType = keyType;
|
||||
Links = links.IsDefault ? ImmutableArray<VexProductLink>.Empty : links;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The canonical product key used for correlation and storage.
|
||||
/// </summary>
|
||||
public string ProductKey { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The scope/authority level of the product identifier.
|
||||
/// </summary>
|
||||
public VexProductScope Scope { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The type of the canonical key.
|
||||
/// </summary>
|
||||
public VexProductKeyType KeyType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Original and alias identifiers preserved for traceability.
|
||||
/// </summary>
|
||||
public ImmutableArray<VexProductLink> Links { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the original identifier if available.
|
||||
/// </summary>
|
||||
public string? OriginalKey => Links.FirstOrDefault(l => l.IsOriginal)?.Identifier;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the PURL link if available.
|
||||
/// </summary>
|
||||
public string? Purl => Links.FirstOrDefault(l => l.Type == "purl")?.Identifier;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the CPE link if available.
|
||||
/// </summary>
|
||||
public string? Cpe => Links.FirstOrDefault(l => l.Type == "cpe")?.Identifier;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a link to an original or alias product identifier.
|
||||
/// </summary>
|
||||
public sealed record VexProductLink
|
||||
{
|
||||
public VexProductLink(string identifier, string type, bool isOriginal)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(identifier))
|
||||
{
|
||||
throw new ArgumentException("Identifier must be provided.", nameof(identifier));
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(type))
|
||||
{
|
||||
throw new ArgumentException("Type must be provided.", nameof(type));
|
||||
}
|
||||
|
||||
Identifier = identifier.Trim();
|
||||
Type = type.Trim().ToLowerInvariant();
|
||||
IsOriginal = isOriginal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The product identifier value.
|
||||
/// </summary>
|
||||
public string Identifier { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The type of identifier (purl, cpe, rpm, deb, oci, platform, other).
|
||||
/// </summary>
|
||||
public string Type { get; }
|
||||
|
||||
/// <summary>
|
||||
/// True if this is the original identifier provided at ingest time.
|
||||
/// </summary>
|
||||
public bool IsOriginal { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The scope/authority level of a product identifier.
|
||||
/// </summary>
|
||||
public enum VexProductScope
|
||||
{
|
||||
/// <summary>
|
||||
/// Unknown or unclassified scope.
|
||||
/// </summary>
|
||||
Unknown = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Package-level identifier (PURL).
|
||||
/// </summary>
|
||||
Package = 1,
|
||||
|
||||
/// <summary>
|
||||
/// Component-level identifier (CPE).
|
||||
/// </summary>
|
||||
Component = 2,
|
||||
|
||||
/// <summary>
|
||||
/// OS package identifier (RPM, DEB).
|
||||
/// </summary>
|
||||
OsPackage = 3,
|
||||
|
||||
/// <summary>
|
||||
/// Container image identifier.
|
||||
/// </summary>
|
||||
Container = 4,
|
||||
|
||||
/// <summary>
|
||||
/// Platform-level identifier.
|
||||
/// </summary>
|
||||
Platform = 5,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The type of product key identifier.
|
||||
/// </summary>
|
||||
public enum VexProductKeyType
|
||||
{
|
||||
/// <summary>
|
||||
/// Other/unknown type.
|
||||
/// </summary>
|
||||
Other = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Package URL (PURL).
|
||||
/// </summary>
|
||||
Purl = 1,
|
||||
|
||||
/// <summary>
|
||||
/// Common Platform Enumeration (CPE).
|
||||
/// </summary>
|
||||
Cpe = 2,
|
||||
|
||||
/// <summary>
|
||||
/// RPM NEVRA format.
|
||||
/// </summary>
|
||||
RpmNevra = 3,
|
||||
|
||||
/// <summary>
|
||||
/// Debian package format.
|
||||
/// </summary>
|
||||
DebianPackage = 4,
|
||||
|
||||
/// <summary>
|
||||
/// OCI image reference.
|
||||
/// </summary>
|
||||
OciImage = 5,
|
||||
|
||||
/// <summary>
|
||||
/// Platform identifier.
|
||||
/// </summary>
|
||||
Platform = 6,
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace StellaOps.Excititor.Core.Evidence;
|
||||
|
||||
/// <summary>
|
||||
/// Service interface for creating and verifying DSSE attestations on evidence locker manifests.
|
||||
/// </summary>
|
||||
public interface IVexEvidenceAttestor
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a DSSE attestation for the given manifest and returns the signed manifest.
|
||||
/// </summary>
|
||||
ValueTask<VexEvidenceAttestationResult> AttestManifestAsync(
|
||||
VexLockerManifest manifest,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Verifies an attestation for the given manifest.
|
||||
/// </summary>
|
||||
ValueTask<VexEvidenceVerificationResult> VerifyAttestationAsync(
|
||||
VexLockerManifest manifest,
|
||||
string dsseEnvelopeJson,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of attesting an evidence manifest.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceAttestationResult
|
||||
{
|
||||
public VexEvidenceAttestationResult(
|
||||
VexLockerManifest signedManifest,
|
||||
string dsseEnvelopeJson,
|
||||
string dsseEnvelopeHash,
|
||||
string attestationId,
|
||||
DateTimeOffset attestedAt)
|
||||
{
|
||||
SignedManifest = signedManifest ?? throw new ArgumentNullException(nameof(signedManifest));
|
||||
DsseEnvelopeJson = EnsureNotNullOrWhiteSpace(dsseEnvelopeJson, nameof(dsseEnvelopeJson));
|
||||
DsseEnvelopeHash = EnsureNotNullOrWhiteSpace(dsseEnvelopeHash, nameof(dsseEnvelopeHash));
|
||||
AttestationId = EnsureNotNullOrWhiteSpace(attestationId, nameof(attestationId));
|
||||
AttestedAt = attestedAt;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The manifest with the attestation signature attached.
|
||||
/// </summary>
|
||||
public VexLockerManifest SignedManifest { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The DSSE envelope as JSON.
|
||||
/// </summary>
|
||||
public string DsseEnvelopeJson { get; }
|
||||
|
||||
/// <summary>
|
||||
/// SHA-256 hash of the DSSE envelope.
|
||||
/// </summary>
|
||||
public string DsseEnvelopeHash { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Unique identifier for this attestation.
|
||||
/// </summary>
|
||||
public string AttestationId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// When the attestation was created.
|
||||
/// </summary>
|
||||
public DateTimeOffset AttestedAt { get; }
|
||||
|
||||
private static string EnsureNotNullOrWhiteSpace(string value, string name)
|
||||
=> string.IsNullOrWhiteSpace(value) ? throw new ArgumentException($"{name} must be provided.", name) : value.Trim();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of verifying an evidence attestation.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceVerificationResult
|
||||
{
|
||||
public VexEvidenceVerificationResult(
|
||||
bool isValid,
|
||||
string? failureReason = null,
|
||||
ImmutableDictionary<string, string>? diagnostics = null)
|
||||
{
|
||||
IsValid = isValid;
|
||||
FailureReason = failureReason?.Trim();
|
||||
Diagnostics = diagnostics ?? ImmutableDictionary<string, string>.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the attestation is valid.
|
||||
/// </summary>
|
||||
public bool IsValid { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Reason for failure if not valid.
|
||||
/// </summary>
|
||||
public string? FailureReason { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Additional diagnostic information.
|
||||
/// </summary>
|
||||
public ImmutableDictionary<string, string> Diagnostics { get; }
|
||||
|
||||
public static VexEvidenceVerificationResult Success(ImmutableDictionary<string, string>? diagnostics = null)
|
||||
=> new(true, null, diagnostics);
|
||||
|
||||
public static VexEvidenceVerificationResult Failure(string reason, ImmutableDictionary<string, string>? diagnostics = null)
|
||||
=> new(false, reason, diagnostics);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// in-toto statement for evidence locker attestations.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceInTotoStatement
|
||||
{
|
||||
public const string InTotoStatementType = "https://in-toto.io/Statement/v1";
|
||||
public const string EvidenceLockerPredicateType = "https://stella-ops.org/attestations/evidence-locker/v1";
|
||||
|
||||
public VexEvidenceInTotoStatement(
|
||||
ImmutableArray<VexEvidenceInTotoSubject> subjects,
|
||||
VexEvidenceAttestationPredicate predicate)
|
||||
{
|
||||
Type = InTotoStatementType;
|
||||
Subjects = subjects;
|
||||
PredicateType = EvidenceLockerPredicateType;
|
||||
Predicate = predicate ?? throw new ArgumentNullException(nameof(predicate));
|
||||
}
|
||||
|
||||
public string Type { get; }
|
||||
public ImmutableArray<VexEvidenceInTotoSubject> Subjects { get; }
|
||||
public string PredicateType { get; }
|
||||
public VexEvidenceAttestationPredicate Predicate { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subject of an evidence locker attestation.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceInTotoSubject(
|
||||
string Name,
|
||||
ImmutableDictionary<string, string> Digest);
|
||||
|
||||
/// <summary>
|
||||
/// Predicate for evidence locker attestations.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceAttestationPredicate
|
||||
{
|
||||
public VexEvidenceAttestationPredicate(
|
||||
string manifestId,
|
||||
string tenant,
|
||||
string merkleRoot,
|
||||
int itemCount,
|
||||
DateTimeOffset createdAt,
|
||||
ImmutableDictionary<string, string>? metadata = null)
|
||||
{
|
||||
ManifestId = EnsureNotNullOrWhiteSpace(manifestId, nameof(manifestId));
|
||||
Tenant = EnsureNotNullOrWhiteSpace(tenant, nameof(tenant));
|
||||
MerkleRoot = EnsureNotNullOrWhiteSpace(merkleRoot, nameof(merkleRoot));
|
||||
ItemCount = itemCount;
|
||||
CreatedAt = createdAt;
|
||||
Metadata = metadata ?? ImmutableDictionary<string, string>.Empty;
|
||||
}
|
||||
|
||||
public string ManifestId { get; }
|
||||
public string Tenant { get; }
|
||||
public string MerkleRoot { get; }
|
||||
public int ItemCount { get; }
|
||||
public DateTimeOffset CreatedAt { get; }
|
||||
public ImmutableDictionary<string, string> Metadata { get; }
|
||||
|
||||
public static VexEvidenceAttestationPredicate FromManifest(VexLockerManifest manifest)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
return new VexEvidenceAttestationPredicate(
|
||||
manifest.ManifestId,
|
||||
manifest.Tenant,
|
||||
manifest.MerkleRoot,
|
||||
manifest.Items.Length,
|
||||
manifest.CreatedAt,
|
||||
manifest.Metadata);
|
||||
}
|
||||
|
||||
private static string EnsureNotNullOrWhiteSpace(string value, string name)
|
||||
=> string.IsNullOrWhiteSpace(value) ? throw new ArgumentException($"{name} must be provided.", name) : value.Trim();
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
|
||||
namespace StellaOps.Excititor.Core.Evidence;
|
||||
|
||||
/// <summary>
|
||||
/// Service interface for building evidence locker payloads and Merkle manifests.
|
||||
/// </summary>
|
||||
public interface IVexEvidenceLockerService
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an evidence snapshot item from an observation.
|
||||
/// </summary>
|
||||
VexEvidenceSnapshotItem CreateSnapshotItem(
|
||||
VexObservation observation,
|
||||
string linksetId,
|
||||
VexEvidenceProvenance? provenance = null);
|
||||
|
||||
/// <summary>
|
||||
/// Builds a locker manifest from a collection of observations.
|
||||
/// </summary>
|
||||
VexLockerManifest BuildManifest(
|
||||
string tenant,
|
||||
IEnumerable<VexObservation> observations,
|
||||
Func<VexObservation, string> linksetIdSelector,
|
||||
DateTimeOffset? timestamp = null,
|
||||
int sequence = 1,
|
||||
bool isSealed = false);
|
||||
|
||||
/// <summary>
|
||||
/// Builds a locker manifest from pre-built snapshot items.
|
||||
/// </summary>
|
||||
VexLockerManifest BuildManifest(
|
||||
string tenant,
|
||||
IEnumerable<VexEvidenceSnapshotItem> items,
|
||||
DateTimeOffset? timestamp = null,
|
||||
int sequence = 1,
|
||||
bool isSealed = false);
|
||||
|
||||
/// <summary>
|
||||
/// Verifies a manifest's Merkle root against its items.
|
||||
/// </summary>
|
||||
bool VerifyManifest(VexLockerManifest manifest);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Default implementation of <see cref="IVexEvidenceLockerService"/>.
|
||||
/// </summary>
|
||||
public sealed class VexEvidenceLockerService : IVexEvidenceLockerService
|
||||
{
|
||||
private readonly TimeProvider _timeProvider;
|
||||
|
||||
public VexEvidenceLockerService(TimeProvider? timeProvider = null)
|
||||
{
|
||||
_timeProvider = timeProvider ?? TimeProvider.System;
|
||||
}
|
||||
|
||||
public VexEvidenceSnapshotItem CreateSnapshotItem(
|
||||
VexObservation observation,
|
||||
string linksetId,
|
||||
VexEvidenceProvenance? provenance = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(observation);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(linksetId))
|
||||
{
|
||||
throw new ArgumentException("linksetId must be provided.", nameof(linksetId));
|
||||
}
|
||||
|
||||
return new VexEvidenceSnapshotItem(
|
||||
observationId: observation.ObservationId,
|
||||
providerId: observation.ProviderId,
|
||||
contentHash: observation.Upstream.ContentHash,
|
||||
linksetId: linksetId,
|
||||
dsseEnvelopeHash: null, // Populated by OBS-54-001
|
||||
provenance: provenance ?? VexEvidenceProvenance.Empty);
|
||||
}
|
||||
|
||||
public VexLockerManifest BuildManifest(
|
||||
string tenant,
|
||||
IEnumerable<VexObservation> observations,
|
||||
Func<VexObservation, string> linksetIdSelector,
|
||||
DateTimeOffset? timestamp = null,
|
||||
int sequence = 1,
|
||||
bool isSealed = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(observations);
|
||||
ArgumentNullException.ThrowIfNull(linksetIdSelector);
|
||||
|
||||
var items = observations
|
||||
.Where(o => o is not null)
|
||||
.Select(o => CreateSnapshotItem(o, linksetIdSelector(o)))
|
||||
.ToList();
|
||||
|
||||
return BuildManifest(tenant, items, timestamp, sequence, isSealed);
|
||||
}
|
||||
|
||||
public VexLockerManifest BuildManifest(
|
||||
string tenant,
|
||||
IEnumerable<VexEvidenceSnapshotItem> items,
|
||||
DateTimeOffset? timestamp = null,
|
||||
int sequence = 1,
|
||||
bool isSealed = false)
|
||||
{
|
||||
var ts = timestamp ?? _timeProvider.GetUtcNow();
|
||||
var manifestId = VexLockerManifest.CreateManifestId(tenant, ts, sequence);
|
||||
|
||||
var metadata = isSealed
|
||||
? System.Collections.Immutable.ImmutableDictionary<string, string>.Empty.Add("sealed", "true")
|
||||
: System.Collections.Immutable.ImmutableDictionary<string, string>.Empty;
|
||||
|
||||
return new VexLockerManifest(
|
||||
tenant: tenant,
|
||||
manifestId: manifestId,
|
||||
createdAt: ts,
|
||||
items: items,
|
||||
signature: null,
|
||||
metadata: metadata);
|
||||
}
|
||||
|
||||
public bool VerifyManifest(VexLockerManifest manifest)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
|
||||
var expectedRoot = VexLockerManifest.ComputeMerkleRoot(manifest.Items);
|
||||
return string.Equals(manifest.MerkleRoot, expectedRoot, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace StellaOps.Excititor.Core.Evidence;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single evidence item in a locker payload for sealed-mode auditing.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceSnapshotItem
|
||||
{
|
||||
public VexEvidenceSnapshotItem(
|
||||
string observationId,
|
||||
string providerId,
|
||||
string contentHash,
|
||||
string linksetId,
|
||||
string? dsseEnvelopeHash = null,
|
||||
VexEvidenceProvenance? provenance = null)
|
||||
{
|
||||
ObservationId = EnsureNotNullOrWhiteSpace(observationId, nameof(observationId));
|
||||
ProviderId = EnsureNotNullOrWhiteSpace(providerId, nameof(providerId)).ToLowerInvariant();
|
||||
ContentHash = EnsureNotNullOrWhiteSpace(contentHash, nameof(contentHash));
|
||||
LinksetId = EnsureNotNullOrWhiteSpace(linksetId, nameof(linksetId));
|
||||
DsseEnvelopeHash = TrimToNull(dsseEnvelopeHash);
|
||||
Provenance = provenance ?? VexEvidenceProvenance.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The observation ID this evidence corresponds to.
|
||||
/// </summary>
|
||||
[JsonPropertyName("observationId")]
|
||||
public string ObservationId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The provider that supplied this evidence.
|
||||
/// </summary>
|
||||
[JsonPropertyName("providerId")]
|
||||
public string ProviderId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// SHA-256 hash of the raw observation content.
|
||||
/// </summary>
|
||||
[JsonPropertyName("contentHash")]
|
||||
public string ContentHash { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The linkset ID this evidence relates to.
|
||||
/// </summary>
|
||||
[JsonPropertyName("linksetId")]
|
||||
public string LinksetId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional DSSE envelope hash when attestations are enabled.
|
||||
/// </summary>
|
||||
[JsonPropertyName("dsseEnvelopeHash")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? DsseEnvelopeHash { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Provenance information for this evidence.
|
||||
/// </summary>
|
||||
[JsonPropertyName("provenance")]
|
||||
public VexEvidenceProvenance Provenance { get; }
|
||||
|
||||
private static string EnsureNotNullOrWhiteSpace(string value, string name)
|
||||
=> string.IsNullOrWhiteSpace(value) ? throw new ArgumentException($"{name} must be provided.", name) : value.Trim();
|
||||
|
||||
private static string? TrimToNull(string? value)
|
||||
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provenance information for evidence items.
|
||||
/// </summary>
|
||||
public sealed record VexEvidenceProvenance
|
||||
{
|
||||
public static readonly VexEvidenceProvenance Empty = new("ingest", null, null);
|
||||
|
||||
public VexEvidenceProvenance(
|
||||
string source,
|
||||
int? mirrorGeneration = null,
|
||||
string? exportCenterManifest = null)
|
||||
{
|
||||
Source = EnsureNotNullOrWhiteSpace(source, nameof(source)).ToLowerInvariant();
|
||||
MirrorGeneration = mirrorGeneration;
|
||||
ExportCenterManifest = TrimToNull(exportCenterManifest);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Source type: "mirror" or "ingest".
|
||||
/// </summary>
|
||||
[JsonPropertyName("source")]
|
||||
public string Source { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Mirror generation number when source is "mirror".
|
||||
/// </summary>
|
||||
[JsonPropertyName("mirrorGeneration")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public int? MirrorGeneration { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Export center manifest hash when available.
|
||||
/// </summary>
|
||||
[JsonPropertyName("exportCenterManifest")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? ExportCenterManifest { get; }
|
||||
|
||||
private static string EnsureNotNullOrWhiteSpace(string value, string name)
|
||||
=> string.IsNullOrWhiteSpace(value) ? throw new ArgumentException($"{name} must be provided.", name) : value.Trim();
|
||||
|
||||
private static string? TrimToNull(string? value)
|
||||
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locker manifest containing evidence snapshots with Merkle root for verification.
|
||||
/// </summary>
|
||||
public sealed record VexLockerManifest
|
||||
{
|
||||
public VexLockerManifest(
|
||||
string tenant,
|
||||
string manifestId,
|
||||
DateTimeOffset createdAt,
|
||||
IEnumerable<VexEvidenceSnapshotItem> items,
|
||||
string? signature = null,
|
||||
ImmutableDictionary<string, string>? metadata = null)
|
||||
{
|
||||
Tenant = EnsureNotNullOrWhiteSpace(tenant, nameof(tenant)).ToLowerInvariant();
|
||||
ManifestId = EnsureNotNullOrWhiteSpace(manifestId, nameof(manifestId));
|
||||
CreatedAt = createdAt.ToUniversalTime();
|
||||
Items = NormalizeItems(items);
|
||||
MerkleRoot = ComputeMerkleRoot(Items);
|
||||
Signature = TrimToNull(signature);
|
||||
Metadata = NormalizeMetadata(metadata);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tenant this manifest belongs to.
|
||||
/// </summary>
|
||||
[JsonPropertyName("tenant")]
|
||||
public string Tenant { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Unique manifest identifier.
|
||||
/// </summary>
|
||||
[JsonPropertyName("manifestId")]
|
||||
public string ManifestId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// When this manifest was created.
|
||||
/// </summary>
|
||||
[JsonPropertyName("createdAt")]
|
||||
public DateTimeOffset CreatedAt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Evidence items in deterministic order.
|
||||
/// </summary>
|
||||
[JsonPropertyName("items")]
|
||||
public ImmutableArray<VexEvidenceSnapshotItem> Items { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Merkle root computed over item content hashes.
|
||||
/// </summary>
|
||||
[JsonPropertyName("merkleRoot")]
|
||||
public string MerkleRoot { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional DSSE signature (populated by OBS-54-001).
|
||||
/// </summary>
|
||||
[JsonPropertyName("signature")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? Signature { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Additional metadata (e.g., sealed mode flag).
|
||||
/// </summary>
|
||||
[JsonPropertyName("metadata")]
|
||||
public ImmutableDictionary<string, string> Metadata { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new manifest with an attached signature.
|
||||
/// </summary>
|
||||
public VexLockerManifest WithSignature(string signature)
|
||||
{
|
||||
return new VexLockerManifest(
|
||||
Tenant,
|
||||
ManifestId,
|
||||
CreatedAt,
|
||||
Items,
|
||||
signature,
|
||||
Metadata);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic manifest ID.
|
||||
/// </summary>
|
||||
public static string CreateManifestId(string tenant, DateTimeOffset timestamp, int sequence)
|
||||
{
|
||||
var normalizedTenant = (tenant ?? "default").Trim().ToLowerInvariant();
|
||||
var date = timestamp.ToUniversalTime().ToString("yyyy-MM-dd");
|
||||
return $"locker:excititor:{normalizedTenant}:{date}:{sequence:D4}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes Merkle root from a list of hashes.
|
||||
/// </summary>
|
||||
public static string ComputeMerkleRoot(ImmutableArray<VexEvidenceSnapshotItem> items)
|
||||
{
|
||||
if (items.Length == 0)
|
||||
{
|
||||
return "sha256:" + Convert.ToHexString(SHA256.HashData(Array.Empty<byte>())).ToLowerInvariant();
|
||||
}
|
||||
|
||||
var hashes = items
|
||||
.Select(i => i.ContentHash.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase)
|
||||
? i.ContentHash[7..]
|
||||
: i.ContentHash)
|
||||
.ToList();
|
||||
|
||||
return ComputeMerkleRootFromHashes(hashes);
|
||||
}
|
||||
|
||||
private static string ComputeMerkleRootFromHashes(List<string> hashes)
|
||||
{
|
||||
if (hashes.Count == 0)
|
||||
{
|
||||
return "sha256:" + Convert.ToHexString(SHA256.HashData(Array.Empty<byte>())).ToLowerInvariant();
|
||||
}
|
||||
|
||||
if (hashes.Count == 1)
|
||||
{
|
||||
return "sha256:" + hashes[0].ToLowerInvariant();
|
||||
}
|
||||
|
||||
// Pad to even number if necessary
|
||||
if (hashes.Count % 2 != 0)
|
||||
{
|
||||
hashes.Add(hashes[^1]);
|
||||
}
|
||||
|
||||
var nextLevel = new List<string>();
|
||||
for (var i = 0; i < hashes.Count; i += 2)
|
||||
{
|
||||
var combined = hashes[i].ToLowerInvariant() + hashes[i + 1].ToLowerInvariant();
|
||||
var bytes = Convert.FromHexString(combined);
|
||||
var hash = SHA256.HashData(bytes);
|
||||
nextLevel.Add(Convert.ToHexString(hash).ToLowerInvariant());
|
||||
}
|
||||
|
||||
return ComputeMerkleRootFromHashes(nextLevel);
|
||||
}
|
||||
|
||||
private static ImmutableArray<VexEvidenceSnapshotItem> NormalizeItems(IEnumerable<VexEvidenceSnapshotItem>? items)
|
||||
{
|
||||
if (items is null)
|
||||
{
|
||||
return ImmutableArray<VexEvidenceSnapshotItem>.Empty;
|
||||
}
|
||||
|
||||
// Sort by observationId, then providerId for deterministic ordering
|
||||
return items
|
||||
.Where(i => i is not null)
|
||||
.OrderBy(i => i.ObservationId, StringComparer.Ordinal)
|
||||
.ThenBy(i => i.ProviderId, StringComparer.OrdinalIgnoreCase)
|
||||
.ToImmutableArray();
|
||||
}
|
||||
|
||||
private static ImmutableDictionary<string, string> NormalizeMetadata(ImmutableDictionary<string, string>? metadata)
|
||||
{
|
||||
if (metadata is null || metadata.Count == 0)
|
||||
{
|
||||
return ImmutableDictionary<string, string>.Empty;
|
||||
}
|
||||
|
||||
var builder = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
|
||||
foreach (var pair in metadata.OrderBy(kv => kv.Key, StringComparer.Ordinal))
|
||||
{
|
||||
var key = TrimToNull(pair.Key);
|
||||
var value = TrimToNull(pair.Value);
|
||||
if (key is null || value is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
builder[key] = value;
|
||||
}
|
||||
|
||||
return builder.ToImmutable();
|
||||
}
|
||||
|
||||
private static string EnsureNotNullOrWhiteSpace(string value, string name)
|
||||
=> string.IsNullOrWhiteSpace(value) ? throw new ArgumentException($"{name} must be provided.", name) : value.Trim();
|
||||
|
||||
private static string? TrimToNull(string? value)
|
||||
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace StellaOps.Excititor.Core.Observations;
|
||||
|
||||
/// <summary>
|
||||
/// Publishes vex.linkset.updated events to downstream consumers.
|
||||
/// Implementations may persist to MongoDB, publish to NATS, or both.
|
||||
/// </summary>
|
||||
public interface IVexLinksetEventPublisher
|
||||
{
|
||||
/// <summary>
|
||||
/// Publishes a linkset updated event.
|
||||
/// </summary>
|
||||
Task PublishAsync(VexLinksetUpdatedEvent @event, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Publishes multiple linkset updated events in a batch.
|
||||
/// </summary>
|
||||
Task PublishManyAsync(IEnumerable<VexLinksetUpdatedEvent> events, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
namespace StellaOps.Excititor.Core.Observations;
|
||||
|
||||
/// <summary>
|
||||
/// Persistence abstraction for VEX linksets with tenant-isolated operations.
|
||||
/// Linksets correlate observations and capture conflict annotations.
|
||||
/// </summary>
|
||||
public interface IVexLinksetStore
|
||||
{
|
||||
/// <summary>
|
||||
/// Persists a new linkset. Returns true if inserted, false if it already exists.
|
||||
/// </summary>
|
||||
ValueTask<bool> InsertAsync(
|
||||
VexLinkset linkset,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Persists or updates a linkset. Returns true if inserted, false if updated.
|
||||
/// </summary>
|
||||
ValueTask<bool> UpsertAsync(
|
||||
VexLinkset linkset,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a linkset by tenant and linkset ID.
|
||||
/// </summary>
|
||||
ValueTask<VexLinkset?> GetByIdAsync(
|
||||
string tenant,
|
||||
string linksetId,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves or creates a linkset for the given vulnerability and product key.
|
||||
/// </summary>
|
||||
ValueTask<VexLinkset> GetOrCreateAsync(
|
||||
string tenant,
|
||||
string vulnerabilityId,
|
||||
string productKey,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Finds linksets by vulnerability ID.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<VexLinkset>> FindByVulnerabilityAsync(
|
||||
string tenant,
|
||||
string vulnerabilityId,
|
||||
int limit,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Finds linksets by product key.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<VexLinkset>> FindByProductKeyAsync(
|
||||
string tenant,
|
||||
string productKey,
|
||||
int limit,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Finds linksets that have disagreements (conflicts).
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<VexLinkset>> FindWithConflictsAsync(
|
||||
string tenant,
|
||||
int limit,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Finds linksets by provider ID.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<VexLinkset>> FindByProviderAsync(
|
||||
string tenant,
|
||||
string providerId,
|
||||
int limit,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a linkset by tenant and linkset ID. Returns true if deleted.
|
||||
/// </summary>
|
||||
ValueTask<bool> DeleteAsync(
|
||||
string tenant,
|
||||
string linksetId,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the count of linksets for the specified tenant.
|
||||
/// </summary>
|
||||
ValueTask<long> CountAsync(
|
||||
string tenant,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the count of linksets with conflicts for the specified tenant.
|
||||
/// </summary>
|
||||
ValueTask<long> CountWithConflictsAsync(
|
||||
string tenant,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace StellaOps.Excititor.Core.Observations;
|
||||
|
||||
/// <summary>
|
||||
/// Persistence abstraction for VEX observations with tenant-isolated write operations.
|
||||
/// </summary>
|
||||
public interface IVexObservationStore
|
||||
{
|
||||
/// <summary>
|
||||
/// Persists a new observation. Returns true if inserted, false if it already exists.
|
||||
/// </summary>
|
||||
ValueTask<bool> InsertAsync(
|
||||
VexObservation observation,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Persists or updates an observation. Returns true if inserted, false if updated.
|
||||
/// </summary>
|
||||
ValueTask<bool> UpsertAsync(
|
||||
VexObservation observation,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Persists multiple observations in a batch. Returns the count of newly inserted observations.
|
||||
/// </summary>
|
||||
ValueTask<int> InsertManyAsync(
|
||||
string tenant,
|
||||
IEnumerable<VexObservation> observations,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves an observation by tenant and observation ID.
|
||||
/// </summary>
|
||||
ValueTask<VexObservation?> GetByIdAsync(
|
||||
string tenant,
|
||||
string observationId,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves observations for a specific vulnerability and product key.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<VexObservation>> FindByVulnerabilityAndProductAsync(
|
||||
string tenant,
|
||||
string vulnerabilityId,
|
||||
string productKey,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves observations by provider.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<VexObservation>> FindByProviderAsync(
|
||||
string tenant,
|
||||
string providerId,
|
||||
int limit,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes an observation by tenant and observation ID. Returns true if deleted.
|
||||
/// </summary>
|
||||
ValueTask<bool> DeleteAsync(
|
||||
string tenant,
|
||||
string observationId,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the count of observations for the specified tenant.
|
||||
/// </summary>
|
||||
ValueTask<long> CountAsync(
|
||||
string tenant,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace StellaOps.Excititor.Core.Observations;
|
||||
|
||||
/// <summary>
|
||||
/// Service interface for emitting timeline events during ingest/linkset operations.
|
||||
/// Implementations should emit events asynchronously without blocking the main operation.
|
||||
/// </summary>
|
||||
public interface IVexTimelineEventEmitter
|
||||
{
|
||||
/// <summary>
|
||||
/// Emits a timeline event for an observation ingest operation.
|
||||
/// </summary>
|
||||
ValueTask EmitObservationIngestAsync(
|
||||
string tenant,
|
||||
string providerId,
|
||||
string streamId,
|
||||
string traceId,
|
||||
string observationId,
|
||||
string evidenceHash,
|
||||
string justificationSummary,
|
||||
ImmutableDictionary<string, string>? attributes = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Emits a timeline event for a linkset update operation.
|
||||
/// </summary>
|
||||
ValueTask EmitLinksetUpdateAsync(
|
||||
string tenant,
|
||||
string providerId,
|
||||
string streamId,
|
||||
string traceId,
|
||||
string linksetId,
|
||||
string vulnerabilityId,
|
||||
string productKey,
|
||||
string payloadHash,
|
||||
string justificationSummary,
|
||||
ImmutableDictionary<string, string>? attributes = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Emits a timeline event for a generic operation.
|
||||
/// </summary>
|
||||
ValueTask EmitAsync(
|
||||
TimelineEvent evt,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Emits multiple timeline events in a batch.
|
||||
/// </summary>
|
||||
ValueTask EmitBatchAsync(
|
||||
string tenant,
|
||||
IEnumerable<TimelineEvent> events,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Well-known timeline event types for Excititor operations.
|
||||
/// </summary>
|
||||
public static class VexTimelineEventTypes
|
||||
{
|
||||
/// <summary>
|
||||
/// An observation was ingested.
|
||||
/// </summary>
|
||||
public const string ObservationIngested = "vex.observation.ingested";
|
||||
|
||||
/// <summary>
|
||||
/// An observation was updated.
|
||||
/// </summary>
|
||||
public const string ObservationUpdated = "vex.observation.updated";
|
||||
|
||||
/// <summary>
|
||||
/// An observation was superseded by another.
|
||||
/// </summary>
|
||||
public const string ObservationSuperseded = "vex.observation.superseded";
|
||||
|
||||
/// <summary>
|
||||
/// A linkset was created.
|
||||
/// </summary>
|
||||
public const string LinksetCreated = "vex.linkset.created";
|
||||
|
||||
/// <summary>
|
||||
/// A linkset was updated with new observations.
|
||||
/// </summary>
|
||||
public const string LinksetUpdated = "vex.linkset.updated";
|
||||
|
||||
/// <summary>
|
||||
/// A linkset conflict was detected.
|
||||
/// </summary>
|
||||
public const string LinksetConflictDetected = "vex.linkset.conflict_detected";
|
||||
|
||||
/// <summary>
|
||||
/// A linkset conflict was resolved.
|
||||
/// </summary>
|
||||
public const string LinksetConflictResolved = "vex.linkset.conflict_resolved";
|
||||
|
||||
/// <summary>
|
||||
/// Evidence was sealed to the locker.
|
||||
/// </summary>
|
||||
public const string EvidenceSealed = "vex.evidence.sealed";
|
||||
|
||||
/// <summary>
|
||||
/// An attestation was attached.
|
||||
/// </summary>
|
||||
public const string AttestationAttached = "vex.attestation.attached";
|
||||
|
||||
/// <summary>
|
||||
/// An attestation was verified.
|
||||
/// </summary>
|
||||
public const string AttestationVerified = "vex.attestation.verified";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Well-known attribute keys for timeline events.
|
||||
/// </summary>
|
||||
public static class VexTimelineEventAttributes
|
||||
{
|
||||
public const string ObservationId = "observation_id";
|
||||
public const string LinksetId = "linkset_id";
|
||||
public const string VulnerabilityId = "vulnerability_id";
|
||||
public const string ProductKey = "product_key";
|
||||
public const string Status = "status";
|
||||
public const string ConflictType = "conflict_type";
|
||||
public const string AttestationId = "attestation_id";
|
||||
public const string SupersededBy = "superseded_by";
|
||||
public const string Supersedes = "supersedes";
|
||||
public const string ObservationCount = "observation_count";
|
||||
public const string ConflictCount = "conflict_count";
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
namespace StellaOps.Excititor.Core.Observations;
|
||||
|
||||
/// <summary>
|
||||
/// Persistence abstraction for VEX timeline events.
|
||||
/// Timeline events capture ingest/linkset changes with trace IDs, justification summaries,
|
||||
/// and evidence hashes so downstream systems can replay raw facts chronologically.
|
||||
/// </summary>
|
||||
public interface IVexTimelineEventStore
|
||||
{
|
||||
/// <summary>
|
||||
/// Persists a new timeline event. Returns the event ID if successful.
|
||||
/// </summary>
|
||||
ValueTask<string> InsertAsync(
|
||||
TimelineEvent evt,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Persists multiple timeline events in a batch. Returns the count of successfully inserted events.
|
||||
/// </summary>
|
||||
ValueTask<int> InsertManyAsync(
|
||||
string tenant,
|
||||
IEnumerable<TimelineEvent> events,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves timeline events for a tenant within a time range.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<TimelineEvent>> FindByTimeRangeAsync(
|
||||
string tenant,
|
||||
DateTimeOffset from,
|
||||
DateTimeOffset to,
|
||||
int limit,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves timeline events by trace ID for correlation.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<TimelineEvent>> FindByTraceIdAsync(
|
||||
string tenant,
|
||||
string traceId,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves timeline events by provider ID.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<TimelineEvent>> FindByProviderAsync(
|
||||
string tenant,
|
||||
string providerId,
|
||||
int limit,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves timeline events by event type.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<TimelineEvent>> FindByEventTypeAsync(
|
||||
string tenant,
|
||||
string eventType,
|
||||
int limit,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the most recent timeline events for a tenant.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<TimelineEvent>> GetRecentAsync(
|
||||
string tenant,
|
||||
int limit,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a single timeline event by ID.
|
||||
/// </summary>
|
||||
ValueTask<TimelineEvent?> GetByIdAsync(
|
||||
string tenant,
|
||||
string eventId,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the count of timeline events for the specified tenant.
|
||||
/// </summary>
|
||||
ValueTask<long> CountAsync(
|
||||
string tenant,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the count of timeline events for the specified tenant within a time range.
|
||||
/// </summary>
|
||||
ValueTask<long> CountInRangeAsync(
|
||||
string tenant,
|
||||
DateTimeOffset from,
|
||||
DateTimeOffset to,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace StellaOps.Excititor.Core.Observations;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a VEX linkset correlating multiple observations for a specific
|
||||
/// vulnerability and product key. Linksets capture disagreements (conflicts)
|
||||
/// between providers without deciding a winner.
|
||||
/// </summary>
|
||||
public sealed record VexLinkset
|
||||
{
|
||||
public VexLinkset(
|
||||
string linksetId,
|
||||
string tenant,
|
||||
string vulnerabilityId,
|
||||
string productKey,
|
||||
IEnumerable<VexLinksetObservationRefModel> observations,
|
||||
IEnumerable<VexObservationDisagreement>? disagreements = null,
|
||||
DateTimeOffset? createdAt = null,
|
||||
DateTimeOffset? updatedAt = null)
|
||||
{
|
||||
LinksetId = VexObservation.EnsureNotNullOrWhiteSpace(linksetId, nameof(linksetId));
|
||||
Tenant = VexObservation.EnsureNotNullOrWhiteSpace(tenant, nameof(tenant)).ToLowerInvariant();
|
||||
VulnerabilityId = VexObservation.EnsureNotNullOrWhiteSpace(vulnerabilityId, nameof(vulnerabilityId));
|
||||
ProductKey = VexObservation.EnsureNotNullOrWhiteSpace(productKey, nameof(productKey));
|
||||
Observations = NormalizeObservations(observations);
|
||||
Disagreements = NormalizeDisagreements(disagreements);
|
||||
CreatedAt = (createdAt ?? DateTimeOffset.UtcNow).ToUniversalTime();
|
||||
UpdatedAt = (updatedAt ?? CreatedAt).ToUniversalTime();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unique identifier for this linkset. Typically a SHA256 hash over
|
||||
/// (tenant, vulnerabilityId, productKey) for deterministic addressing.
|
||||
/// </summary>
|
||||
public string LinksetId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Tenant identifier (normalized to lowercase).
|
||||
/// </summary>
|
||||
public string Tenant { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The vulnerability identifier (CVE, GHSA, vendor ID).
|
||||
/// </summary>
|
||||
public string VulnerabilityId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Product key (typically a PURL or CPE).
|
||||
/// </summary>
|
||||
public string ProductKey { get; }
|
||||
|
||||
/// <summary>
|
||||
/// References to observations that contribute to this linkset.
|
||||
/// </summary>
|
||||
public ImmutableArray<VexLinksetObservationRefModel> Observations { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Conflict annotations capturing disagreements between providers.
|
||||
/// </summary>
|
||||
public ImmutableArray<VexObservationDisagreement> Disagreements { get; }
|
||||
|
||||
/// <summary>
|
||||
/// When this linkset was first created.
|
||||
/// </summary>
|
||||
public DateTimeOffset CreatedAt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// When this linkset was last updated.
|
||||
/// </summary>
|
||||
public DateTimeOffset UpdatedAt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Distinct provider IDs contributing to this linkset.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> ProviderIds =>
|
||||
Observations.Select(o => o.ProviderId)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Distinct statuses observed in this linkset.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Statuses =>
|
||||
Observations.Select(o => o.Status)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.OrderBy(s => s, StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Whether this linkset contains disagreements (conflicts).
|
||||
/// </summary>
|
||||
public bool HasConflicts => !Disagreements.IsDefaultOrEmpty && Disagreements.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Confidence level based on the linkset state.
|
||||
/// </summary>
|
||||
public VexLinksetConfidence Confidence
|
||||
{
|
||||
get
|
||||
{
|
||||
if (HasConflicts)
|
||||
{
|
||||
return VexLinksetConfidence.Low;
|
||||
}
|
||||
|
||||
if (Observations.Length == 0)
|
||||
{
|
||||
return VexLinksetConfidence.Low;
|
||||
}
|
||||
|
||||
var distinctStatuses = Statuses.Count;
|
||||
if (distinctStatuses > 1)
|
||||
{
|
||||
return VexLinksetConfidence.Low;
|
||||
}
|
||||
|
||||
var distinctProviders = ProviderIds.Count;
|
||||
if (distinctProviders >= 2)
|
||||
{
|
||||
return VexLinksetConfidence.High;
|
||||
}
|
||||
|
||||
return VexLinksetConfidence.Medium;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic linkset ID from key components.
|
||||
/// </summary>
|
||||
public static string CreateLinksetId(string tenant, string vulnerabilityId, string productKey)
|
||||
{
|
||||
var normalizedTenant = (tenant ?? string.Empty).Trim().ToLowerInvariant();
|
||||
var normalizedVuln = (vulnerabilityId ?? string.Empty).Trim();
|
||||
var normalizedProduct = (productKey ?? string.Empty).Trim();
|
||||
|
||||
var input = $"{normalizedTenant}|{normalizedVuln}|{normalizedProduct}";
|
||||
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(input));
|
||||
return $"sha256:{Convert.ToHexString(hash).ToLowerInvariant()}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new linkset with updated observations and recomputed disagreements.
|
||||
/// </summary>
|
||||
public VexLinkset WithObservations(
|
||||
IEnumerable<VexLinksetObservationRefModel> observations,
|
||||
IEnumerable<VexObservationDisagreement>? disagreements = null)
|
||||
{
|
||||
return new VexLinkset(
|
||||
LinksetId,
|
||||
Tenant,
|
||||
VulnerabilityId,
|
||||
ProductKey,
|
||||
observations,
|
||||
disagreements,
|
||||
CreatedAt,
|
||||
DateTimeOffset.UtcNow);
|
||||
}
|
||||
|
||||
private static ImmutableArray<VexLinksetObservationRefModel> NormalizeObservations(
|
||||
IEnumerable<VexLinksetObservationRefModel>? observations)
|
||||
{
|
||||
if (observations is null)
|
||||
{
|
||||
return ImmutableArray<VexLinksetObservationRefModel>.Empty;
|
||||
}
|
||||
|
||||
var set = new SortedSet<VexLinksetObservationRefModel>(VexLinksetObservationRefComparer.Instance);
|
||||
foreach (var item in observations)
|
||||
{
|
||||
if (item is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var obsId = VexObservation.TrimToNull(item.ObservationId);
|
||||
var provider = VexObservation.TrimToNull(item.ProviderId);
|
||||
var status = VexObservation.TrimToNull(item.Status);
|
||||
if (obsId is null || provider is null || status is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
double? clamped = item.Confidence is null ? null : Math.Clamp(item.Confidence.Value, 0.0, 1.0);
|
||||
set.Add(new VexLinksetObservationRefModel(obsId, provider, status, clamped));
|
||||
}
|
||||
|
||||
return set.Count == 0 ? ImmutableArray<VexLinksetObservationRefModel>.Empty : set.ToImmutableArray();
|
||||
}
|
||||
|
||||
private static ImmutableArray<VexObservationDisagreement> NormalizeDisagreements(
|
||||
IEnumerable<VexObservationDisagreement>? disagreements)
|
||||
{
|
||||
if (disagreements is null)
|
||||
{
|
||||
return ImmutableArray<VexObservationDisagreement>.Empty;
|
||||
}
|
||||
|
||||
var set = new SortedSet<VexObservationDisagreement>(DisagreementComparer.Instance);
|
||||
foreach (var disagreement in disagreements)
|
||||
{
|
||||
if (disagreement is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var normalizedProvider = VexObservation.TrimToNull(disagreement.ProviderId);
|
||||
var normalizedStatus = VexObservation.TrimToNull(disagreement.Status);
|
||||
|
||||
if (normalizedProvider is null || normalizedStatus is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var normalizedJustification = VexObservation.TrimToNull(disagreement.Justification);
|
||||
double? clampedConfidence = disagreement.Confidence is null
|
||||
? null
|
||||
: Math.Clamp(disagreement.Confidence.Value, 0.0, 1.0);
|
||||
|
||||
set.Add(new VexObservationDisagreement(
|
||||
normalizedProvider,
|
||||
normalizedStatus,
|
||||
normalizedJustification,
|
||||
clampedConfidence));
|
||||
}
|
||||
|
||||
return set.Count == 0 ? ImmutableArray<VexObservationDisagreement>.Empty : set.ToImmutableArray();
|
||||
}
|
||||
|
||||
private sealed class DisagreementComparer : IComparer<VexObservationDisagreement>
|
||||
{
|
||||
public static readonly DisagreementComparer Instance = new();
|
||||
|
||||
public int Compare(VexObservationDisagreement? x, VexObservationDisagreement? y)
|
||||
{
|
||||
if (ReferenceEquals(x, y))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (x is null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (y is null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
var providerCompare = StringComparer.OrdinalIgnoreCase.Compare(x.ProviderId, y.ProviderId);
|
||||
if (providerCompare != 0)
|
||||
{
|
||||
return providerCompare;
|
||||
}
|
||||
|
||||
var statusCompare = StringComparer.OrdinalIgnoreCase.Compare(x.Status, y.Status);
|
||||
if (statusCompare != 0)
|
||||
{
|
||||
return statusCompare;
|
||||
}
|
||||
|
||||
var justificationCompare = StringComparer.OrdinalIgnoreCase.Compare(
|
||||
x.Justification ?? string.Empty,
|
||||
y.Justification ?? string.Empty);
|
||||
if (justificationCompare != 0)
|
||||
{
|
||||
return justificationCompare;
|
||||
}
|
||||
|
||||
return Nullable.Compare(x.Confidence, y.Confidence);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Confidence level for a linkset based on agreement between providers.
|
||||
/// </summary>
|
||||
public enum VexLinksetConfidence
|
||||
{
|
||||
/// <summary>
|
||||
/// Low confidence: conflicts exist or insufficient observations.
|
||||
/// </summary>
|
||||
Low,
|
||||
|
||||
/// <summary>
|
||||
/// Medium confidence: single provider or consistent observations.
|
||||
/// </summary>
|
||||
Medium,
|
||||
|
||||
/// <summary>
|
||||
/// High confidence: multiple providers agree.
|
||||
/// </summary>
|
||||
High
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace StellaOps.Excititor.Core.Observations;
|
||||
|
||||
/// <summary>
|
||||
/// Computes disagreements (conflicts) from VEX observations without choosing winners.
|
||||
/// Excititor remains aggregation-only; downstream consumers use disagreements to highlight
|
||||
/// conflicts and apply their own decision rules (AOC-19-002).
|
||||
/// </summary>
|
||||
public sealed class VexLinksetDisagreementService
|
||||
{
|
||||
/// <summary>
|
||||
/// Analyzes observations and returns disagreements where providers report different
|
||||
/// statuses or justifications for the same vulnerability/product combination.
|
||||
/// </summary>
|
||||
public ImmutableArray<VexObservationDisagreement> ComputeDisagreements(
|
||||
IEnumerable<VexObservation> observations)
|
||||
{
|
||||
if (observations is null)
|
||||
{
|
||||
return ImmutableArray<VexObservationDisagreement>.Empty;
|
||||
}
|
||||
|
||||
var observationList = observations
|
||||
.Where(o => o is not null)
|
||||
.ToList();
|
||||
|
||||
if (observationList.Count < 2)
|
||||
{
|
||||
return ImmutableArray<VexObservationDisagreement>.Empty;
|
||||
}
|
||||
|
||||
// Group by (vulnerabilityId, productKey)
|
||||
var groups = observationList
|
||||
.SelectMany(obs => obs.Statements.Select(stmt => (obs, stmt)))
|
||||
.GroupBy(x => new
|
||||
{
|
||||
VulnerabilityId = Normalize(x.stmt.VulnerabilityId),
|
||||
ProductKey = Normalize(x.stmt.ProductKey)
|
||||
});
|
||||
|
||||
var disagreements = new List<VexObservationDisagreement>();
|
||||
|
||||
foreach (var group in groups)
|
||||
{
|
||||
var groupDisagreements = DetectGroupDisagreements(group.ToList());
|
||||
disagreements.AddRange(groupDisagreements);
|
||||
}
|
||||
|
||||
return disagreements
|
||||
.Distinct(DisagreementComparer.Instance)
|
||||
.OrderBy(d => d.ProviderId, StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(d => d.Status, StringComparer.OrdinalIgnoreCase)
|
||||
.ToImmutableArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Analyzes observations for a specific linkset and returns disagreements.
|
||||
/// </summary>
|
||||
public ImmutableArray<VexObservationDisagreement> ComputeDisagreementsForLinkset(
|
||||
IEnumerable<VexLinksetObservationRefModel> observationRefs)
|
||||
{
|
||||
if (observationRefs is null)
|
||||
{
|
||||
return ImmutableArray<VexObservationDisagreement>.Empty;
|
||||
}
|
||||
|
||||
var refList = observationRefs
|
||||
.Where(r => r is not null)
|
||||
.ToList();
|
||||
|
||||
if (refList.Count < 2)
|
||||
{
|
||||
return ImmutableArray<VexObservationDisagreement>.Empty;
|
||||
}
|
||||
|
||||
// Group by status to detect conflicts
|
||||
var statusGroups = refList
|
||||
.GroupBy(r => Normalize(r.Status))
|
||||
.ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (statusGroups.Count <= 1)
|
||||
{
|
||||
// All providers agree on status
|
||||
return ImmutableArray<VexObservationDisagreement>.Empty;
|
||||
}
|
||||
|
||||
// Multiple statuses = disagreement
|
||||
// Generate disagreement entries for each provider-status combination
|
||||
var disagreements = refList
|
||||
.Select(r => new VexObservationDisagreement(
|
||||
providerId: r.ProviderId,
|
||||
status: r.Status,
|
||||
justification: null,
|
||||
confidence: ComputeConfidence(r.Status, statusGroups)))
|
||||
.Distinct(DisagreementComparer.Instance)
|
||||
.OrderBy(d => d.ProviderId, StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(d => d.Status, StringComparer.OrdinalIgnoreCase)
|
||||
.ToImmutableArray();
|
||||
|
||||
return disagreements;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a linkset with computed disagreements based on its observations.
|
||||
/// Returns a new linkset with updated disagreements.
|
||||
/// </summary>
|
||||
public VexLinkset UpdateLinksetDisagreements(VexLinkset linkset)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(linkset);
|
||||
|
||||
var disagreements = ComputeDisagreementsForLinkset(linkset.Observations);
|
||||
|
||||
return linkset.WithObservations(
|
||||
linkset.Observations,
|
||||
disagreements);
|
||||
}
|
||||
|
||||
private static IEnumerable<VexObservationDisagreement> DetectGroupDisagreements(
|
||||
List<(VexObservation obs, VexObservationStatement stmt)> group)
|
||||
{
|
||||
if (group.Count < 2)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
// Group by provider to get unique provider perspectives
|
||||
var byProvider = group
|
||||
.GroupBy(x => Normalize(x.obs.ProviderId))
|
||||
.Select(g => new
|
||||
{
|
||||
ProviderId = g.Key,
|
||||
Status = Normalize(g.First().stmt.Status.ToString()),
|
||||
Justification = g.First().stmt.Justification?.ToString()
|
||||
})
|
||||
.ToList();
|
||||
|
||||
// Count status frequencies
|
||||
var statusCounts = byProvider
|
||||
.GroupBy(p => p.Status, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
// If all providers agree on status, no disagreement
|
||||
if (statusCounts.Count <= 1)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
// Multiple statuses = disagreement
|
||||
// Report each provider's position as a disagreement
|
||||
var totalProviders = byProvider.Count;
|
||||
|
||||
foreach (var provider in byProvider)
|
||||
{
|
||||
var statusCount = statusCounts[provider.Status];
|
||||
var confidence = (double)statusCount / totalProviders;
|
||||
|
||||
yield return new VexObservationDisagreement(
|
||||
providerId: provider.ProviderId,
|
||||
status: provider.Status,
|
||||
justification: provider.Justification,
|
||||
confidence: confidence);
|
||||
}
|
||||
}
|
||||
|
||||
private static double ComputeConfidence(
|
||||
string status,
|
||||
Dictionary<string, List<VexLinksetObservationRefModel>> statusGroups)
|
||||
{
|
||||
var totalCount = statusGroups.Values.Sum(g => g.Count);
|
||||
if (totalCount == 0)
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
if (statusGroups.TryGetValue(status, out var group))
|
||||
{
|
||||
return (double)group.Count / totalCount;
|
||||
}
|
||||
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
private static string Normalize(string value)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value)
|
||||
? string.Empty
|
||||
: value.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
private sealed class DisagreementComparer : IEqualityComparer<VexObservationDisagreement>
|
||||
{
|
||||
public static readonly DisagreementComparer Instance = new();
|
||||
|
||||
public bool Equals(VexObservationDisagreement? x, VexObservationDisagreement? y)
|
||||
{
|
||||
if (ReferenceEquals(x, y))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (x is null || y is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return string.Equals(x.ProviderId, y.ProviderId, StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(x.Status, y.Status, StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(x.Justification, y.Justification, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public int GetHashCode(VexObservationDisagreement obj)
|
||||
{
|
||||
var hash = new HashCode();
|
||||
hash.Add(obj.ProviderId, StringComparer.OrdinalIgnoreCase);
|
||||
hash.Add(obj.Status, StringComparer.OrdinalIgnoreCase);
|
||||
hash.Add(obj.Justification, StringComparer.OrdinalIgnoreCase);
|
||||
return hash.ToHashCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace StellaOps.Excititor.Core.Orchestration;
|
||||
|
||||
/// <summary>
|
||||
/// Client interface for the orchestrator worker SDK.
|
||||
/// Emits heartbeats, progress, and artifact hashes for deterministic, restartable ingestion.
|
||||
/// </summary>
|
||||
public interface IVexWorkerOrchestratorClient
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new job context for a provider run.
|
||||
/// </summary>
|
||||
ValueTask<VexWorkerJobContext> StartJobAsync(
|
||||
string tenant,
|
||||
string connectorId,
|
||||
string? checkpoint,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Emits a heartbeat for the given job.
|
||||
/// </summary>
|
||||
ValueTask SendHeartbeatAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerHeartbeat heartbeat,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Records an artifact produced during the job.
|
||||
/// </summary>
|
||||
ValueTask RecordArtifactAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerArtifact artifact,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Marks the job as completed successfully.
|
||||
/// </summary>
|
||||
ValueTask CompleteJobAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerJobResult result,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Marks the job as failed.
|
||||
/// </summary>
|
||||
ValueTask FailJobAsync(
|
||||
VexWorkerJobContext context,
|
||||
string errorCode,
|
||||
string? errorMessage,
|
||||
int? retryAfterSeconds,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Marks the job as failed with a classified error.
|
||||
/// </summary>
|
||||
ValueTask FailJobAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerError error,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Polls for pending commands from the orchestrator.
|
||||
/// </summary>
|
||||
ValueTask<VexWorkerCommand?> GetPendingCommandAsync(
|
||||
VexWorkerJobContext context,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Acknowledges that a command has been processed.
|
||||
/// </summary>
|
||||
ValueTask AcknowledgeCommandAsync(
|
||||
VexWorkerJobContext context,
|
||||
long commandSequence,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Saves a checkpoint for resumable ingestion.
|
||||
/// </summary>
|
||||
ValueTask SaveCheckpointAsync(
|
||||
VexWorkerJobContext context,
|
||||
VexWorkerCheckpoint checkpoint,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Loads the most recent checkpoint for a connector.
|
||||
/// </summary>
|
||||
ValueTask<VexWorkerCheckpoint?> LoadCheckpointAsync(
|
||||
string connectorId,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Context for an active worker job.
|
||||
/// </summary>
|
||||
public sealed record VexWorkerJobContext
|
||||
{
|
||||
public VexWorkerJobContext(
|
||||
string tenant,
|
||||
string connectorId,
|
||||
Guid runId,
|
||||
string? checkpoint,
|
||||
DateTimeOffset startedAt)
|
||||
{
|
||||
Tenant = EnsureNotNullOrWhiteSpace(tenant, nameof(tenant));
|
||||
ConnectorId = EnsureNotNullOrWhiteSpace(connectorId, nameof(connectorId));
|
||||
RunId = runId;
|
||||
Checkpoint = checkpoint?.Trim();
|
||||
StartedAt = startedAt;
|
||||
}
|
||||
|
||||
public string Tenant { get; }
|
||||
public string ConnectorId { get; }
|
||||
public Guid RunId { get; }
|
||||
public string? Checkpoint { get; }
|
||||
public DateTimeOffset StartedAt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Current sequence number for heartbeats.
|
||||
/// </summary>
|
||||
public long Sequence { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Increments and returns the next sequence number.
|
||||
/// </summary>
|
||||
public long NextSequence() => ++Sequence;
|
||||
|
||||
private static string EnsureNotNullOrWhiteSpace(string value, string name)
|
||||
=> string.IsNullOrWhiteSpace(value) ? throw new ArgumentException($"{name} must be provided.", name) : value.Trim();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Heartbeat status for orchestrator reporting.
|
||||
/// </summary>
|
||||
public enum VexWorkerHeartbeatStatus
|
||||
{
|
||||
Starting,
|
||||
Running,
|
||||
Paused,
|
||||
Throttled,
|
||||
Backfill,
|
||||
Failed,
|
||||
Succeeded
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Heartbeat payload for orchestrator.
|
||||
/// </summary>
|
||||
public sealed record VexWorkerHeartbeat(
|
||||
VexWorkerHeartbeatStatus Status,
|
||||
int? Progress,
|
||||
int? QueueDepth,
|
||||
string? LastArtifactHash,
|
||||
string? LastArtifactKind,
|
||||
string? ErrorCode,
|
||||
int? RetryAfterSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// Artifact produced during ingestion.
|
||||
/// </summary>
|
||||
public sealed record VexWorkerArtifact(
|
||||
string Hash,
|
||||
string Kind,
|
||||
string? ProviderId,
|
||||
string? DocumentId,
|
||||
DateTimeOffset CreatedAt,
|
||||
ImmutableDictionary<string, string>? Metadata = null);
|
||||
|
||||
/// <summary>
|
||||
/// Result of a completed worker job.
|
||||
/// </summary>
|
||||
public sealed record VexWorkerJobResult(
|
||||
int DocumentsProcessed,
|
||||
int ClaimsGenerated,
|
||||
string? LastCheckpoint,
|
||||
string? LastArtifactHash,
|
||||
DateTimeOffset CompletedAt,
|
||||
ImmutableDictionary<string, string>? Metadata = null);
|
||||
|
||||
/// <summary>
|
||||
/// Commands issued by the orchestrator to control worker behavior.
|
||||
/// </summary>
|
||||
public enum VexWorkerCommandKind
|
||||
{
|
||||
/// <summary>
|
||||
/// Continue normal processing.
|
||||
/// </summary>
|
||||
Continue,
|
||||
|
||||
/// <summary>
|
||||
/// Pause processing until resumed.
|
||||
/// </summary>
|
||||
Pause,
|
||||
|
||||
/// <summary>
|
||||
/// Resume after a pause.
|
||||
/// </summary>
|
||||
Resume,
|
||||
|
||||
/// <summary>
|
||||
/// Apply throttling constraints.
|
||||
/// </summary>
|
||||
Throttle,
|
||||
|
||||
/// <summary>
|
||||
/// Retry the current operation.
|
||||
/// </summary>
|
||||
Retry,
|
||||
|
||||
/// <summary>
|
||||
/// Abort the current job.
|
||||
/// </summary>
|
||||
Abort
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Command received from the orchestrator.
|
||||
/// </summary>
|
||||
public sealed record VexWorkerCommand(
|
||||
VexWorkerCommandKind Kind,
|
||||
long Sequence,
|
||||
DateTimeOffset IssuedAt,
|
||||
DateTimeOffset? ExpiresAt,
|
||||
VexWorkerThrottleParams? Throttle,
|
||||
string? Reason);
|
||||
|
||||
/// <summary>
|
||||
/// Throttle parameters issued with a throttle command.
|
||||
/// </summary>
|
||||
public sealed record VexWorkerThrottleParams(
|
||||
int? RequestsPerMinute,
|
||||
int? BurstLimit,
|
||||
int? CooldownSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// Classification of errors for orchestrator reporting.
|
||||
/// </summary>
|
||||
public enum VexWorkerErrorCategory
|
||||
{
|
||||
/// <summary>
|
||||
/// Unknown or unclassified error.
|
||||
/// </summary>
|
||||
Unknown,
|
||||
|
||||
/// <summary>
|
||||
/// Transient network or connectivity issues.
|
||||
/// </summary>
|
||||
Network,
|
||||
|
||||
/// <summary>
|
||||
/// Authentication or authorization failure.
|
||||
/// </summary>
|
||||
Authorization,
|
||||
|
||||
/// <summary>
|
||||
/// Rate limiting or throttling by upstream.
|
||||
/// </summary>
|
||||
RateLimited,
|
||||
|
||||
/// <summary>
|
||||
/// Invalid or malformed data from upstream.
|
||||
/// </summary>
|
||||
DataFormat,
|
||||
|
||||
/// <summary>
|
||||
/// Upstream service unavailable.
|
||||
/// </summary>
|
||||
ServiceUnavailable,
|
||||
|
||||
/// <summary>
|
||||
/// Internal processing error.
|
||||
/// </summary>
|
||||
Internal,
|
||||
|
||||
/// <summary>
|
||||
/// Configuration or setup error.
|
||||
/// </summary>
|
||||
Configuration,
|
||||
|
||||
/// <summary>
|
||||
/// Operation cancelled.
|
||||
/// </summary>
|
||||
Cancelled,
|
||||
|
||||
/// <summary>
|
||||
/// Operation timed out.
|
||||
/// </summary>
|
||||
Timeout
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Classified error for orchestrator reporting.
|
||||
/// </summary>
|
||||
public sealed record VexWorkerError
|
||||
{
|
||||
public VexWorkerError(
|
||||
string code,
|
||||
VexWorkerErrorCategory category,
|
||||
string message,
|
||||
bool retryable,
|
||||
int? retryAfterSeconds = null,
|
||||
string? stage = null,
|
||||
ImmutableDictionary<string, string>? details = null)
|
||||
{
|
||||
Code = code ?? throw new ArgumentNullException(nameof(code));
|
||||
Category = category;
|
||||
Message = message ?? string.Empty;
|
||||
Retryable = retryable;
|
||||
RetryAfterSeconds = retryAfterSeconds;
|
||||
Stage = stage;
|
||||
Details = details ?? ImmutableDictionary<string, string>.Empty;
|
||||
}
|
||||
|
||||
public string Code { get; }
|
||||
public VexWorkerErrorCategory Category { get; }
|
||||
public string Message { get; }
|
||||
public bool Retryable { get; }
|
||||
public int? RetryAfterSeconds { get; }
|
||||
public string? Stage { get; }
|
||||
public ImmutableDictionary<string, string> Details { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a transient network error.
|
||||
/// </summary>
|
||||
public static VexWorkerError Network(string message, int? retryAfterSeconds = 30)
|
||||
=> new("NETWORK_ERROR", VexWorkerErrorCategory.Network, message, retryable: true, retryAfterSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// Creates an authorization error.
|
||||
/// </summary>
|
||||
public static VexWorkerError Authorization(string message)
|
||||
=> new("AUTH_ERROR", VexWorkerErrorCategory.Authorization, message, retryable: false);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a rate-limited error.
|
||||
/// </summary>
|
||||
public static VexWorkerError RateLimited(string message, int retryAfterSeconds)
|
||||
=> new("RATE_LIMITED", VexWorkerErrorCategory.RateLimited, message, retryable: true, retryAfterSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a service unavailable error.
|
||||
/// </summary>
|
||||
public static VexWorkerError ServiceUnavailable(string message, int? retryAfterSeconds = 60)
|
||||
=> new("SERVICE_UNAVAILABLE", VexWorkerErrorCategory.ServiceUnavailable, message, retryable: true, retryAfterSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a data format error.
|
||||
/// </summary>
|
||||
public static VexWorkerError DataFormat(string message)
|
||||
=> new("DATA_FORMAT_ERROR", VexWorkerErrorCategory.DataFormat, message, retryable: false);
|
||||
|
||||
/// <summary>
|
||||
/// Creates an internal error.
|
||||
/// </summary>
|
||||
public static VexWorkerError Internal(string message)
|
||||
=> new("INTERNAL_ERROR", VexWorkerErrorCategory.Internal, message, retryable: false);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a timeout error.
|
||||
/// </summary>
|
||||
public static VexWorkerError Timeout(string message, int? retryAfterSeconds = 30)
|
||||
=> new("TIMEOUT", VexWorkerErrorCategory.Timeout, message, retryable: true, retryAfterSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a cancelled error.
|
||||
/// </summary>
|
||||
public static VexWorkerError Cancelled(string message)
|
||||
=> new("CANCELLED", VexWorkerErrorCategory.Cancelled, message, retryable: false);
|
||||
|
||||
/// <summary>
|
||||
/// Classifies an exception into an appropriate error.
|
||||
/// </summary>
|
||||
public static VexWorkerError FromException(Exception ex, string? stage = null)
|
||||
{
|
||||
return ex switch
|
||||
{
|
||||
OperationCanceledException => Cancelled(ex.Message),
|
||||
TimeoutException => Timeout(ex.Message),
|
||||
System.Net.Http.HttpRequestException httpEx when httpEx.StatusCode == System.Net.HttpStatusCode.TooManyRequests
|
||||
=> RateLimited(ex.Message, 60),
|
||||
System.Net.Http.HttpRequestException httpEx when httpEx.StatusCode == System.Net.HttpStatusCode.Unauthorized
|
||||
|| httpEx.StatusCode == System.Net.HttpStatusCode.Forbidden
|
||||
=> Authorization(ex.Message),
|
||||
System.Net.Http.HttpRequestException httpEx when httpEx.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable
|
||||
|| httpEx.StatusCode == System.Net.HttpStatusCode.BadGateway
|
||||
|| httpEx.StatusCode == System.Net.HttpStatusCode.GatewayTimeout
|
||||
=> ServiceUnavailable(ex.Message),
|
||||
System.Net.Http.HttpRequestException => Network(ex.Message),
|
||||
System.Net.Sockets.SocketException => Network(ex.Message),
|
||||
System.IO.IOException => Network(ex.Message),
|
||||
System.Text.Json.JsonException => DataFormat(ex.Message),
|
||||
FormatException => DataFormat(ex.Message),
|
||||
InvalidOperationException => Internal(ex.Message),
|
||||
_ => new VexWorkerError("UNKNOWN_ERROR", VexWorkerErrorCategory.Unknown, ex.Message, retryable: false, stage: stage)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checkpoint state for resumable ingestion.
|
||||
/// </summary>
|
||||
public sealed record VexWorkerCheckpoint(
|
||||
string ConnectorId,
|
||||
string? Cursor,
|
||||
DateTimeOffset? LastProcessedAt,
|
||||
ImmutableArray<string> ProcessedDigests,
|
||||
ImmutableDictionary<string, string> ResumeTokens)
|
||||
{
|
||||
public static VexWorkerCheckpoint Empty(string connectorId) => new(
|
||||
connectorId,
|
||||
Cursor: null,
|
||||
LastProcessedAt: null,
|
||||
ProcessedDigests: ImmutableArray<string>.Empty,
|
||||
ResumeTokens: ImmutableDictionary<string, string>.Empty);
|
||||
}
|
||||
@@ -124,7 +124,16 @@ public sealed class OpenVexExporter : IVexExporter
|
||||
SourceUri: source.DocumentSource.ToString(),
|
||||
Detail: source.Detail,
|
||||
FirstObserved: source.FirstSeen.UtcDateTime.ToString("O", CultureInfo.InvariantCulture),
|
||||
LastObserved: source.LastSeen.UtcDateTime.ToString("O", CultureInfo.InvariantCulture)))
|
||||
LastObserved: source.LastSeen.UtcDateTime.ToString("O", CultureInfo.InvariantCulture),
|
||||
// VEX Lens enrichment fields
|
||||
IssuerHint: source.IssuerHint,
|
||||
SignatureType: source.SignatureType,
|
||||
KeyId: source.KeyId,
|
||||
TransparencyLogRef: source.TransparencyLogRef,
|
||||
TrustWeight: source.TrustWeight,
|
||||
TrustTier: source.TrustTier,
|
||||
StalenessSeconds: source.StalenessSeconds,
|
||||
ProductTreeSnippet: source.ProductTreeSnippet))
|
||||
.ToImmutableArray();
|
||||
|
||||
var statementId = FormattableString.Invariant($"{statement.VulnerabilityId}#{NormalizeProductKey(statement.Product.Key)}");
|
||||
@@ -200,6 +209,9 @@ internal sealed record OpenVexExportProduct(
|
||||
[property: JsonPropertyName("purl"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? Purl,
|
||||
[property: JsonPropertyName("cpe"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? Cpe);
|
||||
|
||||
/// <summary>
|
||||
/// OpenVEX source entry with VEX Lens enrichment fields for consensus computation.
|
||||
/// </summary>
|
||||
internal sealed record OpenVexExportSource(
|
||||
[property: JsonPropertyName("provider")] string Provider,
|
||||
[property: JsonPropertyName("status")] string Status,
|
||||
@@ -208,7 +220,16 @@ internal sealed record OpenVexExportSource(
|
||||
[property: JsonPropertyName("source_uri")] string SourceUri,
|
||||
[property: JsonPropertyName("detail"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? Detail,
|
||||
[property: JsonPropertyName("first_observed")] string FirstObserved,
|
||||
[property: JsonPropertyName("last_observed")] string LastObserved);
|
||||
[property: JsonPropertyName("last_observed")] string LastObserved,
|
||||
// VEX Lens enrichment fields for consensus without callback to Excititor
|
||||
[property: JsonPropertyName("issuer_hint"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? IssuerHint,
|
||||
[property: JsonPropertyName("signature_type"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? SignatureType,
|
||||
[property: JsonPropertyName("key_id"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? KeyId,
|
||||
[property: JsonPropertyName("transparency_log_ref"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? TransparencyLogRef,
|
||||
[property: JsonPropertyName("trust_weight"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] decimal? TrustWeight,
|
||||
[property: JsonPropertyName("trust_tier"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? TrustTier,
|
||||
[property: JsonPropertyName("staleness_seconds"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] long? StalenessSeconds,
|
||||
[property: JsonPropertyName("product_tree_snippet"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? ProductTreeSnippet);
|
||||
|
||||
internal sealed record OpenVexExportMetadata(
|
||||
[property: JsonPropertyName("generated_at")] string GeneratedAt,
|
||||
|
||||
@@ -169,17 +169,60 @@ public static class OpenVexStatementMerger
|
||||
private static ImmutableArray<OpenVexSourceEntry> BuildSources(ImmutableArray<VexClaim> claims)
|
||||
{
|
||||
var builder = ImmutableArray.CreateBuilder<OpenVexSourceEntry>(claims.Length);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
foreach (var claim in claims)
|
||||
{
|
||||
// Extract VEX Lens enrichment from signature metadata
|
||||
var signature = claim.Document.Signature;
|
||||
var trust = signature?.Trust;
|
||||
|
||||
// Compute staleness from trust metadata retrieval time or last seen
|
||||
long? stalenessSeconds = null;
|
||||
if (trust?.RetrievedAtUtc is { } retrievedAt)
|
||||
{
|
||||
stalenessSeconds = (long)Math.Ceiling((now - retrievedAt).TotalSeconds);
|
||||
}
|
||||
else if (signature?.VerifiedAt is { } verifiedAt)
|
||||
{
|
||||
stalenessSeconds = (long)Math.Ceiling((now - verifiedAt).TotalSeconds);
|
||||
}
|
||||
|
||||
// Extract product tree snippet from additional metadata (if present)
|
||||
string? productTreeSnippet = null;
|
||||
if (claim.AdditionalMetadata.TryGetValue("csaf.product_tree", out var productTree))
|
||||
{
|
||||
productTreeSnippet = productTree;
|
||||
}
|
||||
|
||||
// Derive trust tier from issuer or provider type
|
||||
string? trustTier = null;
|
||||
if (trust is not null)
|
||||
{
|
||||
trustTier = trust.TenantOverrideApplied ? "tenant-override" : DeriveIssuerTier(trust.IssuerId);
|
||||
}
|
||||
else if (claim.AdditionalMetadata.TryGetValue("issuer.tier", out var tier))
|
||||
{
|
||||
trustTier = tier;
|
||||
}
|
||||
|
||||
builder.Add(new OpenVexSourceEntry(
|
||||
claim.ProviderId,
|
||||
claim.Status,
|
||||
claim.Justification,
|
||||
claim.Document.Digest,
|
||||
claim.Document.SourceUri,
|
||||
claim.Detail,
|
||||
claim.FirstSeen,
|
||||
claim.LastSeen));
|
||||
providerId: claim.ProviderId,
|
||||
status: claim.Status,
|
||||
justification: claim.Justification,
|
||||
documentDigest: claim.Document.Digest,
|
||||
documentSource: claim.Document.SourceUri,
|
||||
detail: claim.Detail,
|
||||
firstSeen: claim.FirstSeen,
|
||||
lastSeen: claim.LastSeen,
|
||||
issuerHint: signature?.Issuer ?? signature?.Subject,
|
||||
signatureType: signature?.Type,
|
||||
keyId: signature?.KeyId,
|
||||
transparencyLogRef: signature?.TransparencyLogReference,
|
||||
trustWeight: trust?.EffectiveWeight,
|
||||
trustTier: trustTier,
|
||||
stalenessSeconds: stalenessSeconds,
|
||||
productTreeSnippet: productTreeSnippet));
|
||||
}
|
||||
|
||||
return builder
|
||||
@@ -189,6 +232,34 @@ public static class OpenVexStatementMerger
|
||||
.ToImmutableArray();
|
||||
}
|
||||
|
||||
private static string? DeriveIssuerTier(string issuerId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(issuerId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// Common issuer tier patterns
|
||||
var lowerIssuerId = issuerId.ToLowerInvariant();
|
||||
if (lowerIssuerId.Contains("vendor") || lowerIssuerId.Contains("upstream"))
|
||||
{
|
||||
return "vendor";
|
||||
}
|
||||
|
||||
if (lowerIssuerId.Contains("distro") || lowerIssuerId.Contains("rhel") ||
|
||||
lowerIssuerId.Contains("ubuntu") || lowerIssuerId.Contains("debian"))
|
||||
{
|
||||
return "distro-trusted";
|
||||
}
|
||||
|
||||
if (lowerIssuerId.Contains("community") || lowerIssuerId.Contains("oss"))
|
||||
{
|
||||
return "community";
|
||||
}
|
||||
|
||||
return "other";
|
||||
}
|
||||
|
||||
private static VexProduct MergeProduct(ImmutableArray<VexClaim> claims)
|
||||
{
|
||||
var key = claims[0].Product.Key;
|
||||
@@ -266,17 +337,85 @@ public sealed record OpenVexMergedStatement(
|
||||
DateTimeOffset FirstObserved,
|
||||
DateTimeOffset LastObserved);
|
||||
|
||||
public sealed record OpenVexSourceEntry(
|
||||
string ProviderId,
|
||||
VexClaimStatus Status,
|
||||
VexJustification? Justification,
|
||||
string DocumentDigest,
|
||||
Uri DocumentSource,
|
||||
string? Detail,
|
||||
DateTimeOffset FirstSeen,
|
||||
DateTimeOffset LastSeen)
|
||||
/// <summary>
|
||||
/// Represents a merged VEX source entry with enrichment for VEX Lens consumption.
|
||||
/// </summary>
|
||||
public sealed record OpenVexSourceEntry
|
||||
{
|
||||
public string DocumentDigest { get; } = string.IsNullOrWhiteSpace(DocumentDigest)
|
||||
? throw new ArgumentException("Document digest must be provided.", nameof(DocumentDigest))
|
||||
: DocumentDigest.Trim();
|
||||
public OpenVexSourceEntry(
|
||||
string providerId,
|
||||
VexClaimStatus status,
|
||||
VexJustification? justification,
|
||||
string documentDigest,
|
||||
Uri documentSource,
|
||||
string? detail,
|
||||
DateTimeOffset firstSeen,
|
||||
DateTimeOffset lastSeen,
|
||||
string? issuerHint = null,
|
||||
string? signatureType = null,
|
||||
string? keyId = null,
|
||||
string? transparencyLogRef = null,
|
||||
decimal? trustWeight = null,
|
||||
string? trustTier = null,
|
||||
long? stalenessSeconds = null,
|
||||
string? productTreeSnippet = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(documentDigest))
|
||||
{
|
||||
throw new ArgumentException("Document digest must be provided.", nameof(documentDigest));
|
||||
}
|
||||
|
||||
ProviderId = providerId;
|
||||
Status = status;
|
||||
Justification = justification;
|
||||
DocumentDigest = documentDigest.Trim();
|
||||
DocumentSource = documentSource;
|
||||
Detail = detail;
|
||||
FirstSeen = firstSeen;
|
||||
LastSeen = lastSeen;
|
||||
|
||||
// VEX Lens enrichment fields
|
||||
IssuerHint = string.IsNullOrWhiteSpace(issuerHint) ? null : issuerHint.Trim();
|
||||
SignatureType = string.IsNullOrWhiteSpace(signatureType) ? null : signatureType.Trim();
|
||||
KeyId = string.IsNullOrWhiteSpace(keyId) ? null : keyId.Trim();
|
||||
TransparencyLogRef = string.IsNullOrWhiteSpace(transparencyLogRef) ? null : transparencyLogRef.Trim();
|
||||
TrustWeight = trustWeight;
|
||||
TrustTier = string.IsNullOrWhiteSpace(trustTier) ? null : trustTier.Trim();
|
||||
StalenessSeconds = stalenessSeconds;
|
||||
ProductTreeSnippet = string.IsNullOrWhiteSpace(productTreeSnippet) ? null : productTreeSnippet.Trim();
|
||||
}
|
||||
|
||||
public string ProviderId { get; }
|
||||
public VexClaimStatus Status { get; }
|
||||
public VexJustification? Justification { get; }
|
||||
public string DocumentDigest { get; }
|
||||
public Uri DocumentSource { get; }
|
||||
public string? Detail { get; }
|
||||
public DateTimeOffset FirstSeen { get; }
|
||||
public DateTimeOffset LastSeen { get; }
|
||||
|
||||
// VEX Lens enrichment fields for consensus computation
|
||||
/// <summary>Issuer identity/hint (e.g., vendor name, distro-trusted) for trust weighting.</summary>
|
||||
public string? IssuerHint { get; }
|
||||
|
||||
/// <summary>Cryptographic signature type (jws, pgp, cosign, etc.).</summary>
|
||||
public string? SignatureType { get; }
|
||||
|
||||
/// <summary>Key identifier used for signature verification.</summary>
|
||||
public string? KeyId { get; }
|
||||
|
||||
/// <summary>Transparency log reference (e.g., Rekor URL) for attestation verification.</summary>
|
||||
public string? TransparencyLogRef { get; }
|
||||
|
||||
/// <summary>Trust weight (0-1) from issuer directory for consensus calculation.</summary>
|
||||
public decimal? TrustWeight { get; }
|
||||
|
||||
/// <summary>Trust tier label (vendor, distro-trusted, community, etc.).</summary>
|
||||
public string? TrustTier { get; }
|
||||
|
||||
/// <summary>Seconds since the document was last verified/retrieved.</summary>
|
||||
public long? StalenessSeconds { get; }
|
||||
|
||||
/// <summary>Product tree snippet (JSON) from CSAF documents for product matching.</summary>
|
||||
public string? ProductTreeSnippet { get; }
|
||||
}
|
||||
|
||||
@@ -17,17 +17,17 @@ public interface IVexProviderStore
|
||||
ValueTask SaveAsync(VexProvider provider, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
}
|
||||
|
||||
public interface IVexConsensusStore
|
||||
{
|
||||
ValueTask<VexConsensus?> FindAsync(string vulnerabilityId, string productKey, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask<IReadOnlyCollection<VexConsensus>> FindByVulnerabilityAsync(string vulnerabilityId, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask SaveAsync(VexConsensus consensus, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
IAsyncEnumerable<VexConsensus> FindCalculatedBeforeAsync(DateTimeOffset cutoff, int batchSize, CancellationToken cancellationToken, IClientSessionHandle? session = null)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
public interface IVexConsensusStore
|
||||
{
|
||||
ValueTask<VexConsensus?> FindAsync(string vulnerabilityId, string productKey, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask<IReadOnlyCollection<VexConsensus>> FindByVulnerabilityAsync(string vulnerabilityId, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask SaveAsync(VexConsensus consensus, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
IAsyncEnumerable<VexConsensus> FindCalculatedBeforeAsync(DateTimeOffset cutoff, int batchSize, CancellationToken cancellationToken, IClientSessionHandle? session = null)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public interface IVexClaimStore
|
||||
{
|
||||
@@ -44,7 +44,12 @@ public sealed record VexConnectorState(
|
||||
DateTimeOffset? LastSuccessAt,
|
||||
int FailureCount,
|
||||
DateTimeOffset? NextEligibleRun,
|
||||
string? LastFailureReason)
|
||||
string? LastFailureReason,
|
||||
DateTimeOffset? LastHeartbeatAt = null,
|
||||
string? LastHeartbeatStatus = null,
|
||||
string? LastArtifactHash = null,
|
||||
string? LastArtifactKind = null,
|
||||
string? LastCheckpoint = null)
|
||||
{
|
||||
public VexConnectorState(
|
||||
string connectorId,
|
||||
@@ -58,30 +63,35 @@ public sealed record VexConnectorState(
|
||||
LastSuccessAt: null,
|
||||
FailureCount: 0,
|
||||
NextEligibleRun: null,
|
||||
LastFailureReason: null)
|
||||
LastFailureReason: null,
|
||||
LastHeartbeatAt: null,
|
||||
LastHeartbeatStatus: null,
|
||||
LastArtifactHash: null,
|
||||
LastArtifactKind: null,
|
||||
LastCheckpoint: null)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public interface IVexConnectorStateRepository
|
||||
{
|
||||
ValueTask<VexConnectorState?> GetAsync(string connectorId, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask SaveAsync(VexConnectorState state, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask<IReadOnlyCollection<VexConnectorState>> ListAsync(CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
}
|
||||
|
||||
public interface IVexConsensusHoldStore
|
||||
{
|
||||
ValueTask<VexConsensusHold?> FindAsync(string vulnerabilityId, string productKey, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask SaveAsync(VexConsensusHold hold, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask RemoveAsync(string vulnerabilityId, string productKey, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
IAsyncEnumerable<VexConsensusHold> FindEligibleAsync(DateTimeOffset asOf, int batchSize, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
}
|
||||
public interface IVexConnectorStateRepository
|
||||
{
|
||||
ValueTask<VexConnectorState?> GetAsync(string connectorId, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask SaveAsync(VexConnectorState state, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask<IReadOnlyCollection<VexConnectorState>> ListAsync(CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
}
|
||||
|
||||
public interface IVexConsensusHoldStore
|
||||
{
|
||||
ValueTask<VexConsensusHold?> FindAsync(string vulnerabilityId, string productKey, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask SaveAsync(VexConsensusHold hold, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
ValueTask RemoveAsync(string vulnerabilityId, string productKey, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
|
||||
IAsyncEnumerable<VexConsensusHold> FindEligibleAsync(DateTimeOffset asOf, int batchSize, CancellationToken cancellationToken, IClientSessionHandle? session = null);
|
||||
}
|
||||
|
||||
public interface IVexCacheIndex
|
||||
{
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Driver;
|
||||
|
||||
namespace StellaOps.Excititor.Storage.Mongo.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// Adds idempotency indexes to the vex_raw collection to enforce content-addressed storage.
|
||||
/// Ensures that:
|
||||
/// 1. Each document is uniquely identified by its content digest
|
||||
/// 2. Provider+Source combinations are unique per digest
|
||||
/// 3. Supports efficient queries for evidence retrieval
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Rollback: Run db.vex_raw.dropIndex("idx_provider_sourceUri_digest_unique")
|
||||
/// and db.vex_raw.dropIndex("idx_digest_providerId") to reverse this migration.
|
||||
/// </remarks>
|
||||
internal sealed class VexRawIdempotencyIndexMigration : IVexMongoMigration
|
||||
{
|
||||
public string Id => "20251127-vex-raw-idempotency-indexes";
|
||||
|
||||
public async ValueTask ExecuteAsync(IMongoDatabase database, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(database);
|
||||
|
||||
var collection = database.GetCollection<BsonDocument>(VexMongoCollectionNames.Raw);
|
||||
|
||||
// Index 1: Unique constraint on providerId + sourceUri + digest
|
||||
// Ensures the same document from the same provider/source is only stored once
|
||||
var providerSourceDigestIndex = new BsonDocument
|
||||
{
|
||||
{ "providerId", 1 },
|
||||
{ "sourceUri", 1 },
|
||||
{ "digest", 1 }
|
||||
};
|
||||
|
||||
var uniqueIndexModel = new CreateIndexModel<BsonDocument>(
|
||||
providerSourceDigestIndex,
|
||||
new CreateIndexOptions
|
||||
{
|
||||
Unique = true,
|
||||
Name = "idx_provider_sourceUri_digest_unique",
|
||||
Background = true
|
||||
});
|
||||
|
||||
// Index 2: Compound index for efficient evidence queries by digest + provider
|
||||
var digestProviderIndex = new BsonDocument
|
||||
{
|
||||
{ "digest", 1 },
|
||||
{ "providerId", 1 }
|
||||
};
|
||||
|
||||
var queryIndexModel = new CreateIndexModel<BsonDocument>(
|
||||
digestProviderIndex,
|
||||
new CreateIndexOptions
|
||||
{
|
||||
Name = "idx_digest_providerId",
|
||||
Background = true
|
||||
});
|
||||
|
||||
// Index 3: TTL index candidate for future cleanup (optional staleness tracking)
|
||||
var retrievedAtIndex = new BsonDocument
|
||||
{
|
||||
{ "retrievedAt", 1 }
|
||||
};
|
||||
|
||||
var retrievedAtIndexModel = new CreateIndexModel<BsonDocument>(
|
||||
retrievedAtIndex,
|
||||
new CreateIndexOptions
|
||||
{
|
||||
Name = "idx_retrievedAt",
|
||||
Background = true
|
||||
});
|
||||
|
||||
// Create all indexes
|
||||
await collection.Indexes.CreateManyAsync(
|
||||
new[] { uniqueIndexModel, queryIndexModel, retrievedAtIndexModel },
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for idempotency index management.
|
||||
/// </summary>
|
||||
public static class VexRawIdempotencyIndexExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Drops the idempotency indexes (for rollback).
|
||||
/// </summary>
|
||||
public static async Task RollbackIdempotencyIndexesAsync(
|
||||
this IMongoDatabase database,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(database);
|
||||
|
||||
var collection = database.GetCollection<BsonDocument>(VexMongoCollectionNames.Raw);
|
||||
|
||||
var indexNames = new[]
|
||||
{
|
||||
"idx_provider_sourceUri_digest_unique",
|
||||
"idx_digest_providerId",
|
||||
"idx_retrievedAt"
|
||||
};
|
||||
|
||||
foreach (var indexName in indexNames)
|
||||
{
|
||||
try
|
||||
{
|
||||
await collection.Indexes.DropOneAsync(indexName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (MongoCommandException ex) when (ex.CodeName == "IndexNotFound")
|
||||
{
|
||||
// Index doesn't exist, skip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that idempotency indexes exist.
|
||||
/// </summary>
|
||||
public static async Task<bool> VerifyIdempotencyIndexesExistAsync(
|
||||
this IMongoDatabase database,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(database);
|
||||
|
||||
var collection = database.GetCollection<BsonDocument>(VexMongoCollectionNames.Raw);
|
||||
var cursor = await collection.Indexes.ListAsync(cancellationToken).ConfigureAwait(false);
|
||||
var indexes = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var indexNames = indexes.Select(i => i.GetValue("name", "").AsString).ToHashSet();
|
||||
|
||||
return indexNames.Contains("idx_provider_sourceUri_digest_unique") &&
|
||||
indexNames.Contains("idx_digest_providerId");
|
||||
}
|
||||
}
|
||||
@@ -25,15 +25,17 @@ internal sealed class VexRawSchemaMigration : IVexMongoMigration
|
||||
|
||||
if (!exists)
|
||||
{
|
||||
await database.CreateCollectionAsync(
|
||||
VexMongoCollectionNames.Raw,
|
||||
new CreateCollectionOptions
|
||||
{
|
||||
Validator = validator,
|
||||
ValidationAction = DocumentValidationAction.Warn,
|
||||
ValidationLevel = DocumentValidationLevel.Moderate,
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
// In MongoDB.Driver 3.x, CreateCollectionOptions doesn't support Validator directly.
|
||||
// Use the create command instead.
|
||||
var createCommand = new BsonDocument
|
||||
{
|
||||
{ "create", VexMongoCollectionNames.Raw },
|
||||
{ "validator", validator },
|
||||
{ "validationAction", "warn" },
|
||||
{ "validationLevel", "moderate" }
|
||||
};
|
||||
await database.RunCommandAsync<BsonDocument>(createCommand, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MongoDB.Driver;
|
||||
|
||||
namespace StellaOps.Excititor.Storage.Mongo.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// Migration that creates indexes for the vex.timeline_events collection.
|
||||
/// </summary>
|
||||
internal sealed class VexTimelineEventIndexMigration : IVexMongoMigration
|
||||
{
|
||||
public string Id => "20251127-timeline-events";
|
||||
|
||||
public async ValueTask ExecuteAsync(IMongoDatabase database, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(database);
|
||||
|
||||
var collection = database.GetCollection<VexTimelineEventRecord>(VexMongoCollectionNames.TimelineEvents);
|
||||
|
||||
// Unique index on tenant + event ID
|
||||
var tenantEventIdIndex = Builders<VexTimelineEventRecord>.IndexKeys
|
||||
.Ascending(x => x.Tenant)
|
||||
.Ascending(x => x.Id);
|
||||
|
||||
// Index for querying by time range (descending for recent-first queries)
|
||||
var tenantTimeIndex = Builders<VexTimelineEventRecord>.IndexKeys
|
||||
.Ascending(x => x.Tenant)
|
||||
.Descending(x => x.CreatedAt);
|
||||
|
||||
// Index for querying by trace ID
|
||||
var tenantTraceIndex = Builders<VexTimelineEventRecord>.IndexKeys
|
||||
.Ascending(x => x.Tenant)
|
||||
.Ascending(x => x.TraceId)
|
||||
.Ascending(x => x.CreatedAt);
|
||||
|
||||
// Index for querying by provider
|
||||
var tenantProviderIndex = Builders<VexTimelineEventRecord>.IndexKeys
|
||||
.Ascending(x => x.Tenant)
|
||||
.Ascending(x => x.ProviderId)
|
||||
.Descending(x => x.CreatedAt);
|
||||
|
||||
// Index for querying by event type
|
||||
var tenantEventTypeIndex = Builders<VexTimelineEventRecord>.IndexKeys
|
||||
.Ascending(x => x.Tenant)
|
||||
.Ascending(x => x.EventType)
|
||||
.Descending(x => x.CreatedAt);
|
||||
|
||||
// TTL index for automatic cleanup (30 days by default)
|
||||
// Uncomment if timeline events should expire:
|
||||
// var ttlIndex = Builders<VexTimelineEventRecord>.IndexKeys.Ascending(x => x.CreatedAt);
|
||||
// var ttlOptions = new CreateIndexOptions { ExpireAfter = TimeSpan.FromDays(30) };
|
||||
|
||||
await Task.WhenAll(
|
||||
collection.Indexes.CreateOneAsync(
|
||||
new CreateIndexModel<VexTimelineEventRecord>(tenantEventIdIndex, new CreateIndexOptions { Unique = true }),
|
||||
cancellationToken: cancellationToken),
|
||||
collection.Indexes.CreateOneAsync(
|
||||
new CreateIndexModel<VexTimelineEventRecord>(tenantTimeIndex),
|
||||
cancellationToken: cancellationToken),
|
||||
collection.Indexes.CreateOneAsync(
|
||||
new CreateIndexModel<VexTimelineEventRecord>(tenantTraceIndex),
|
||||
cancellationToken: cancellationToken),
|
||||
collection.Indexes.CreateOneAsync(
|
||||
new CreateIndexModel<VexTimelineEventRecord>(tenantProviderIndex),
|
||||
cancellationToken: cancellationToken),
|
||||
collection.Indexes.CreateOneAsync(
|
||||
new CreateIndexModel<VexTimelineEventRecord>(tenantEventTypeIndex),
|
||||
cancellationToken: cancellationToken)
|
||||
).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
|
||||
namespace StellaOps.Excititor.Storage.Mongo;
|
||||
|
||||
/// <summary>
|
||||
/// MongoDB implementation of <see cref="IVexLinksetEventPublisher"/>.
|
||||
/// Events are persisted to the vex.linkset_events collection for replay and audit.
|
||||
/// </summary>
|
||||
internal sealed class MongoVexLinksetEventPublisher : IVexLinksetEventPublisher
|
||||
{
|
||||
private readonly IMongoCollection<VexLinksetEventRecord> _collection;
|
||||
|
||||
public MongoVexLinksetEventPublisher(IMongoDatabase database)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(database);
|
||||
_collection = database.GetCollection<VexLinksetEventRecord>(VexMongoCollectionNames.LinksetEvents);
|
||||
}
|
||||
|
||||
public async Task PublishAsync(VexLinksetUpdatedEvent @event, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(@event);
|
||||
|
||||
var record = ToRecord(@event);
|
||||
await _collection.InsertOneAsync(record, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task PublishManyAsync(IEnumerable<VexLinksetUpdatedEvent> events, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(events);
|
||||
|
||||
var records = events
|
||||
.Where(e => e is not null)
|
||||
.Select(ToRecord)
|
||||
.ToList();
|
||||
|
||||
if (records.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var options = new InsertManyOptions { IsOrdered = false };
|
||||
await _collection.InsertManyAsync(records, options, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static VexLinksetEventRecord ToRecord(VexLinksetUpdatedEvent @event)
|
||||
{
|
||||
var eventId = $"{@event.LinksetId}:{@event.CreatedAtUtc.UtcTicks}";
|
||||
|
||||
return new VexLinksetEventRecord
|
||||
{
|
||||
Id = eventId,
|
||||
EventType = @event.EventType,
|
||||
Tenant = @event.Tenant.ToLowerInvariant(),
|
||||
LinksetId = @event.LinksetId,
|
||||
VulnerabilityId = @event.VulnerabilityId,
|
||||
ProductKey = @event.ProductKey,
|
||||
Observations = @event.Observations
|
||||
.Select(o => new VexLinksetEventObservationRecord
|
||||
{
|
||||
ObservationId = o.ObservationId,
|
||||
ProviderId = o.ProviderId,
|
||||
Status = o.Status,
|
||||
Confidence = o.Confidence
|
||||
})
|
||||
.ToList(),
|
||||
Disagreements = @event.Disagreements
|
||||
.Select(d => new VexLinksetDisagreementRecord
|
||||
{
|
||||
ProviderId = d.ProviderId,
|
||||
Status = d.Status,
|
||||
Justification = d.Justification,
|
||||
Confidence = d.Confidence
|
||||
})
|
||||
.ToList(),
|
||||
CreatedAtUtc = @event.CreatedAtUtc.UtcDateTime,
|
||||
PublishedAtUtc = DateTime.UtcNow,
|
||||
ConflictCount = @event.Disagreements.Length,
|
||||
ObservationCount = @event.Observations.Length
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
using System.Collections.Immutable;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
|
||||
namespace StellaOps.Excititor.Storage.Mongo;
|
||||
|
||||
internal sealed class MongoVexLinksetStore : IVexLinksetStore
|
||||
{
|
||||
private readonly IMongoCollection<VexLinksetRecord> _collection;
|
||||
|
||||
public MongoVexLinksetStore(IMongoDatabase database)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(database);
|
||||
_collection = database.GetCollection<VexLinksetRecord>(VexMongoCollectionNames.Linksets);
|
||||
}
|
||||
|
||||
public async ValueTask<bool> InsertAsync(
|
||||
VexLinkset linkset,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(linkset);
|
||||
|
||||
var record = ToRecord(linkset);
|
||||
|
||||
try
|
||||
{
|
||||
await _collection.InsertOneAsync(record, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<bool> UpsertAsync(
|
||||
VexLinkset linkset,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(linkset);
|
||||
|
||||
var record = ToRecord(linkset);
|
||||
var normalizedTenant = NormalizeTenant(linkset.Tenant);
|
||||
|
||||
var filter = Builders<VexLinksetRecord>.Filter.And(
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.LinksetId, linkset.LinksetId));
|
||||
|
||||
var options = new ReplaceOptions { IsUpsert = true };
|
||||
var result = await _collection
|
||||
.ReplaceOneAsync(filter, record, options, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return result.UpsertedId is not null;
|
||||
}
|
||||
|
||||
public async ValueTask<VexLinkset?> GetByIdAsync(
|
||||
string tenant,
|
||||
string linksetId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedId = linksetId?.Trim() ?? throw new ArgumentNullException(nameof(linksetId));
|
||||
|
||||
var filter = Builders<VexLinksetRecord>.Filter.And(
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.LinksetId, normalizedId));
|
||||
|
||||
var record = await _collection
|
||||
.Find(filter)
|
||||
.FirstOrDefaultAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return record is null ? null : ToModel(record);
|
||||
}
|
||||
|
||||
public async ValueTask<VexLinkset> GetOrCreateAsync(
|
||||
string tenant,
|
||||
string vulnerabilityId,
|
||||
string productKey,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedVuln = vulnerabilityId?.Trim() ?? throw new ArgumentNullException(nameof(vulnerabilityId));
|
||||
var normalizedProduct = productKey?.Trim() ?? throw new ArgumentNullException(nameof(productKey));
|
||||
|
||||
var linksetId = VexLinkset.CreateLinksetId(normalizedTenant, normalizedVuln, normalizedProduct);
|
||||
|
||||
var existing = await GetByIdAsync(normalizedTenant, linksetId, cancellationToken).ConfigureAwait(false);
|
||||
if (existing is not null)
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
|
||||
var newLinkset = new VexLinkset(
|
||||
linksetId,
|
||||
normalizedTenant,
|
||||
normalizedVuln,
|
||||
normalizedProduct,
|
||||
observations: Array.Empty<VexLinksetObservationRefModel>(),
|
||||
disagreements: null,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
updatedAt: DateTimeOffset.UtcNow);
|
||||
|
||||
try
|
||||
{
|
||||
await InsertAsync(newLinkset, cancellationToken).ConfigureAwait(false);
|
||||
return newLinkset;
|
||||
}
|
||||
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
|
||||
{
|
||||
// Race condition - another process created it. Fetch and return.
|
||||
var created = await GetByIdAsync(normalizedTenant, linksetId, cancellationToken).ConfigureAwait(false);
|
||||
return created ?? newLinkset;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<VexLinkset>> FindByVulnerabilityAsync(
|
||||
string tenant,
|
||||
string vulnerabilityId,
|
||||
int limit,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedVuln = vulnerabilityId?.Trim().ToLowerInvariant()
|
||||
?? throw new ArgumentNullException(nameof(vulnerabilityId));
|
||||
|
||||
var filter = Builders<VexLinksetRecord>.Filter.And(
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.VulnerabilityId, normalizedVuln));
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexLinksetRecord>.Sort.Descending(r => r.UpdatedAt))
|
||||
.Limit(Math.Max(1, limit))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<VexLinkset>> FindByProductKeyAsync(
|
||||
string tenant,
|
||||
string productKey,
|
||||
int limit,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedProduct = productKey?.Trim().ToLowerInvariant()
|
||||
?? throw new ArgumentNullException(nameof(productKey));
|
||||
|
||||
var filter = Builders<VexLinksetRecord>.Filter.And(
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.ProductKey, normalizedProduct));
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexLinksetRecord>.Sort.Descending(r => r.UpdatedAt))
|
||||
.Limit(Math.Max(1, limit))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<VexLinkset>> FindWithConflictsAsync(
|
||||
string tenant,
|
||||
int limit,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
|
||||
var filter = Builders<VexLinksetRecord>.Filter.And(
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexLinksetRecord>.Filter.SizeGt(r => r.Disagreements, 0));
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexLinksetRecord>.Sort.Descending(r => r.UpdatedAt))
|
||||
.Limit(Math.Max(1, limit))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<VexLinkset>> FindByProviderAsync(
|
||||
string tenant,
|
||||
string providerId,
|
||||
int limit,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedProvider = providerId?.Trim().ToLowerInvariant()
|
||||
?? throw new ArgumentNullException(nameof(providerId));
|
||||
|
||||
var filter = Builders<VexLinksetRecord>.Filter.And(
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexLinksetRecord>.Filter.AnyEq(r => r.ProviderIds, normalizedProvider));
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexLinksetRecord>.Sort.Descending(r => r.UpdatedAt))
|
||||
.Limit(Math.Max(1, limit))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<bool> DeleteAsync(
|
||||
string tenant,
|
||||
string linksetId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedId = linksetId?.Trim() ?? throw new ArgumentNullException(nameof(linksetId));
|
||||
|
||||
var filter = Builders<VexLinksetRecord>.Filter.And(
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.LinksetId, normalizedId));
|
||||
|
||||
var result = await _collection
|
||||
.DeleteOneAsync(filter, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return result.DeletedCount > 0;
|
||||
}
|
||||
|
||||
public async ValueTask<long> CountAsync(
|
||||
string tenant,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
|
||||
var filter = Builders<VexLinksetRecord>.Filter.Eq(r => r.Tenant, normalizedTenant);
|
||||
|
||||
return await _collection
|
||||
.CountDocumentsAsync(filter, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask<long> CountWithConflictsAsync(
|
||||
string tenant,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
|
||||
var filter = Builders<VexLinksetRecord>.Filter.And(
|
||||
Builders<VexLinksetRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexLinksetRecord>.Filter.SizeGt(r => r.Disagreements, 0));
|
||||
|
||||
return await _collection
|
||||
.CountDocumentsAsync(filter, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static string NormalizeTenant(string tenant)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tenant))
|
||||
{
|
||||
throw new ArgumentException("tenant is required", nameof(tenant));
|
||||
}
|
||||
|
||||
return tenant.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static VexLinksetRecord ToRecord(VexLinkset linkset)
|
||||
{
|
||||
return new VexLinksetRecord
|
||||
{
|
||||
Id = linkset.LinksetId,
|
||||
Tenant = linkset.Tenant.ToLowerInvariant(),
|
||||
LinksetId = linkset.LinksetId,
|
||||
VulnerabilityId = linkset.VulnerabilityId.ToLowerInvariant(),
|
||||
ProductKey = linkset.ProductKey.ToLowerInvariant(),
|
||||
ProviderIds = linkset.ProviderIds.ToList(),
|
||||
Statuses = linkset.Statuses.ToList(),
|
||||
CreatedAt = linkset.CreatedAt.UtcDateTime,
|
||||
UpdatedAt = linkset.UpdatedAt.UtcDateTime,
|
||||
Observations = linkset.Observations.Select(ToObservationRecord).ToList(),
|
||||
Disagreements = linkset.Disagreements.Select(ToDisagreementRecord).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
private static VexObservationLinksetObservationRecord ToObservationRecord(VexLinksetObservationRefModel obs)
|
||||
{
|
||||
return new VexObservationLinksetObservationRecord
|
||||
{
|
||||
ObservationId = obs.ObservationId,
|
||||
ProviderId = obs.ProviderId,
|
||||
Status = obs.Status,
|
||||
Confidence = obs.Confidence
|
||||
};
|
||||
}
|
||||
|
||||
private static VexLinksetDisagreementRecord ToDisagreementRecord(VexObservationDisagreement disagreement)
|
||||
{
|
||||
return new VexLinksetDisagreementRecord
|
||||
{
|
||||
ProviderId = disagreement.ProviderId,
|
||||
Status = disagreement.Status,
|
||||
Justification = disagreement.Justification,
|
||||
Confidence = disagreement.Confidence
|
||||
};
|
||||
}
|
||||
|
||||
private static VexLinkset ToModel(VexLinksetRecord record)
|
||||
{
|
||||
var observations = record.Observations?
|
||||
.Where(o => o is not null)
|
||||
.Select(o => new VexLinksetObservationRefModel(
|
||||
o.ObservationId,
|
||||
o.ProviderId,
|
||||
o.Status,
|
||||
o.Confidence))
|
||||
.ToImmutableArray() ?? ImmutableArray<VexLinksetObservationRefModel>.Empty;
|
||||
|
||||
var disagreements = record.Disagreements?
|
||||
.Where(d => d is not null)
|
||||
.Select(d => new VexObservationDisagreement(
|
||||
d.ProviderId,
|
||||
d.Status,
|
||||
d.Justification,
|
||||
d.Confidence))
|
||||
.ToImmutableArray() ?? ImmutableArray<VexObservationDisagreement>.Empty;
|
||||
|
||||
return new VexLinkset(
|
||||
linksetId: record.LinksetId,
|
||||
tenant: record.Tenant,
|
||||
vulnerabilityId: record.VulnerabilityId,
|
||||
productKey: record.ProductKey,
|
||||
observations: observations,
|
||||
disagreements: disagreements,
|
||||
createdAt: new DateTimeOffset(record.CreatedAt, TimeSpan.Zero),
|
||||
updatedAt: new DateTimeOffset(record.UpdatedAt, TimeSpan.Zero));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Text.Json.Nodes;
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
|
||||
namespace StellaOps.Excititor.Storage.Mongo;
|
||||
|
||||
internal sealed class MongoVexObservationStore : IVexObservationStore
|
||||
{
|
||||
private readonly IMongoCollection<VexObservationRecord> _collection;
|
||||
|
||||
public MongoVexObservationStore(IMongoDatabase database)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(database);
|
||||
_collection = database.GetCollection<VexObservationRecord>(VexMongoCollectionNames.Observations);
|
||||
}
|
||||
|
||||
public async ValueTask<bool> InsertAsync(
|
||||
VexObservation observation,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(observation);
|
||||
|
||||
var record = ToRecord(observation);
|
||||
|
||||
try
|
||||
{
|
||||
await _collection.InsertOneAsync(record, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<bool> UpsertAsync(
|
||||
VexObservation observation,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(observation);
|
||||
|
||||
var record = ToRecord(observation);
|
||||
var normalizedTenant = NormalizeTenant(observation.Tenant);
|
||||
|
||||
var filter = Builders<VexObservationRecord>.Filter.And(
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.ObservationId, observation.ObservationId));
|
||||
|
||||
var options = new ReplaceOptions { IsUpsert = true };
|
||||
var result = await _collection
|
||||
.ReplaceOneAsync(filter, record, options, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return result.UpsertedId is not null;
|
||||
}
|
||||
|
||||
public async ValueTask<int> InsertManyAsync(
|
||||
string tenant,
|
||||
IEnumerable<VexObservation> observations,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var records = observations
|
||||
.Where(o => o is not null && string.Equals(NormalizeTenant(o.Tenant), normalizedTenant, StringComparison.Ordinal))
|
||||
.Select(ToRecord)
|
||||
.ToList();
|
||||
|
||||
if (records.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var options = new InsertManyOptions { IsOrdered = false };
|
||||
try
|
||||
{
|
||||
await _collection.InsertManyAsync(records, options, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return records.Count;
|
||||
}
|
||||
catch (MongoBulkWriteException<VexObservationRecord> ex)
|
||||
{
|
||||
// Return the count of successful inserts
|
||||
var duplicates = ex.WriteErrors?.Count(e => e.Category == ServerErrorCategory.DuplicateKey) ?? 0;
|
||||
return records.Count - duplicates;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<VexObservation?> GetByIdAsync(
|
||||
string tenant,
|
||||
string observationId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedId = observationId?.Trim() ?? throw new ArgumentNullException(nameof(observationId));
|
||||
|
||||
var filter = Builders<VexObservationRecord>.Filter.And(
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.ObservationId, normalizedId));
|
||||
|
||||
var record = await _collection
|
||||
.Find(filter)
|
||||
.FirstOrDefaultAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return record is null ? null : ToModel(record);
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<VexObservation>> FindByVulnerabilityAndProductAsync(
|
||||
string tenant,
|
||||
string vulnerabilityId,
|
||||
string productKey,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedVuln = vulnerabilityId?.Trim().ToLowerInvariant()
|
||||
?? throw new ArgumentNullException(nameof(vulnerabilityId));
|
||||
var normalizedProduct = productKey?.Trim().ToLowerInvariant()
|
||||
?? throw new ArgumentNullException(nameof(productKey));
|
||||
|
||||
var filter = Builders<VexObservationRecord>.Filter.And(
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.VulnerabilityId, normalizedVuln),
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.ProductKey, normalizedProduct));
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexObservationRecord>.Sort.Descending(r => r.CreatedAt))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<VexObservation>> FindByProviderAsync(
|
||||
string tenant,
|
||||
string providerId,
|
||||
int limit,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedProvider = providerId?.Trim().ToLowerInvariant()
|
||||
?? throw new ArgumentNullException(nameof(providerId));
|
||||
|
||||
var filter = Builders<VexObservationRecord>.Filter.And(
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.ProviderId, normalizedProvider));
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexObservationRecord>.Sort.Descending(r => r.CreatedAt))
|
||||
.Limit(Math.Max(1, limit))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<bool> DeleteAsync(
|
||||
string tenant,
|
||||
string observationId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedId = observationId?.Trim() ?? throw new ArgumentNullException(nameof(observationId));
|
||||
|
||||
var filter = Builders<VexObservationRecord>.Filter.And(
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexObservationRecord>.Filter.Eq(r => r.ObservationId, normalizedId));
|
||||
|
||||
var result = await _collection
|
||||
.DeleteOneAsync(filter, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return result.DeletedCount > 0;
|
||||
}
|
||||
|
||||
public async ValueTask<long> CountAsync(
|
||||
string tenant,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
|
||||
var filter = Builders<VexObservationRecord>.Filter.Eq(r => r.Tenant, normalizedTenant);
|
||||
|
||||
return await _collection
|
||||
.CountDocumentsAsync(filter, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static string NormalizeTenant(string tenant)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tenant))
|
||||
{
|
||||
throw new ArgumentException("tenant is required", nameof(tenant));
|
||||
}
|
||||
|
||||
return tenant.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static VexObservationRecord ToRecord(VexObservation observation)
|
||||
{
|
||||
var firstStatement = observation.Statements.FirstOrDefault();
|
||||
|
||||
return new VexObservationRecord
|
||||
{
|
||||
Id = observation.ObservationId,
|
||||
Tenant = observation.Tenant,
|
||||
ObservationId = observation.ObservationId,
|
||||
VulnerabilityId = firstStatement?.VulnerabilityId?.ToLowerInvariant() ?? string.Empty,
|
||||
ProductKey = firstStatement?.ProductKey?.ToLowerInvariant() ?? string.Empty,
|
||||
ProviderId = observation.ProviderId,
|
||||
StreamId = observation.StreamId,
|
||||
Status = firstStatement?.Status.ToString().ToLowerInvariant() ?? "unknown",
|
||||
Document = new VexObservationDocumentRecord
|
||||
{
|
||||
Digest = observation.Upstream.ContentHash,
|
||||
SourceUri = null,
|
||||
Format = observation.Content.Format,
|
||||
Revision = observation.Upstream.DocumentVersion,
|
||||
Signature = new VexObservationSignatureRecord
|
||||
{
|
||||
Present = observation.Upstream.Signature.Present,
|
||||
Subject = observation.Upstream.Signature.Format,
|
||||
Issuer = observation.Upstream.Signature.KeyId,
|
||||
VerifiedAt = null
|
||||
}
|
||||
},
|
||||
Upstream = new VexObservationUpstreamRecord
|
||||
{
|
||||
UpstreamId = observation.Upstream.UpstreamId,
|
||||
DocumentVersion = observation.Upstream.DocumentVersion,
|
||||
FetchedAt = observation.Upstream.FetchedAt,
|
||||
ReceivedAt = observation.Upstream.ReceivedAt,
|
||||
ContentHash = observation.Upstream.ContentHash,
|
||||
Signature = new VexObservationSignatureRecord
|
||||
{
|
||||
Present = observation.Upstream.Signature.Present,
|
||||
Subject = observation.Upstream.Signature.Format,
|
||||
Issuer = observation.Upstream.Signature.KeyId,
|
||||
VerifiedAt = null
|
||||
}
|
||||
},
|
||||
Content = new VexObservationContentRecord
|
||||
{
|
||||
Format = observation.Content.Format,
|
||||
SpecVersion = observation.Content.SpecVersion,
|
||||
Raw = BsonDocument.Parse(observation.Content.Raw.ToJsonString())
|
||||
},
|
||||
Statements = observation.Statements.Select(ToStatementRecord).ToList(),
|
||||
Linkset = ToLinksetRecord(observation.Linkset),
|
||||
CreatedAt = observation.CreatedAt.UtcDateTime
|
||||
};
|
||||
}
|
||||
|
||||
private static VexObservationStatementRecord ToStatementRecord(VexObservationStatement statement)
|
||||
{
|
||||
return new VexObservationStatementRecord
|
||||
{
|
||||
VulnerabilityId = statement.VulnerabilityId,
|
||||
ProductKey = statement.ProductKey,
|
||||
Status = statement.Status.ToString().ToLowerInvariant(),
|
||||
LastObserved = statement.LastObserved,
|
||||
Locator = statement.Locator,
|
||||
Justification = statement.Justification?.ToString().ToLowerInvariant(),
|
||||
IntroducedVersion = statement.IntroducedVersion,
|
||||
FixedVersion = statement.FixedVersion,
|
||||
Detail = null,
|
||||
ScopeScore = null,
|
||||
Epss = null,
|
||||
Kev = null
|
||||
};
|
||||
}
|
||||
|
||||
private static VexObservationLinksetRecord ToLinksetRecord(VexObservationLinkset linkset)
|
||||
{
|
||||
return new VexObservationLinksetRecord
|
||||
{
|
||||
Aliases = linkset.Aliases.ToList(),
|
||||
Purls = linkset.Purls.ToList(),
|
||||
Cpes = linkset.Cpes.ToList(),
|
||||
References = linkset.References.Select(r => new VexObservationReferenceRecord
|
||||
{
|
||||
Type = r.Type,
|
||||
Url = r.Url
|
||||
}).ToList(),
|
||||
ReconciledFrom = linkset.ReconciledFrom.ToList(),
|
||||
Disagreements = linkset.Disagreements.Select(d => new VexLinksetDisagreementRecord
|
||||
{
|
||||
ProviderId = d.ProviderId,
|
||||
Status = d.Status,
|
||||
Justification = d.Justification,
|
||||
Confidence = d.Confidence
|
||||
}).ToList(),
|
||||
Observations = linkset.Observations.Select(o => new VexObservationLinksetObservationRecord
|
||||
{
|
||||
ObservationId = o.ObservationId,
|
||||
ProviderId = o.ProviderId,
|
||||
Status = o.Status,
|
||||
Confidence = o.Confidence
|
||||
}).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
private static VexObservation ToModel(VexObservationRecord record)
|
||||
{
|
||||
var statements = record.Statements.Select(MapStatement).ToImmutableArray();
|
||||
var linkset = MapLinkset(record.Linkset);
|
||||
|
||||
var upstreamSignature = record.Upstream?.Signature is null
|
||||
? new VexObservationSignature(false, null, null, null)
|
||||
: new VexObservationSignature(
|
||||
record.Upstream.Signature.Present,
|
||||
record.Upstream.Signature.Subject,
|
||||
record.Upstream.Signature.Issuer,
|
||||
signature: null);
|
||||
|
||||
var upstream = record.Upstream is null
|
||||
? new VexObservationUpstream(
|
||||
upstreamId: record.ObservationId,
|
||||
documentVersion: null,
|
||||
fetchedAt: record.CreatedAt,
|
||||
receivedAt: record.CreatedAt,
|
||||
contentHash: record.Document.Digest,
|
||||
signature: upstreamSignature)
|
||||
: new VexObservationUpstream(
|
||||
record.Upstream.UpstreamId,
|
||||
record.Upstream.DocumentVersion,
|
||||
record.Upstream.FetchedAt,
|
||||
record.Upstream.ReceivedAt,
|
||||
record.Upstream.ContentHash,
|
||||
upstreamSignature);
|
||||
|
||||
var content = record.Content is null
|
||||
? new VexObservationContent("unknown", null, new JsonObject())
|
||||
: new VexObservationContent(
|
||||
record.Content.Format ?? "unknown",
|
||||
record.Content.SpecVersion,
|
||||
JsonNode.Parse(record.Content.Raw.ToJson()) ?? new JsonObject(),
|
||||
metadata: ImmutableDictionary<string, string>.Empty);
|
||||
|
||||
return new VexObservation(
|
||||
observationId: record.ObservationId,
|
||||
tenant: record.Tenant,
|
||||
providerId: record.ProviderId,
|
||||
streamId: string.IsNullOrWhiteSpace(record.StreamId) ? record.ProviderId : record.StreamId,
|
||||
upstream: upstream,
|
||||
statements: statements,
|
||||
content: content,
|
||||
linkset: linkset,
|
||||
createdAt: new DateTimeOffset(record.CreatedAt, TimeSpan.Zero),
|
||||
supersedes: ImmutableArray<string>.Empty,
|
||||
attributes: ImmutableDictionary<string, string>.Empty);
|
||||
}
|
||||
|
||||
private static VexObservationStatement MapStatement(VexObservationStatementRecord record)
|
||||
{
|
||||
var justification = string.IsNullOrWhiteSpace(record.Justification)
|
||||
? (VexJustification?)null
|
||||
: Enum.Parse<VexJustification>(record.Justification, ignoreCase: true);
|
||||
|
||||
return new VexObservationStatement(
|
||||
record.VulnerabilityId,
|
||||
record.ProductKey,
|
||||
Enum.Parse<VexClaimStatus>(record.Status, ignoreCase: true),
|
||||
record.LastObserved,
|
||||
locator: record.Locator,
|
||||
justification: justification,
|
||||
introducedVersion: record.IntroducedVersion,
|
||||
fixedVersion: record.FixedVersion,
|
||||
purl: null,
|
||||
cpe: null,
|
||||
evidence: null,
|
||||
metadata: ImmutableDictionary<string, string>.Empty);
|
||||
}
|
||||
|
||||
private static VexObservationLinkset MapLinkset(VexObservationLinksetRecord record)
|
||||
{
|
||||
var aliases = record?.Aliases?.Where(NotNullOrWhiteSpace).Select(a => a.Trim()).ToImmutableArray() ?? ImmutableArray<string>.Empty;
|
||||
var purls = record?.Purls?.Where(NotNullOrWhiteSpace).Select(p => p.Trim()).ToImmutableArray() ?? ImmutableArray<string>.Empty;
|
||||
var cpes = record?.Cpes?.Where(NotNullOrWhiteSpace).Select(c => c.Trim()).ToImmutableArray() ?? ImmutableArray<string>.Empty;
|
||||
var references = record?.References?.Select(r => new VexObservationReference(r.Type, r.Url)).ToImmutableArray() ?? ImmutableArray<VexObservationReference>.Empty;
|
||||
var reconciledFrom = record?.ReconciledFrom?.Where(NotNullOrWhiteSpace).Select(r => r.Trim()).ToImmutableArray() ?? ImmutableArray<string>.Empty;
|
||||
var disagreements = record?.Disagreements?.Select(d => new VexObservationDisagreement(d.ProviderId, d.Status, d.Justification, d.Confidence)).ToImmutableArray() ?? ImmutableArray<VexObservationDisagreement>.Empty;
|
||||
var observationRefs = record?.Observations?.Select(o => new VexLinksetObservationRefModel(
|
||||
o.ObservationId,
|
||||
o.ProviderId,
|
||||
o.Status,
|
||||
o.Confidence)).ToImmutableArray() ?? ImmutableArray<VexLinksetObservationRefModel>.Empty;
|
||||
|
||||
return new VexObservationLinkset(aliases, purls, cpes, references, reconciledFrom, disagreements, observationRefs);
|
||||
}
|
||||
|
||||
private static bool NotNullOrWhiteSpace(string? value) => !string.IsNullOrWhiteSpace(value);
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
using System.Collections.Immutable;
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
|
||||
namespace StellaOps.Excititor.Storage.Mongo;
|
||||
|
||||
/// <summary>
|
||||
/// MongoDB record for timeline events.
|
||||
/// </summary>
|
||||
[BsonIgnoreExtraElements]
|
||||
internal sealed class VexTimelineEventRecord
|
||||
{
|
||||
[BsonId]
|
||||
public string Id { get; set; } = default!;
|
||||
|
||||
public string Tenant { get; set; } = default!;
|
||||
|
||||
public string ProviderId { get; set; } = default!;
|
||||
|
||||
public string StreamId { get; set; } = default!;
|
||||
|
||||
public string EventType { get; set; } = default!;
|
||||
|
||||
public string TraceId { get; set; } = default!;
|
||||
|
||||
public string JustificationSummary { get; set; } = string.Empty;
|
||||
|
||||
public string? EvidenceHash { get; set; }
|
||||
|
||||
public string? PayloadHash { get; set; }
|
||||
|
||||
public DateTime CreatedAt { get; set; }
|
||||
= DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc);
|
||||
|
||||
public Dictionary<string, string> Attributes { get; set; } = new(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MongoDB implementation of the timeline event store.
|
||||
/// </summary>
|
||||
internal sealed class MongoVexTimelineEventStore : IVexTimelineEventStore
|
||||
{
|
||||
private readonly IMongoCollection<VexTimelineEventRecord> _collection;
|
||||
|
||||
public MongoVexTimelineEventStore(IMongoDatabase database)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(database);
|
||||
_collection = database.GetCollection<VexTimelineEventRecord>(VexMongoCollectionNames.TimelineEvents);
|
||||
}
|
||||
|
||||
public async ValueTask<string> InsertAsync(
|
||||
TimelineEvent evt,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(evt);
|
||||
|
||||
var record = ToRecord(evt);
|
||||
|
||||
try
|
||||
{
|
||||
await _collection.InsertOneAsync(record, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return record.Id;
|
||||
}
|
||||
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
|
||||
{
|
||||
// Event already exists, return the ID anyway
|
||||
return record.Id;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<int> InsertManyAsync(
|
||||
string tenant,
|
||||
IEnumerable<TimelineEvent> events,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var records = events
|
||||
.Where(e => e is not null && string.Equals(NormalizeTenant(e.Tenant), normalizedTenant, StringComparison.Ordinal))
|
||||
.Select(ToRecord)
|
||||
.ToList();
|
||||
|
||||
if (records.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var options = new InsertManyOptions { IsOrdered = false };
|
||||
try
|
||||
{
|
||||
await _collection.InsertManyAsync(records, options, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return records.Count;
|
||||
}
|
||||
catch (MongoBulkWriteException<VexTimelineEventRecord> ex)
|
||||
{
|
||||
var duplicates = ex.WriteErrors?.Count(e => e.Category == ServerErrorCategory.DuplicateKey) ?? 0;
|
||||
return records.Count - duplicates;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<TimelineEvent>> FindByTimeRangeAsync(
|
||||
string tenant,
|
||||
DateTimeOffset from,
|
||||
DateTimeOffset to,
|
||||
int limit,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var fromUtc = from.UtcDateTime;
|
||||
var toUtc = to.UtcDateTime;
|
||||
|
||||
var filter = Builders<VexTimelineEventRecord>.Filter.And(
|
||||
Builders<VexTimelineEventRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexTimelineEventRecord>.Filter.Gte(r => r.CreatedAt, fromUtc),
|
||||
Builders<VexTimelineEventRecord>.Filter.Lte(r => r.CreatedAt, toUtc));
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexTimelineEventRecord>.Sort.Ascending(r => r.CreatedAt))
|
||||
.Limit(Math.Max(1, limit))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<TimelineEvent>> FindByTraceIdAsync(
|
||||
string tenant,
|
||||
string traceId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedTraceId = traceId?.Trim() ?? throw new ArgumentNullException(nameof(traceId));
|
||||
|
||||
var filter = Builders<VexTimelineEventRecord>.Filter.And(
|
||||
Builders<VexTimelineEventRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexTimelineEventRecord>.Filter.Eq(r => r.TraceId, normalizedTraceId));
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexTimelineEventRecord>.Sort.Ascending(r => r.CreatedAt))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<TimelineEvent>> FindByProviderAsync(
|
||||
string tenant,
|
||||
string providerId,
|
||||
int limit,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedProvider = providerId?.Trim().ToLowerInvariant()
|
||||
?? throw new ArgumentNullException(nameof(providerId));
|
||||
|
||||
var filter = Builders<VexTimelineEventRecord>.Filter.And(
|
||||
Builders<VexTimelineEventRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexTimelineEventRecord>.Filter.Eq(r => r.ProviderId, normalizedProvider));
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexTimelineEventRecord>.Sort.Descending(r => r.CreatedAt))
|
||||
.Limit(Math.Max(1, limit))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<TimelineEvent>> FindByEventTypeAsync(
|
||||
string tenant,
|
||||
string eventType,
|
||||
int limit,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedType = eventType?.Trim().ToLowerInvariant()
|
||||
?? throw new ArgumentNullException(nameof(eventType));
|
||||
|
||||
var filter = Builders<VexTimelineEventRecord>.Filter.And(
|
||||
Builders<VexTimelineEventRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexTimelineEventRecord>.Filter.Eq(r => r.EventType, normalizedType));
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexTimelineEventRecord>.Sort.Descending(r => r.CreatedAt))
|
||||
.Limit(Math.Max(1, limit))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<IReadOnlyList<TimelineEvent>> GetRecentAsync(
|
||||
string tenant,
|
||||
int limit,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
|
||||
var filter = Builders<VexTimelineEventRecord>.Filter.Eq(r => r.Tenant, normalizedTenant);
|
||||
|
||||
var records = await _collection
|
||||
.Find(filter)
|
||||
.Sort(Builders<VexTimelineEventRecord>.Sort.Descending(r => r.CreatedAt))
|
||||
.Limit(Math.Max(1, limit))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return records.Select(ToModel).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask<TimelineEvent?> GetByIdAsync(
|
||||
string tenant,
|
||||
string eventId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var normalizedId = eventId?.Trim() ?? throw new ArgumentNullException(nameof(eventId));
|
||||
|
||||
var filter = Builders<VexTimelineEventRecord>.Filter.And(
|
||||
Builders<VexTimelineEventRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexTimelineEventRecord>.Filter.Eq(r => r.Id, normalizedId));
|
||||
|
||||
var record = await _collection
|
||||
.Find(filter)
|
||||
.FirstOrDefaultAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return record is null ? null : ToModel(record);
|
||||
}
|
||||
|
||||
public async ValueTask<long> CountAsync(
|
||||
string tenant,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
|
||||
var filter = Builders<VexTimelineEventRecord>.Filter.Eq(r => r.Tenant, normalizedTenant);
|
||||
|
||||
return await _collection
|
||||
.CountDocumentsAsync(filter, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask<long> CountInRangeAsync(
|
||||
string tenant,
|
||||
DateTimeOffset from,
|
||||
DateTimeOffset to,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedTenant = NormalizeTenant(tenant);
|
||||
var fromUtc = from.UtcDateTime;
|
||||
var toUtc = to.UtcDateTime;
|
||||
|
||||
var filter = Builders<VexTimelineEventRecord>.Filter.And(
|
||||
Builders<VexTimelineEventRecord>.Filter.Eq(r => r.Tenant, normalizedTenant),
|
||||
Builders<VexTimelineEventRecord>.Filter.Gte(r => r.CreatedAt, fromUtc),
|
||||
Builders<VexTimelineEventRecord>.Filter.Lte(r => r.CreatedAt, toUtc));
|
||||
|
||||
return await _collection
|
||||
.CountDocumentsAsync(filter, cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static string NormalizeTenant(string tenant)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tenant))
|
||||
{
|
||||
throw new ArgumentException("tenant is required", nameof(tenant));
|
||||
}
|
||||
|
||||
return tenant.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static VexTimelineEventRecord ToRecord(TimelineEvent evt)
|
||||
{
|
||||
return new VexTimelineEventRecord
|
||||
{
|
||||
Id = evt.EventId,
|
||||
Tenant = evt.Tenant,
|
||||
ProviderId = evt.ProviderId.ToLowerInvariant(),
|
||||
StreamId = evt.StreamId.ToLowerInvariant(),
|
||||
EventType = evt.EventType.ToLowerInvariant(),
|
||||
TraceId = evt.TraceId,
|
||||
JustificationSummary = evt.JustificationSummary,
|
||||
EvidenceHash = evt.EvidenceHash,
|
||||
PayloadHash = evt.PayloadHash,
|
||||
CreatedAt = evt.CreatedAt.UtcDateTime,
|
||||
Attributes = evt.Attributes.ToDictionary(kvp => kvp.Key, kvp => kvp.Value, StringComparer.Ordinal)
|
||||
};
|
||||
}
|
||||
|
||||
private static TimelineEvent ToModel(VexTimelineEventRecord record)
|
||||
{
|
||||
var attributes = record.Attributes?.ToImmutableDictionary(StringComparer.Ordinal)
|
||||
?? ImmutableDictionary<string, string>.Empty;
|
||||
|
||||
return new TimelineEvent(
|
||||
eventId: record.Id,
|
||||
tenant: record.Tenant,
|
||||
providerId: record.ProviderId,
|
||||
streamId: record.StreamId,
|
||||
eventType: record.EventType,
|
||||
traceId: record.TraceId,
|
||||
justificationSummary: record.JustificationSummary,
|
||||
createdAt: new DateTimeOffset(DateTime.SpecifyKind(record.CreatedAt, DateTimeKind.Utc)),
|
||||
evidenceHash: record.EvidenceHash,
|
||||
payloadHash: record.PayloadHash,
|
||||
attributes: attributes);
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Storage.Mongo.Migrations;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
using StellaOps.Excititor.Storage.Mongo.Migrations;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
|
||||
namespace StellaOps.Excititor.Storage.Mongo;
|
||||
|
||||
@@ -49,24 +49,32 @@ public static class VexMongoServiceCollectionExtensions
|
||||
|
||||
services.AddScoped<IVexRawStore, MongoVexRawStore>();
|
||||
services.AddScoped<IVexExportStore, MongoVexExportStore>();
|
||||
services.AddScoped<IVexProviderStore, MongoVexProviderStore>();
|
||||
services.AddScoped<IVexNormalizerRouter, StorageBackedVexNormalizerRouter>();
|
||||
services.AddScoped<IVexConsensusStore, MongoVexConsensusStore>();
|
||||
services.AddScoped<IVexConsensusHoldStore, MongoVexConsensusHoldStore>();
|
||||
services.AddScoped<IVexClaimStore, MongoVexClaimStore>();
|
||||
services.AddScoped<IVexCacheIndex, MongoVexCacheIndex>();
|
||||
services.AddScoped<IVexCacheMaintenance, MongoVexCacheMaintenance>();
|
||||
services.AddScoped<IVexConnectorStateRepository, MongoVexConnectorStateRepository>();
|
||||
services.AddScoped<IAirgapImportStore, MongoAirgapImportStore>();
|
||||
services.AddScoped<VexStatementBackfillService>();
|
||||
services.AddScoped<IVexObservationLookup, MongoVexObservationLookup>();
|
||||
services.AddSingleton<IVexMongoMigration, VexInitialIndexMigration>();
|
||||
services.AddSingleton<IVexMongoMigration, VexRawSchemaMigration>();
|
||||
services.AddSingleton<IVexMongoMigration, VexConsensusSignalsMigration>();
|
||||
services.AddSingleton<IVexMongoMigration, VexConsensusHoldMigration>();
|
||||
services.AddSingleton<IVexMongoMigration, VexObservationCollectionsMigration>();
|
||||
services.AddSingleton<VexMongoMigrationRunner>();
|
||||
services.AddHostedService<VexMongoMigrationHostedService>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
services.AddScoped<IVexProviderStore, MongoVexProviderStore>();
|
||||
services.AddScoped<IVexNormalizerRouter, StorageBackedVexNormalizerRouter>();
|
||||
services.AddScoped<IVexConsensusStore, MongoVexConsensusStore>();
|
||||
services.AddScoped<IVexConsensusHoldStore, MongoVexConsensusHoldStore>();
|
||||
services.AddScoped<IVexClaimStore, MongoVexClaimStore>();
|
||||
services.AddScoped<IVexCacheIndex, MongoVexCacheIndex>();
|
||||
services.AddScoped<IVexCacheMaintenance, MongoVexCacheMaintenance>();
|
||||
services.AddScoped<IVexConnectorStateRepository, MongoVexConnectorStateRepository>();
|
||||
services.AddScoped<IAirgapImportStore, MongoAirgapImportStore>();
|
||||
services.AddScoped<VexStatementBackfillService>();
|
||||
services.AddScoped<IVexObservationLookup, MongoVexObservationLookup>();
|
||||
services.AddScoped<IVexObservationStore, MongoVexObservationStore>();
|
||||
services.AddScoped<IVexLinksetStore, MongoVexLinksetStore>();
|
||||
services.AddScoped<IVexLinksetEventPublisher, MongoVexLinksetEventPublisher>();
|
||||
services.AddScoped<VexLinksetDisagreementService>();
|
||||
services.AddScoped<IVexTimelineEventStore, MongoVexTimelineEventStore>();
|
||||
services.AddScoped<IVexTimelineEventEmitter, VexTimelineEventEmitter>();
|
||||
services.AddSingleton<IVexMongoMigration, VexInitialIndexMigration>();
|
||||
services.AddSingleton<IVexMongoMigration, VexTimelineEventIndexMigration>();
|
||||
services.AddSingleton<IVexMongoMigration, VexRawSchemaMigration>();
|
||||
services.AddSingleton<IVexMongoMigration, VexConsensusSignalsMigration>();
|
||||
services.AddSingleton<IVexMongoMigration, VexConsensusHoldMigration>();
|
||||
services.AddSingleton<IVexMongoMigration, VexObservationCollectionsMigration>();
|
||||
services.AddSingleton<IVexMongoMigration, VexRawIdempotencyIndexMigration>();
|
||||
services.AddSingleton<VexMongoMigrationRunner>();
|
||||
services.AddHostedService<VexMongoMigrationHostedService>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Text.RegularExpressions;
|
||||
using MongoDB.Bson;
|
||||
|
||||
namespace StellaOps.Excititor.Storage.Mongo.Validation;
|
||||
|
||||
/// <summary>
|
||||
/// Validates VEX raw documents against the schema defined in <see cref="Migrations.VexRawSchemaMigration"/>.
|
||||
/// Provides programmatic validation for operators to prove Excititor stores only immutable evidence.
|
||||
/// </summary>
|
||||
public static class VexRawSchemaValidator
|
||||
{
|
||||
private static readonly ImmutableHashSet<string> ValidFormats = ImmutableHashSet.Create(
|
||||
StringComparer.OrdinalIgnoreCase,
|
||||
"csaf", "cyclonedx", "openvex");
|
||||
|
||||
private static readonly ImmutableHashSet<BsonType> ValidContentTypes = ImmutableHashSet.Create(
|
||||
BsonType.Binary, BsonType.String);
|
||||
|
||||
private static readonly ImmutableHashSet<BsonType> ValidGridFsTypes = ImmutableHashSet.Create(
|
||||
BsonType.ObjectId, BsonType.Null, BsonType.String);
|
||||
|
||||
/// <summary>
|
||||
/// Validates a VEX raw document against the schema requirements.
|
||||
/// </summary>
|
||||
/// <param name="document">The document to validate.</param>
|
||||
/// <returns>Validation result with any violations found.</returns>
|
||||
public static VexRawValidationResult Validate(BsonDocument document)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(document);
|
||||
|
||||
var violations = new List<VexRawSchemaViolation>();
|
||||
|
||||
// Required fields
|
||||
ValidateRequired(document, "_id", violations);
|
||||
ValidateRequired(document, "providerId", violations);
|
||||
ValidateRequired(document, "format", violations);
|
||||
ValidateRequired(document, "sourceUri", violations);
|
||||
ValidateRequired(document, "retrievedAt", violations);
|
||||
ValidateRequired(document, "digest", violations);
|
||||
|
||||
// Field types and constraints
|
||||
ValidateStringField(document, "_id", minLength: 1, violations);
|
||||
ValidateStringField(document, "providerId", minLength: 1, violations);
|
||||
ValidateFormatEnum(document, violations);
|
||||
ValidateStringField(document, "sourceUri", minLength: 1, violations);
|
||||
ValidateDateField(document, "retrievedAt", violations);
|
||||
ValidateStringField(document, "digest", minLength: 32, violations);
|
||||
|
||||
// Optional fields with type constraints
|
||||
if (document.Contains("content"))
|
||||
{
|
||||
ValidateContentField(document, violations);
|
||||
}
|
||||
|
||||
if (document.Contains("gridFsObjectId"))
|
||||
{
|
||||
ValidateGridFsObjectIdField(document, violations);
|
||||
}
|
||||
|
||||
if (document.Contains("metadata"))
|
||||
{
|
||||
ValidateMetadataField(document, violations);
|
||||
}
|
||||
|
||||
return new VexRawValidationResult(
|
||||
document.GetValue("_id", BsonNull.Value).ToString() ?? "<unknown>",
|
||||
violations.Count == 0,
|
||||
violations.ToImmutableArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates multiple documents and returns aggregated results.
|
||||
/// </summary>
|
||||
public static VexRawBatchValidationResult ValidateBatch(IEnumerable<BsonDocument> documents)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(documents);
|
||||
|
||||
var results = new List<VexRawValidationResult>();
|
||||
foreach (var doc in documents)
|
||||
{
|
||||
results.Add(Validate(doc));
|
||||
}
|
||||
|
||||
var valid = results.Count(r => r.IsValid);
|
||||
var invalid = results.Count(r => !r.IsValid);
|
||||
|
||||
return new VexRawBatchValidationResult(
|
||||
results.Count,
|
||||
valid,
|
||||
invalid,
|
||||
results.Where(r => !r.IsValid).ToImmutableArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the MongoDB JSON Schema document for offline validation.
|
||||
/// </summary>
|
||||
public static BsonDocument GetJsonSchema()
|
||||
{
|
||||
var properties = new BsonDocument
|
||||
{
|
||||
{ "_id", new BsonDocument { { "bsonType", "string" }, { "description", "Content digest serving as immutable key" } } },
|
||||
{ "providerId", new BsonDocument { { "bsonType", "string" }, { "minLength", 1 }, { "description", "VEX provider identifier" } } },
|
||||
{ "format", new BsonDocument
|
||||
{
|
||||
{ "bsonType", "string" },
|
||||
{ "enum", new BsonArray { "csaf", "cyclonedx", "openvex" } },
|
||||
{ "description", "VEX document format" }
|
||||
}
|
||||
},
|
||||
{ "sourceUri", new BsonDocument { { "bsonType", "string" }, { "minLength", 1 }, { "description", "Original source URI" } } },
|
||||
{ "retrievedAt", new BsonDocument { { "bsonType", "date" }, { "description", "Timestamp when document was fetched" } } },
|
||||
{ "digest", new BsonDocument { { "bsonType", "string" }, { "minLength", 32 }, { "description", "Content hash (SHA-256 hex)" } } },
|
||||
{ "content", new BsonDocument
|
||||
{
|
||||
{ "bsonType", new BsonArray { "binData", "string" } },
|
||||
{ "description", "Raw document content (binary or base64 string)" }
|
||||
}
|
||||
},
|
||||
{ "gridFsObjectId", new BsonDocument
|
||||
{
|
||||
{ "bsonType", new BsonArray { "objectId", "null", "string" } },
|
||||
{ "description", "GridFS reference for large documents" }
|
||||
}
|
||||
},
|
||||
{ "metadata", new BsonDocument
|
||||
{
|
||||
{ "bsonType", "object" },
|
||||
{ "additionalProperties", true },
|
||||
{ "description", "Provider-specific metadata (string values only)" }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return new BsonDocument
|
||||
{
|
||||
{
|
||||
"$jsonSchema",
|
||||
new BsonDocument
|
||||
{
|
||||
{ "bsonType", "object" },
|
||||
{ "title", "VEX Raw Document Schema" },
|
||||
{ "description", "Schema for immutable VEX evidence storage. Documents are content-addressed and must not be modified after insertion." },
|
||||
{ "required", new BsonArray { "_id", "providerId", "format", "sourceUri", "retrievedAt", "digest" } },
|
||||
{ "properties", properties },
|
||||
{ "additionalProperties", true }
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the schema as a JSON string for operator documentation.
|
||||
/// </summary>
|
||||
public static string GetJsonSchemaAsJson()
|
||||
{
|
||||
return GetJsonSchema().ToJson(new MongoDB.Bson.IO.JsonWriterSettings { Indent = true });
|
||||
}
|
||||
|
||||
private static void ValidateRequired(BsonDocument doc, string field, List<VexRawSchemaViolation> violations)
|
||||
{
|
||||
if (!doc.Contains(field) || doc[field].IsBsonNull)
|
||||
{
|
||||
violations.Add(new VexRawSchemaViolation(field, $"Required field '{field}' is missing or null"));
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateStringField(BsonDocument doc, string field, int minLength, List<VexRawSchemaViolation> violations)
|
||||
{
|
||||
if (!doc.Contains(field))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var value = doc[field];
|
||||
if (value.IsBsonNull)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!value.IsString)
|
||||
{
|
||||
violations.Add(new VexRawSchemaViolation(field, $"Field '{field}' must be a string, got {value.BsonType}"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (value.AsString.Length < minLength)
|
||||
{
|
||||
violations.Add(new VexRawSchemaViolation(field, $"Field '{field}' must have minimum length {minLength}, got {value.AsString.Length}"));
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateFormatEnum(BsonDocument doc, List<VexRawSchemaViolation> violations)
|
||||
{
|
||||
if (!doc.Contains("format"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var value = doc["format"];
|
||||
if (value.IsBsonNull || !value.IsString)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ValidFormats.Contains(value.AsString))
|
||||
{
|
||||
violations.Add(new VexRawSchemaViolation("format", $"Field 'format' must be one of [{string.Join(", ", ValidFormats)}], got '{value.AsString}'"));
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateDateField(BsonDocument doc, string field, List<VexRawSchemaViolation> violations)
|
||||
{
|
||||
if (!doc.Contains(field))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var value = doc[field];
|
||||
if (value.IsBsonNull)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (value.BsonType != BsonType.DateTime)
|
||||
{
|
||||
violations.Add(new VexRawSchemaViolation(field, $"Field '{field}' must be a date, got {value.BsonType}"));
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateContentField(BsonDocument doc, List<VexRawSchemaViolation> violations)
|
||||
{
|
||||
var value = doc["content"];
|
||||
if (value.IsBsonNull)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ValidContentTypes.Contains(value.BsonType))
|
||||
{
|
||||
violations.Add(new VexRawSchemaViolation("content", $"Field 'content' must be binary or string, got {value.BsonType}"));
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateGridFsObjectIdField(BsonDocument doc, List<VexRawSchemaViolation> violations)
|
||||
{
|
||||
var value = doc["gridFsObjectId"];
|
||||
if (!ValidGridFsTypes.Contains(value.BsonType))
|
||||
{
|
||||
violations.Add(new VexRawSchemaViolation("gridFsObjectId", $"Field 'gridFsObjectId' must be objectId, null, or string, got {value.BsonType}"));
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateMetadataField(BsonDocument doc, List<VexRawSchemaViolation> violations)
|
||||
{
|
||||
var value = doc["metadata"];
|
||||
if (value.IsBsonNull)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (value.BsonType != BsonType.Document)
|
||||
{
|
||||
violations.Add(new VexRawSchemaViolation("metadata", $"Field 'metadata' must be an object, got {value.BsonType}"));
|
||||
return;
|
||||
}
|
||||
|
||||
var metadata = value.AsBsonDocument;
|
||||
foreach (var element in metadata)
|
||||
{
|
||||
if (!element.Value.IsString && !element.Value.IsBsonNull)
|
||||
{
|
||||
violations.Add(new VexRawSchemaViolation($"metadata.{element.Name}", $"Metadata field '{element.Name}' must be a string, got {element.Value.BsonType}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a schema violation found during validation.
|
||||
/// </summary>
|
||||
public sealed record VexRawSchemaViolation(string Field, string Message);
|
||||
|
||||
/// <summary>
|
||||
/// Result of validating a single VEX raw document.
|
||||
/// </summary>
|
||||
public sealed record VexRawValidationResult(
|
||||
string DocumentId,
|
||||
bool IsValid,
|
||||
ImmutableArray<VexRawSchemaViolation> Violations);
|
||||
|
||||
/// <summary>
|
||||
/// Result of validating a batch of VEX raw documents.
|
||||
/// </summary>
|
||||
public sealed record VexRawBatchValidationResult(
|
||||
int TotalCount,
|
||||
int ValidCount,
|
||||
int InvalidCount,
|
||||
ImmutableArray<VexRawValidationResult> InvalidDocuments);
|
||||
@@ -47,6 +47,7 @@ public static class VexMongoMappingRegistry
|
||||
RegisterClassMap<VexConnectorStateDocument>();
|
||||
RegisterClassMap<VexConsensusHoldRecord>();
|
||||
RegisterClassMap<AirgapImportRecord>();
|
||||
RegisterClassMap<VexTimelineEventRecord>();
|
||||
}
|
||||
|
||||
private static void RegisterClassMap<TDocument>()
|
||||
@@ -80,5 +81,7 @@ public static class VexMongoCollectionNames
|
||||
public const string Attestations = "vex.attestations";
|
||||
public const string Observations = "vex.observations";
|
||||
public const string Linksets = "vex.linksets";
|
||||
public const string LinksetEvents = "vex.linkset_events";
|
||||
public const string AirgapImports = "vex.airgap_imports";
|
||||
public const string TimelineEvents = "vex.timeline_events";
|
||||
}
|
||||
|
||||
@@ -490,6 +490,10 @@ internal sealed class VexLinksetRecord
|
||||
|
||||
public DateTime CreatedAt { get; set; } = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc);
|
||||
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc);
|
||||
|
||||
public List<VexObservationLinksetObservationRecord> Observations { get; set; } = new();
|
||||
|
||||
public List<VexLinksetDisagreementRecord> Disagreements { get; set; } = new();
|
||||
}
|
||||
|
||||
@@ -1310,6 +1314,21 @@ internal sealed class VexConnectorStateDocument
|
||||
public string? LastFailureReason { get; set; }
|
||||
= null;
|
||||
|
||||
public DateTime? LastHeartbeatAt { get; set; }
|
||||
= null;
|
||||
|
||||
public string? LastHeartbeatStatus { get; set; }
|
||||
= null;
|
||||
|
||||
public string? LastArtifactHash { get; set; }
|
||||
= null;
|
||||
|
||||
public string? LastArtifactKind { get; set; }
|
||||
= null;
|
||||
|
||||
public string? LastCheckpoint { get; set; }
|
||||
= null;
|
||||
|
||||
public static VexConnectorStateDocument FromRecord(VexConnectorState state)
|
||||
=> new()
|
||||
{
|
||||
@@ -1323,6 +1342,11 @@ internal sealed class VexConnectorStateDocument
|
||||
FailureCount = state.FailureCount,
|
||||
NextEligibleRun = state.NextEligibleRun?.UtcDateTime,
|
||||
LastFailureReason = state.LastFailureReason,
|
||||
LastHeartbeatAt = state.LastHeartbeatAt?.UtcDateTime,
|
||||
LastHeartbeatStatus = state.LastHeartbeatStatus,
|
||||
LastArtifactHash = state.LastArtifactHash,
|
||||
LastArtifactKind = state.LastArtifactKind,
|
||||
LastCheckpoint = state.LastCheckpoint,
|
||||
};
|
||||
|
||||
public VexConnectorState ToRecord()
|
||||
@@ -1336,6 +1360,9 @@ internal sealed class VexConnectorStateDocument
|
||||
var nextEligibleRun = NextEligibleRun.HasValue
|
||||
? new DateTimeOffset(DateTime.SpecifyKind(NextEligibleRun.Value, DateTimeKind.Utc))
|
||||
: (DateTimeOffset?)null;
|
||||
var lastHeartbeatAt = LastHeartbeatAt.HasValue
|
||||
? new DateTimeOffset(DateTime.SpecifyKind(LastHeartbeatAt.Value, DateTimeKind.Utc))
|
||||
: (DateTimeOffset?)null;
|
||||
|
||||
return new VexConnectorState(
|
||||
ConnectorId,
|
||||
@@ -1345,6 +1372,52 @@ internal sealed class VexConnectorStateDocument
|
||||
lastSuccessAt,
|
||||
FailureCount,
|
||||
nextEligibleRun,
|
||||
string.IsNullOrWhiteSpace(LastFailureReason) ? null : LastFailureReason);
|
||||
string.IsNullOrWhiteSpace(LastFailureReason) ? null : LastFailureReason,
|
||||
lastHeartbeatAt,
|
||||
LastHeartbeatStatus,
|
||||
LastArtifactHash,
|
||||
LastArtifactKind,
|
||||
LastCheckpoint);
|
||||
}
|
||||
}
|
||||
|
||||
[BsonIgnoreExtraElements]
|
||||
internal sealed class VexLinksetEventRecord
|
||||
{
|
||||
[BsonId]
|
||||
public string Id { get; set; } = default!;
|
||||
|
||||
public string EventType { get; set; } = default!;
|
||||
|
||||
public string Tenant { get; set; } = default!;
|
||||
|
||||
public string LinksetId { get; set; } = default!;
|
||||
|
||||
public string VulnerabilityId { get; set; } = default!;
|
||||
|
||||
public string ProductKey { get; set; } = default!;
|
||||
|
||||
public List<VexLinksetEventObservationRecord> Observations { get; set; } = new();
|
||||
|
||||
public List<VexLinksetDisagreementRecord> Disagreements { get; set; } = new();
|
||||
|
||||
public DateTime CreatedAtUtc { get; set; } = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc);
|
||||
|
||||
public DateTime PublishedAtUtc { get; set; } = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc);
|
||||
|
||||
public int ConflictCount { get; set; } = 0;
|
||||
|
||||
public int ObservationCount { get; set; } = 0;
|
||||
}
|
||||
|
||||
[BsonIgnoreExtraElements]
|
||||
internal sealed class VexLinksetEventObservationRecord
|
||||
{
|
||||
public string ObservationId { get; set; } = default!;
|
||||
|
||||
public string ProviderId { get; set; } = default!;
|
||||
|
||||
public string Status { get; set; } = default!;
|
||||
|
||||
public double? Confidence { get; set; } = null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
|
||||
namespace StellaOps.Excititor.Storage.Mongo;
|
||||
|
||||
/// <summary>
|
||||
/// Default implementation of <see cref="IVexTimelineEventEmitter"/> that persists events to MongoDB.
|
||||
/// </summary>
|
||||
internal sealed class VexTimelineEventEmitter : IVexTimelineEventEmitter
|
||||
{
|
||||
private readonly IVexTimelineEventStore _store;
|
||||
private readonly ILogger<VexTimelineEventEmitter> _logger;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
|
||||
public VexTimelineEventEmitter(
|
||||
IVexTimelineEventStore store,
|
||||
ILogger<VexTimelineEventEmitter> logger,
|
||||
TimeProvider? timeProvider = null)
|
||||
{
|
||||
_store = store ?? throw new ArgumentNullException(nameof(store));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_timeProvider = timeProvider ?? TimeProvider.System;
|
||||
}
|
||||
|
||||
public async ValueTask EmitObservationIngestAsync(
|
||||
string tenant,
|
||||
string providerId,
|
||||
string streamId,
|
||||
string traceId,
|
||||
string observationId,
|
||||
string evidenceHash,
|
||||
string justificationSummary,
|
||||
ImmutableDictionary<string, string>? attributes = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var eventAttributes = (attributes ?? ImmutableDictionary<string, string>.Empty)
|
||||
.SetItem(VexTimelineEventAttributes.ObservationId, observationId);
|
||||
|
||||
var evt = new TimelineEvent(
|
||||
eventId: GenerateEventId(tenant, providerId, VexTimelineEventTypes.ObservationIngested),
|
||||
tenant: tenant,
|
||||
providerId: providerId,
|
||||
streamId: streamId,
|
||||
eventType: VexTimelineEventTypes.ObservationIngested,
|
||||
traceId: traceId,
|
||||
justificationSummary: justificationSummary,
|
||||
createdAt: _timeProvider.GetUtcNow(),
|
||||
evidenceHash: evidenceHash,
|
||||
payloadHash: null,
|
||||
attributes: eventAttributes);
|
||||
|
||||
await EmitAsync(evt, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask EmitLinksetUpdateAsync(
|
||||
string tenant,
|
||||
string providerId,
|
||||
string streamId,
|
||||
string traceId,
|
||||
string linksetId,
|
||||
string vulnerabilityId,
|
||||
string productKey,
|
||||
string payloadHash,
|
||||
string justificationSummary,
|
||||
ImmutableDictionary<string, string>? attributes = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var eventAttributes = (attributes ?? ImmutableDictionary<string, string>.Empty)
|
||||
.SetItem(VexTimelineEventAttributes.LinksetId, linksetId)
|
||||
.SetItem(VexTimelineEventAttributes.VulnerabilityId, vulnerabilityId)
|
||||
.SetItem(VexTimelineEventAttributes.ProductKey, productKey);
|
||||
|
||||
var evt = new TimelineEvent(
|
||||
eventId: GenerateEventId(tenant, providerId, VexTimelineEventTypes.LinksetUpdated),
|
||||
tenant: tenant,
|
||||
providerId: providerId,
|
||||
streamId: streamId,
|
||||
eventType: VexTimelineEventTypes.LinksetUpdated,
|
||||
traceId: traceId,
|
||||
justificationSummary: justificationSummary,
|
||||
createdAt: _timeProvider.GetUtcNow(),
|
||||
evidenceHash: null,
|
||||
payloadHash: payloadHash,
|
||||
attributes: eventAttributes);
|
||||
|
||||
await EmitAsync(evt, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask EmitAsync(
|
||||
TimelineEvent evt,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(evt);
|
||||
|
||||
try
|
||||
{
|
||||
var eventId = await _store.InsertAsync(evt, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Timeline event emitted: {EventType} for tenant {Tenant}, provider {ProviderId}, trace {TraceId}",
|
||||
evt.EventType,
|
||||
evt.Tenant,
|
||||
evt.ProviderId,
|
||||
evt.TraceId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Failed to emit timeline event {EventType} for tenant {Tenant}, provider {ProviderId}: {Message}",
|
||||
evt.EventType,
|
||||
evt.Tenant,
|
||||
evt.ProviderId,
|
||||
ex.Message);
|
||||
|
||||
// Don't throw - timeline events are non-critical and shouldn't block main operations
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask EmitBatchAsync(
|
||||
string tenant,
|
||||
IEnumerable<TimelineEvent> events,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(events);
|
||||
|
||||
var eventList = events.ToList();
|
||||
if (eventList.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var insertedCount = await _store.InsertManyAsync(tenant, eventList, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Batch timeline events emitted: {InsertedCount}/{TotalCount} for tenant {Tenant}",
|
||||
insertedCount,
|
||||
eventList.Count,
|
||||
tenant);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Failed to emit batch timeline events for tenant {Tenant}: {Message}",
|
||||
tenant,
|
||||
ex.Message);
|
||||
|
||||
// Don't throw - timeline events are non-critical
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a deterministic event ID based on tenant, provider, event type, and timestamp.
|
||||
/// </summary>
|
||||
private string GenerateEventId(string tenant, string providerId, string eventType)
|
||||
{
|
||||
var timestamp = _timeProvider.GetUtcNow().ToUnixTimeMilliseconds();
|
||||
var input = $"{tenant}|{providerId}|{eventType}|{timestamp}|{Guid.NewGuid():N}";
|
||||
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(input));
|
||||
return $"evt:{Convert.ToHexString(hash).ToLowerInvariant()[..32]}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using StellaOps.Excititor.Core.Canonicalization;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.Core.UnitTests.Canonicalization;
|
||||
|
||||
public class VexAdvisoryKeyCanonicalizerTests
|
||||
{
|
||||
private readonly VexAdvisoryKeyCanonicalizer _canonicalizer = new();
|
||||
|
||||
[Theory]
|
||||
[InlineData("CVE-2025-12345", "CVE-2025-12345", VexAdvisoryScope.Global)]
|
||||
[InlineData("cve-2025-12345", "CVE-2025-12345", VexAdvisoryScope.Global)]
|
||||
[InlineData("CVE-2024-1234567", "CVE-2024-1234567", VexAdvisoryScope.Global)]
|
||||
public void Canonicalize_Cve_ReturnsGlobalScope(string input, string expectedKey, VexAdvisoryScope expectedScope)
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(input);
|
||||
|
||||
Assert.Equal(expectedKey, result.AdvisoryKey);
|
||||
Assert.Equal(expectedScope, result.Scope);
|
||||
Assert.Single(result.Links);
|
||||
Assert.Equal("cve", result.Links[0].Type);
|
||||
Assert.True(result.Links[0].IsOriginal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GHSA-abcd-efgh-ijkl", "ECO:GHSA-ABCD-EFGH-IJKL", VexAdvisoryScope.Ecosystem)]
|
||||
[InlineData("ghsa-1234-5678-90ab", "ECO:GHSA-1234-5678-90AB", VexAdvisoryScope.Ecosystem)]
|
||||
public void Canonicalize_Ghsa_ReturnsEcosystemScope(string input, string expectedKey, VexAdvisoryScope expectedScope)
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(input);
|
||||
|
||||
Assert.Equal(expectedKey, result.AdvisoryKey);
|
||||
Assert.Equal(expectedScope, result.Scope);
|
||||
Assert.Equal("ghsa", result.Links[0].Type);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("RHSA-2025:1234", "VND:RHSA-2025:1234", VexAdvisoryScope.Vendor)]
|
||||
[InlineData("RHBA-2024:5678", "VND:RHBA-2024:5678", VexAdvisoryScope.Vendor)]
|
||||
public void Canonicalize_Rhsa_ReturnsVendorScope(string input, string expectedKey, VexAdvisoryScope expectedScope)
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(input);
|
||||
|
||||
Assert.Equal(expectedKey, result.AdvisoryKey);
|
||||
Assert.Equal(expectedScope, result.Scope);
|
||||
Assert.Equal("rhsa", result.Links[0].Type);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("DSA-5678", "DST:DSA-5678", VexAdvisoryScope.Distribution)]
|
||||
[InlineData("DSA-1234-1", "DST:DSA-1234-1", VexAdvisoryScope.Distribution)]
|
||||
[InlineData("USN-6543", "DST:USN-6543", VexAdvisoryScope.Distribution)]
|
||||
[InlineData("USN-1234-2", "DST:USN-1234-2", VexAdvisoryScope.Distribution)]
|
||||
public void Canonicalize_DistributionIds_ReturnsDistributionScope(string input, string expectedKey, VexAdvisoryScope expectedScope)
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(input);
|
||||
|
||||
Assert.Equal(expectedKey, result.AdvisoryKey);
|
||||
Assert.Equal(expectedScope, result.Scope);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_WithAliases_PreservesAllLinks()
|
||||
{
|
||||
var aliases = new[] { "RHSA-2025:1234", "GHSA-abcd-efgh-ijkl" };
|
||||
|
||||
var result = _canonicalizer.Canonicalize("CVE-2025-12345", aliases);
|
||||
|
||||
Assert.Equal("CVE-2025-12345", result.AdvisoryKey);
|
||||
Assert.Equal(3, result.Links.Length);
|
||||
|
||||
var original = result.Links.Single(l => l.IsOriginal);
|
||||
Assert.Equal("CVE-2025-12345", original.Identifier);
|
||||
Assert.Equal("cve", original.Type);
|
||||
|
||||
var nonOriginal = result.Links.Where(l => !l.IsOriginal).ToArray();
|
||||
Assert.Equal(2, nonOriginal.Length);
|
||||
Assert.Contains(nonOriginal, l => l.Type == "rhsa");
|
||||
Assert.Contains(nonOriginal, l => l.Type == "ghsa");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_WithDuplicateAliases_DeduplicatesLinks()
|
||||
{
|
||||
var aliases = new[] { "CVE-2025-12345", "cve-2025-12345", "RHSA-2025:1234" };
|
||||
|
||||
var result = _canonicalizer.Canonicalize("CVE-2025-12345", aliases);
|
||||
|
||||
// Should have 2 links: original CVE and RHSA (duplicates removed)
|
||||
Assert.Equal(2, result.Links.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_UnknownFormat_ReturnsUnknownScope()
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize("VENDOR-CUSTOM-12345");
|
||||
|
||||
Assert.Equal("UNK:VENDOR-CUSTOM-12345", result.AdvisoryKey);
|
||||
Assert.Equal(VexAdvisoryScope.Unknown, result.Scope);
|
||||
Assert.Equal("other", result.Links[0].Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_NullInput_ThrowsArgumentException()
|
||||
{
|
||||
Assert.ThrowsAny<ArgumentException>(() => _canonicalizer.Canonicalize(null!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_EmptyInput_ThrowsArgumentException()
|
||||
{
|
||||
Assert.ThrowsAny<ArgumentException>(() => _canonicalizer.Canonicalize(""));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_WhitespaceInput_ThrowsArgumentException()
|
||||
{
|
||||
Assert.ThrowsAny<ArgumentException>(() => _canonicalizer.Canonicalize(" "));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExtractCveFromAliases_WithCve_ReturnsCve()
|
||||
{
|
||||
var aliases = new[] { "RHSA-2025:1234", "CVE-2025-99999", "GHSA-xxxx-yyyy-zzzz" };
|
||||
|
||||
var cve = _canonicalizer.ExtractCveFromAliases(aliases);
|
||||
|
||||
Assert.Equal("CVE-2025-99999", cve);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExtractCveFromAliases_WithoutCve_ReturnsNull()
|
||||
{
|
||||
var aliases = new[] { "RHSA-2025:1234", "GHSA-xxxx-yyyy-zzzz" };
|
||||
|
||||
var cve = _canonicalizer.ExtractCveFromAliases(aliases);
|
||||
|
||||
Assert.Null(cve);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExtractCveFromAliases_NullInput_ReturnsNull()
|
||||
{
|
||||
var cve = _canonicalizer.ExtractCveFromAliases(null);
|
||||
|
||||
Assert.Null(cve);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OriginalId_ReturnsOriginalIdentifier()
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize("CVE-2025-12345");
|
||||
|
||||
Assert.Equal("CVE-2025-12345", result.OriginalId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Aliases_ReturnsNonOriginalIdentifiers()
|
||||
{
|
||||
var aliases = new[] { "RHSA-2025:1234", "GHSA-abcd-efgh-ijkl" };
|
||||
var result = _canonicalizer.Canonicalize("CVE-2025-12345", aliases);
|
||||
|
||||
var aliasArray = result.Aliases.ToArray();
|
||||
Assert.Equal(2, aliasArray.Length);
|
||||
Assert.Contains("RHSA-2025:1234", aliasArray);
|
||||
Assert.Contains("GHSA-abcd-efgh-ijkl", aliasArray);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using StellaOps.Excititor.Core.Canonicalization;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.Core.UnitTests.Canonicalization;
|
||||
|
||||
public class VexProductKeyCanonicalizerTests
|
||||
{
|
||||
private readonly VexProductKeyCanonicalizer _canonicalizer = new();
|
||||
|
||||
[Theory]
|
||||
[InlineData("pkg:npm/leftpad@1.0.0", "pkg:npm/leftpad@1.0.0", VexProductKeyType.Purl, VexProductScope.Package)]
|
||||
[InlineData("pkg:maven/org.apache.log4j/log4j-core@2.17.0", "pkg:maven/org.apache.log4j/log4j-core@2.17.0", VexProductKeyType.Purl, VexProductScope.Package)]
|
||||
[InlineData("PKG:pypi/requests@2.28.0", "pkg:pypi/requests@2.28.0", VexProductKeyType.Purl, VexProductScope.Package)]
|
||||
public void Canonicalize_Purl_ReturnsPackageScope(string input, string expectedKey, VexProductKeyType expectedType, VexProductScope expectedScope)
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(input);
|
||||
|
||||
Assert.Equal(expectedKey, result.ProductKey);
|
||||
Assert.Equal(expectedType, result.KeyType);
|
||||
Assert.Equal(expectedScope, result.Scope);
|
||||
Assert.Single(result.Links);
|
||||
Assert.Equal("purl", result.Links[0].Type);
|
||||
Assert.True(result.Links[0].IsOriginal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("cpe:2.3:a:apache:log4j:2.14.0:*:*:*:*:*:*:*", "cpe:2.3:a:apache:log4j:2.14.0:*:*:*:*:*:*:*", VexProductKeyType.Cpe, VexProductScope.Component)]
|
||||
[InlineData("cpe:/a:apache:log4j:2.14.0", "cpe:/a:apache:log4j:2.14.0", VexProductKeyType.Cpe, VexProductScope.Component)]
|
||||
[InlineData("CPE:2.3:a:vendor:product:1.0", "cpe:2.3:a:vendor:product:1.0", VexProductKeyType.Cpe, VexProductScope.Component)]
|
||||
public void Canonicalize_Cpe_ReturnsComponentScope(string input, string expectedKey, VexProductKeyType expectedType, VexProductScope expectedScope)
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(input);
|
||||
|
||||
Assert.Equal(expectedKey, result.ProductKey);
|
||||
Assert.Equal(expectedType, result.KeyType);
|
||||
Assert.Equal(expectedScope, result.Scope);
|
||||
Assert.Equal("cpe", result.Links[0].Type);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("openssl-3.0.9-1.el9.x86_64", VexProductKeyType.RpmNevra, VexProductScope.OsPackage)]
|
||||
[InlineData("kernel-5.14.0-284.25.1.el9_2.x86_64", VexProductKeyType.RpmNevra, VexProductScope.OsPackage)]
|
||||
public void Canonicalize_RpmNevra_ReturnsOsPackageScope(string input, VexProductKeyType expectedType, VexProductScope expectedScope)
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(input);
|
||||
|
||||
Assert.StartsWith("rpm:", result.ProductKey);
|
||||
Assert.Equal(expectedType, result.KeyType);
|
||||
Assert.Equal(expectedScope, result.Scope);
|
||||
Assert.Equal("rpmnevra", result.Links[0].Type);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("oci:ghcr.io/example/app@sha256:abc123", VexProductKeyType.OciImage, VexProductScope.Container)]
|
||||
[InlineData("oci:docker.io/library/nginx:1.25", VexProductKeyType.OciImage, VexProductScope.Container)]
|
||||
public void Canonicalize_OciImage_ReturnsContainerScope(string input, VexProductKeyType expectedType, VexProductScope expectedScope)
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(input);
|
||||
|
||||
Assert.Equal(input, result.ProductKey);
|
||||
Assert.Equal(expectedType, result.KeyType);
|
||||
Assert.Equal(expectedScope, result.Scope);
|
||||
Assert.Equal("ociimage", result.Links[0].Type);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("platform:redhat:rhel:9", VexProductKeyType.Platform, VexProductScope.Platform)]
|
||||
[InlineData("platform:ubuntu:jammy:22.04", VexProductKeyType.Platform, VexProductScope.Platform)]
|
||||
public void Canonicalize_Platform_ReturnsPlatformScope(string input, VexProductKeyType expectedType, VexProductScope expectedScope)
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(input);
|
||||
|
||||
Assert.Equal(input, result.ProductKey);
|
||||
Assert.Equal(expectedType, result.KeyType);
|
||||
Assert.Equal(expectedScope, result.Scope);
|
||||
Assert.Equal("platform", result.Links[0].Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_WithPurl_PrefersPurlAsCanonicalKey()
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(
|
||||
originalKey: "openssl-3.0.9",
|
||||
purl: "pkg:rpm/redhat/openssl@3.0.9");
|
||||
|
||||
Assert.Equal("pkg:rpm/redhat/openssl@3.0.9", result.ProductKey);
|
||||
Assert.Equal(VexProductScope.Package, result.Scope);
|
||||
Assert.Equal(2, result.Links.Length);
|
||||
|
||||
var original = result.Links.Single(l => l.IsOriginal);
|
||||
Assert.Equal("openssl-3.0.9", original.Identifier);
|
||||
|
||||
var purlLink = result.Links.Single(l => l.Type == "purl");
|
||||
Assert.Equal("pkg:rpm/redhat/openssl@3.0.9", purlLink.Identifier);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_WithCpe_PrefersCpeWhenNoPurl()
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(
|
||||
originalKey: "openssl",
|
||||
cpe: "cpe:2.3:a:openssl:openssl:3.0.9:*:*:*:*:*:*:*");
|
||||
|
||||
Assert.Equal("cpe:2.3:a:openssl:openssl:3.0.9:*:*:*:*:*:*:*", result.ProductKey);
|
||||
Assert.Equal(VexProductScope.Component, result.Scope);
|
||||
Assert.Equal(2, result.Links.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_WithComponentIdentifiers_PreservesAllLinks()
|
||||
{
|
||||
var componentIds = new[]
|
||||
{
|
||||
"pkg:rpm/redhat/openssl@3.0.9",
|
||||
"cpe:2.3:a:openssl:openssl:3.0.9:*:*:*:*:*:*:*"
|
||||
};
|
||||
|
||||
var result = _canonicalizer.Canonicalize(
|
||||
originalKey: "openssl-3.0.9",
|
||||
componentIdentifiers: componentIds);
|
||||
|
||||
// PURL should be chosen as canonical key
|
||||
Assert.Equal("pkg:rpm/redhat/openssl@3.0.9", result.ProductKey);
|
||||
Assert.Equal(3, result.Links.Length);
|
||||
|
||||
var original = result.Links.Single(l => l.IsOriginal);
|
||||
Assert.Equal("openssl-3.0.9", original.Identifier);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_WithDuplicates_DeduplicatesLinks()
|
||||
{
|
||||
var componentIds = new[]
|
||||
{
|
||||
"pkg:npm/leftpad@1.0.0",
|
||||
"pkg:npm/leftpad@1.0.0", // Duplicate
|
||||
};
|
||||
|
||||
var result = _canonicalizer.Canonicalize(
|
||||
originalKey: "pkg:npm/leftpad@1.0.0",
|
||||
componentIdentifiers: componentIds);
|
||||
|
||||
Assert.Single(result.Links);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_UnknownFormat_ReturnsOtherType()
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize("some-custom-product-id");
|
||||
|
||||
Assert.Equal("product:some-custom-product-id", result.ProductKey);
|
||||
Assert.Equal(VexProductKeyType.Other, result.KeyType);
|
||||
Assert.Equal(VexProductScope.Unknown, result.Scope);
|
||||
Assert.Equal("other", result.Links[0].Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_NullInput_ThrowsArgumentException()
|
||||
{
|
||||
Assert.ThrowsAny<ArgumentException>(() => _canonicalizer.Canonicalize(null!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Canonicalize_EmptyInput_ThrowsArgumentException()
|
||||
{
|
||||
Assert.ThrowsAny<ArgumentException>(() => _canonicalizer.Canonicalize(""));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExtractPurlFromIdentifiers_WithPurl_ReturnsPurl()
|
||||
{
|
||||
var identifiers = new[]
|
||||
{
|
||||
"cpe:2.3:a:openssl:openssl:3.0.9:*:*:*:*:*:*:*",
|
||||
"pkg:rpm/redhat/openssl@3.0.9",
|
||||
"openssl-3.0.9"
|
||||
};
|
||||
|
||||
var purl = _canonicalizer.ExtractPurlFromIdentifiers(identifiers);
|
||||
|
||||
Assert.Equal("pkg:rpm/redhat/openssl@3.0.9", purl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExtractPurlFromIdentifiers_WithoutPurl_ReturnsNull()
|
||||
{
|
||||
var identifiers = new[]
|
||||
{
|
||||
"cpe:2.3:a:openssl:openssl:3.0.9:*:*:*:*:*:*:*",
|
||||
"openssl-3.0.9"
|
||||
};
|
||||
|
||||
var purl = _canonicalizer.ExtractPurlFromIdentifiers(identifiers);
|
||||
|
||||
Assert.Null(purl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExtractPurlFromIdentifiers_NullInput_ReturnsNull()
|
||||
{
|
||||
var purl = _canonicalizer.ExtractPurlFromIdentifiers(null);
|
||||
|
||||
Assert.Null(purl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OriginalKey_ReturnsOriginalIdentifier()
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize("pkg:npm/leftpad@1.0.0");
|
||||
|
||||
Assert.Equal("pkg:npm/leftpad@1.0.0", result.OriginalKey);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Purl_ReturnsPurlLink()
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(
|
||||
originalKey: "openssl",
|
||||
purl: "pkg:rpm/redhat/openssl@3.0.9");
|
||||
|
||||
Assert.Equal("pkg:rpm/redhat/openssl@3.0.9", result.Purl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Cpe_ReturnsCpeLink()
|
||||
{
|
||||
var result = _canonicalizer.Canonicalize(
|
||||
originalKey: "openssl",
|
||||
cpe: "cpe:2.3:a:openssl:openssl:3.0.9:*:*:*:*:*:*:*");
|
||||
|
||||
Assert.Equal("cpe:2.3:a:openssl:openssl:3.0.9:*:*:*:*:*:*:*", result.Cpe);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../__Libraries/StellaOps.Excititor.Core/StellaOps.Excititor.Core.csproj" />
|
||||
<ProjectReference Include="../../__Libraries/StellaOps.Excititor.Attestation/StellaOps.Excititor.Attestation.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" />
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.Core.UnitTests;
|
||||
|
||||
public class TimelineEventTests
|
||||
{
|
||||
[Fact]
|
||||
public void Constructor_NormalizesFields_AndPreservesValues()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var attributes = ImmutableDictionary<string, string>.Empty
|
||||
.Add("key1", "value1")
|
||||
.Add("key2", "value2");
|
||||
|
||||
var evt = new TimelineEvent(
|
||||
eventId: " evt-001 ",
|
||||
tenant: " TENANT-A ",
|
||||
providerId: " provider-x ",
|
||||
streamId: " csaf ",
|
||||
eventType: " vex.observation.ingested ",
|
||||
traceId: " trace-abc-123 ",
|
||||
justificationSummary: " Component not present in runtime ",
|
||||
createdAt: now,
|
||||
evidenceHash: " sha256:deadbeef ",
|
||||
payloadHash: " sha256:cafebabe ",
|
||||
attributes: attributes);
|
||||
|
||||
Assert.Equal("evt-001", evt.EventId);
|
||||
Assert.Equal("tenant-a", evt.Tenant); // lowercase
|
||||
Assert.Equal("provider-x", evt.ProviderId);
|
||||
Assert.Equal("csaf", evt.StreamId);
|
||||
Assert.Equal("vex.observation.ingested", evt.EventType);
|
||||
Assert.Equal("trace-abc-123", evt.TraceId);
|
||||
Assert.Equal("Component not present in runtime", evt.JustificationSummary);
|
||||
Assert.Equal(now, evt.CreatedAt);
|
||||
Assert.Equal("sha256:deadbeef", evt.EvidenceHash);
|
||||
Assert.Equal("sha256:cafebabe", evt.PayloadHash);
|
||||
Assert.Equal(2, evt.Attributes.Count);
|
||||
Assert.Equal("value1", evt.Attributes["key1"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ThrowsOnNullOrWhiteSpaceRequiredFields()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
Assert.Throws<ArgumentException>(() => new TimelineEvent(
|
||||
eventId: null!,
|
||||
tenant: "tenant",
|
||||
providerId: "provider",
|
||||
streamId: "stream",
|
||||
eventType: "type",
|
||||
traceId: "trace",
|
||||
justificationSummary: "summary",
|
||||
createdAt: now));
|
||||
|
||||
Assert.Throws<ArgumentException>(() => new TimelineEvent(
|
||||
eventId: " ",
|
||||
tenant: "tenant",
|
||||
providerId: "provider",
|
||||
streamId: "stream",
|
||||
eventType: "type",
|
||||
traceId: "trace",
|
||||
justificationSummary: "summary",
|
||||
createdAt: now));
|
||||
|
||||
Assert.Throws<ArgumentException>(() => new TimelineEvent(
|
||||
eventId: "evt-001",
|
||||
tenant: null!,
|
||||
providerId: "provider",
|
||||
streamId: "stream",
|
||||
eventType: "type",
|
||||
traceId: "trace",
|
||||
justificationSummary: "summary",
|
||||
createdAt: now));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_HandlesNullOptionalFields()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
var evt = new TimelineEvent(
|
||||
eventId: "evt-001",
|
||||
tenant: "tenant-a",
|
||||
providerId: "provider-x",
|
||||
streamId: "csaf",
|
||||
eventType: "vex.observation.ingested",
|
||||
traceId: "trace-abc-123",
|
||||
justificationSummary: null!,
|
||||
createdAt: now,
|
||||
evidenceHash: null,
|
||||
payloadHash: null,
|
||||
attributes: null);
|
||||
|
||||
Assert.Equal(string.Empty, evt.JustificationSummary);
|
||||
Assert.Null(evt.EvidenceHash);
|
||||
Assert.Null(evt.PayloadHash);
|
||||
Assert.Empty(evt.Attributes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_FiltersNullAttributeKeysAndValues()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var attributes = ImmutableDictionary<string, string>.Empty
|
||||
.Add("valid-key", "valid-value")
|
||||
.Add(" ", "bad-key")
|
||||
.Add("null-value", null!);
|
||||
|
||||
var evt = new TimelineEvent(
|
||||
eventId: "evt-001",
|
||||
tenant: "tenant-a",
|
||||
providerId: "provider-x",
|
||||
streamId: "csaf",
|
||||
eventType: "vex.observation.ingested",
|
||||
traceId: "trace-abc-123",
|
||||
justificationSummary: "summary",
|
||||
createdAt: now,
|
||||
attributes: attributes);
|
||||
|
||||
// Only valid key-value pair should remain
|
||||
Assert.Single(evt.Attributes);
|
||||
Assert.True(evt.Attributes.ContainsKey("valid-key"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EventTypes_Constants_AreCorrect()
|
||||
{
|
||||
Assert.Equal("vex.observation.ingested", VexTimelineEventTypes.ObservationIngested);
|
||||
Assert.Equal("vex.observation.updated", VexTimelineEventTypes.ObservationUpdated);
|
||||
Assert.Equal("vex.observation.superseded", VexTimelineEventTypes.ObservationSuperseded);
|
||||
Assert.Equal("vex.linkset.created", VexTimelineEventTypes.LinksetCreated);
|
||||
Assert.Equal("vex.linkset.updated", VexTimelineEventTypes.LinksetUpdated);
|
||||
Assert.Equal("vex.linkset.conflict_detected", VexTimelineEventTypes.LinksetConflictDetected);
|
||||
Assert.Equal("vex.linkset.conflict_resolved", VexTimelineEventTypes.LinksetConflictResolved);
|
||||
Assert.Equal("vex.evidence.sealed", VexTimelineEventTypes.EvidenceSealed);
|
||||
Assert.Equal("vex.attestation.attached", VexTimelineEventTypes.AttestationAttached);
|
||||
Assert.Equal("vex.attestation.verified", VexTimelineEventTypes.AttestationVerified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AttributeKeys_Constants_AreCorrect()
|
||||
{
|
||||
Assert.Equal("observation_id", VexTimelineEventAttributes.ObservationId);
|
||||
Assert.Equal("linkset_id", VexTimelineEventAttributes.LinksetId);
|
||||
Assert.Equal("vulnerability_id", VexTimelineEventAttributes.VulnerabilityId);
|
||||
Assert.Equal("product_key", VexTimelineEventAttributes.ProductKey);
|
||||
Assert.Equal("status", VexTimelineEventAttributes.Status);
|
||||
Assert.Equal("conflict_type", VexTimelineEventAttributes.ConflictType);
|
||||
Assert.Equal("attestation_id", VexTimelineEventAttributes.AttestationId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using StellaOps.Excititor.Attestation.Evidence;
|
||||
using StellaOps.Excititor.Attestation.Signing;
|
||||
using StellaOps.Excititor.Core.Evidence;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.Core.UnitTests;
|
||||
|
||||
public class VexEvidenceAttestorTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task AttestManifestAsync_CreatesValidAttestation()
|
||||
{
|
||||
var signer = new FakeSigner();
|
||||
var attestor = new VexEvidenceAttestor(signer, NullLogger<VexEvidenceAttestor>.Instance);
|
||||
|
||||
var item = new VexEvidenceSnapshotItem(
|
||||
"obs-001",
|
||||
"provider-a",
|
||||
"sha256:0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"linkset-1");
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test-tenant",
|
||||
manifestId: "locker:excititor:test-tenant:2025-11-27:0001",
|
||||
createdAt: DateTimeOffset.Parse("2025-11-27T10:00:00Z"),
|
||||
items: new[] { item });
|
||||
|
||||
var result = await attestor.AttestManifestAsync(manifest);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotNull(result.SignedManifest);
|
||||
Assert.NotNull(result.DsseEnvelopeJson);
|
||||
Assert.StartsWith("sha256:", result.DsseEnvelopeHash);
|
||||
Assert.StartsWith("attest:evidence:test-tenant:", result.AttestationId);
|
||||
Assert.NotNull(result.SignedManifest.Signature);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AttestManifestAsync_EnvelopeContainsCorrectPayload()
|
||||
{
|
||||
var signer = new FakeSigner();
|
||||
var attestor = new VexEvidenceAttestor(signer, NullLogger<VexEvidenceAttestor>.Instance);
|
||||
|
||||
var item = new VexEvidenceSnapshotItem(
|
||||
"obs-001",
|
||||
"provider-a",
|
||||
"sha256:abc123",
|
||||
"linkset-1");
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test-tenant",
|
||||
manifestId: "test-manifest",
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
items: new[] { item });
|
||||
|
||||
var result = await attestor.AttestManifestAsync(manifest);
|
||||
|
||||
var envelope = JsonSerializer.Deserialize<JsonObject>(result.DsseEnvelopeJson);
|
||||
Assert.NotNull(envelope);
|
||||
Assert.Equal("application/vnd.in-toto+json", envelope["payloadType"]?.GetValue<string>());
|
||||
|
||||
var payload = Convert.FromBase64String(envelope["payload"]?.GetValue<string>() ?? "");
|
||||
var statement = JsonSerializer.Deserialize<JsonObject>(payload);
|
||||
Assert.NotNull(statement);
|
||||
Assert.Equal(VexEvidenceInTotoStatement.InTotoStatementType, statement["_type"]?.GetValue<string>());
|
||||
Assert.Equal(VexEvidenceInTotoStatement.EvidenceLockerPredicateType, statement["predicateType"]?.GetValue<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyAttestationAsync_ReturnsValidForCorrectAttestation()
|
||||
{
|
||||
var signer = new FakeSigner();
|
||||
var attestor = new VexEvidenceAttestor(signer, NullLogger<VexEvidenceAttestor>.Instance);
|
||||
|
||||
var item = new VexEvidenceSnapshotItem(
|
||||
"obs-001",
|
||||
"provider-a",
|
||||
"sha256:abc123",
|
||||
"linkset-1");
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test-tenant",
|
||||
manifestId: "test-manifest",
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
items: new[] { item });
|
||||
|
||||
var attestation = await attestor.AttestManifestAsync(manifest);
|
||||
var verification = await attestor.VerifyAttestationAsync(manifest, attestation.DsseEnvelopeJson);
|
||||
|
||||
Assert.True(verification.IsValid);
|
||||
Assert.Null(verification.FailureReason);
|
||||
Assert.True(verification.Diagnostics.ContainsKey("envelope_hash"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyAttestationAsync_ReturnsInvalidForWrongManifest()
|
||||
{
|
||||
var signer = new FakeSigner();
|
||||
var attestor = new VexEvidenceAttestor(signer, NullLogger<VexEvidenceAttestor>.Instance);
|
||||
|
||||
var item = new VexEvidenceSnapshotItem(
|
||||
"obs-001",
|
||||
"provider-a",
|
||||
"sha256:abc123",
|
||||
"linkset-1");
|
||||
var manifest1 = new VexLockerManifest(
|
||||
tenant: "test-tenant",
|
||||
manifestId: "manifest-1",
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
items: new[] { item });
|
||||
|
||||
var manifest2 = new VexLockerManifest(
|
||||
tenant: "test-tenant",
|
||||
manifestId: "manifest-2",
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
items: new[] { item });
|
||||
|
||||
var attestation = await attestor.AttestManifestAsync(manifest1);
|
||||
var verification = await attestor.VerifyAttestationAsync(manifest2, attestation.DsseEnvelopeJson);
|
||||
|
||||
Assert.False(verification.IsValid);
|
||||
Assert.Contains("Manifest ID mismatch", verification.FailureReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyAttestationAsync_ReturnsInvalidForInvalidJson()
|
||||
{
|
||||
var signer = new FakeSigner();
|
||||
var attestor = new VexEvidenceAttestor(signer, NullLogger<VexEvidenceAttestor>.Instance);
|
||||
|
||||
var item = new VexEvidenceSnapshotItem(
|
||||
"obs-001",
|
||||
"provider-a",
|
||||
"sha256:abc123",
|
||||
"linkset-1");
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test-tenant",
|
||||
manifestId: "test-manifest",
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
items: new[] { item });
|
||||
|
||||
var verification = await attestor.VerifyAttestationAsync(manifest, "not valid json");
|
||||
|
||||
Assert.False(verification.IsValid);
|
||||
Assert.Contains("JSON parse error", verification.FailureReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyAttestationAsync_ReturnsInvalidForEmptyEnvelope()
|
||||
{
|
||||
var signer = new FakeSigner();
|
||||
var attestor = new VexEvidenceAttestor(signer, NullLogger<VexEvidenceAttestor>.Instance);
|
||||
|
||||
var item = new VexEvidenceSnapshotItem(
|
||||
"obs-001",
|
||||
"provider-a",
|
||||
"sha256:abc123",
|
||||
"linkset-1");
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test-tenant",
|
||||
manifestId: "test-manifest",
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
items: new[] { item });
|
||||
|
||||
var verification = await attestor.VerifyAttestationAsync(manifest, "");
|
||||
|
||||
Assert.False(verification.IsValid);
|
||||
Assert.Equal("DSSE envelope is required.", verification.FailureReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexEvidenceAttestationPredicate_FromManifest_CapturesAllFields()
|
||||
{
|
||||
var item = new VexEvidenceSnapshotItem(
|
||||
"obs-001",
|
||||
"provider-a",
|
||||
"sha256:abc123",
|
||||
"linkset-1");
|
||||
var metadata = ImmutableDictionary<string, string>.Empty.Add("sealed", "true");
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test-tenant",
|
||||
manifestId: "test-manifest",
|
||||
createdAt: DateTimeOffset.Parse("2025-11-27T10:00:00Z"),
|
||||
items: new[] { item },
|
||||
metadata: metadata);
|
||||
|
||||
var predicate = VexEvidenceAttestationPredicate.FromManifest(manifest);
|
||||
|
||||
Assert.Equal("test-manifest", predicate.ManifestId);
|
||||
Assert.Equal("test-tenant", predicate.Tenant);
|
||||
Assert.Equal(manifest.MerkleRoot, predicate.MerkleRoot);
|
||||
Assert.Equal(1, predicate.ItemCount);
|
||||
Assert.Equal("true", predicate.Metadata["sealed"]);
|
||||
}
|
||||
|
||||
private sealed class FakeSigner : IVexSigner
|
||||
{
|
||||
public ValueTask<VexSignedPayload> SignAsync(ReadOnlyMemory<byte> payload, CancellationToken cancellationToken)
|
||||
{
|
||||
var signature = Convert.ToBase64String(payload.Span.ToArray());
|
||||
return ValueTask.FromResult(new VexSignedPayload(signature, "fake-key-001"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Text.Json.Nodes;
|
||||
using StellaOps.Excititor.Core.Evidence;
|
||||
using StellaOps.Excititor.Core.Observations;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.Core.UnitTests;
|
||||
|
||||
public class VexEvidenceLockerTests
|
||||
{
|
||||
[Fact]
|
||||
public void VexEvidenceSnapshotItem_NormalizesFields()
|
||||
{
|
||||
var item = new VexEvidenceSnapshotItem(
|
||||
observationId: " obs-001 ",
|
||||
providerId: " PROVIDER-A ",
|
||||
contentHash: " sha256:abc123 ",
|
||||
linksetId: " CVE-2024-0001:pkg:npm/lodash ");
|
||||
|
||||
Assert.Equal("obs-001", item.ObservationId);
|
||||
Assert.Equal("provider-a", item.ProviderId);
|
||||
Assert.Equal("sha256:abc123", item.ContentHash);
|
||||
Assert.Equal("CVE-2024-0001:pkg:npm/lodash", item.LinksetId);
|
||||
Assert.Null(item.DsseEnvelopeHash);
|
||||
Assert.Equal("ingest", item.Provenance.Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexEvidenceProvenance_CreatesCorrectProvenance()
|
||||
{
|
||||
var provenance = new VexEvidenceProvenance("mirror", 5, "sha256:manifest123");
|
||||
|
||||
Assert.Equal("mirror", provenance.Source);
|
||||
Assert.Equal(5, provenance.MirrorGeneration);
|
||||
Assert.Equal("sha256:manifest123", provenance.ExportCenterManifest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexLockerManifest_SortsItemsDeterministically()
|
||||
{
|
||||
var item1 = new VexEvidenceSnapshotItem("obs-002", "provider-b", "sha256:bbb", "linkset-1");
|
||||
var item2 = new VexEvidenceSnapshotItem("obs-001", "provider-a", "sha256:aaa", "linkset-1");
|
||||
var item3 = new VexEvidenceSnapshotItem("obs-001", "provider-b", "sha256:ccc", "linkset-2");
|
||||
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test-tenant",
|
||||
manifestId: "locker:excititor:test:2025-11-27:0001",
|
||||
createdAt: DateTimeOffset.Parse("2025-11-27T10:00:00Z"),
|
||||
items: new[] { item1, item2, item3 });
|
||||
|
||||
// Should be sorted by observationId, then providerId
|
||||
Assert.Equal(3, manifest.Items.Length);
|
||||
Assert.Equal("obs-001", manifest.Items[0].ObservationId);
|
||||
Assert.Equal("provider-a", manifest.Items[0].ProviderId);
|
||||
Assert.Equal("obs-001", manifest.Items[1].ObservationId);
|
||||
Assert.Equal("provider-b", manifest.Items[1].ProviderId);
|
||||
Assert.Equal("obs-002", manifest.Items[2].ObservationId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexLockerManifest_ComputesMerkleRoot()
|
||||
{
|
||||
var item1 = new VexEvidenceSnapshotItem("obs-001", "provider-a", "sha256:0000000000000000000000000000000000000000000000000000000000000001", "linkset-1");
|
||||
var item2 = new VexEvidenceSnapshotItem("obs-002", "provider-a", "sha256:0000000000000000000000000000000000000000000000000000000000000002", "linkset-1");
|
||||
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test",
|
||||
manifestId: "test-manifest",
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
items: new[] { item1, item2 });
|
||||
|
||||
Assert.StartsWith("sha256:", manifest.MerkleRoot);
|
||||
Assert.Equal(71, manifest.MerkleRoot.Length); // "sha256:" + 64 hex chars
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexLockerManifest_CreateManifestId_GeneratesCorrectFormat()
|
||||
{
|
||||
var id = VexLockerManifest.CreateManifestId("TestTenant", DateTimeOffset.Parse("2025-11-27T15:30:00Z"), 42);
|
||||
|
||||
Assert.Equal("locker:excititor:testtenant:2025-11-27:0042", id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexLockerManifest_WithSignature_PreservesData()
|
||||
{
|
||||
var item = new VexEvidenceSnapshotItem("obs-001", "provider-a", "sha256:abc123", "linkset-1");
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test",
|
||||
manifestId: "test-manifest",
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
items: new[] { item });
|
||||
|
||||
var signed = manifest.WithSignature("dsse-signature-base64");
|
||||
|
||||
Assert.Null(manifest.Signature);
|
||||
Assert.Equal("dsse-signature-base64", signed.Signature);
|
||||
Assert.Equal(manifest.MerkleRoot, signed.MerkleRoot);
|
||||
Assert.Equal(manifest.Items.Length, signed.Items.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexEvidenceLockerService_CreateSnapshotItem_FromObservation()
|
||||
{
|
||||
var observation = BuildTestObservation("obs-001", "provider-a", "sha256:content123");
|
||||
var service = new VexEvidenceLockerService();
|
||||
|
||||
var item = service.CreateSnapshotItem(observation, "linkset-001");
|
||||
|
||||
Assert.Equal("obs-001", item.ObservationId);
|
||||
Assert.Equal("provider-a", item.ProviderId);
|
||||
Assert.Equal("sha256:content123", item.ContentHash);
|
||||
Assert.Equal("linkset-001", item.LinksetId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexEvidenceLockerService_BuildManifest_CreatesValidManifest()
|
||||
{
|
||||
var obs1 = BuildTestObservation("obs-001", "provider-a", "sha256:aaa");
|
||||
var obs2 = BuildTestObservation("obs-002", "provider-b", "sha256:bbb");
|
||||
var service = new VexEvidenceLockerService();
|
||||
|
||||
var manifest = service.BuildManifest(
|
||||
tenant: "test-tenant",
|
||||
observations: new[] { obs2, obs1 },
|
||||
linksetIdSelector: o => $"linkset:{o.ObservationId}",
|
||||
timestamp: DateTimeOffset.Parse("2025-11-27T10:00:00Z"),
|
||||
sequence: 1,
|
||||
isSealed: true);
|
||||
|
||||
Assert.Equal("test-tenant", manifest.Tenant);
|
||||
Assert.Equal("locker:excititor:test-tenant:2025-11-27:0001", manifest.ManifestId);
|
||||
Assert.Equal(2, manifest.Items.Length);
|
||||
Assert.Equal("obs-001", manifest.Items[0].ObservationId); // sorted
|
||||
Assert.Equal("true", manifest.Metadata["sealed"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexEvidenceLockerService_VerifyManifest_ReturnsTrueForValidManifest()
|
||||
{
|
||||
var item = new VexEvidenceSnapshotItem("obs-001", "provider-a", "sha256:0000000000000000000000000000000000000000000000000000000000000001", "linkset-1");
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test",
|
||||
manifestId: "test-manifest",
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
items: new[] { item });
|
||||
|
||||
var service = new VexEvidenceLockerService();
|
||||
Assert.True(service.VerifyManifest(manifest));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexLockerManifest_EmptyItems_ProducesEmptyMerkleRoot()
|
||||
{
|
||||
var manifest = new VexLockerManifest(
|
||||
tenant: "test",
|
||||
manifestId: "test-manifest",
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
items: Array.Empty<VexEvidenceSnapshotItem>());
|
||||
|
||||
Assert.StartsWith("sha256:", manifest.MerkleRoot);
|
||||
Assert.Empty(manifest.Items);
|
||||
}
|
||||
|
||||
private static VexObservation BuildTestObservation(string id, string provider, string contentHash)
|
||||
{
|
||||
var upstream = new VexObservationUpstream(
|
||||
upstreamId: $"upstream-{id}",
|
||||
documentVersion: "1",
|
||||
fetchedAt: DateTimeOffset.UtcNow,
|
||||
receivedAt: DateTimeOffset.UtcNow,
|
||||
contentHash: contentHash,
|
||||
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: Array.Empty<string>(),
|
||||
purls: Array.Empty<string>(),
|
||||
cpes: Array.Empty<string>(),
|
||||
references: Array.Empty<VexObservationReference>());
|
||||
|
||||
return new VexObservation(
|
||||
observationId: id,
|
||||
tenant: "test",
|
||||
providerId: provider,
|
||||
streamId: "ingest",
|
||||
upstream: upstream,
|
||||
statements: ImmutableArray<VexObservationStatement>.Empty,
|
||||
content: content,
|
||||
linkset: linkset,
|
||||
createdAt: DateTimeOffset.UtcNow);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using EphemeralMongo;
|
||||
using MongoRunner = EphemeralMongo.MongoRunner;
|
||||
using MongoRunnerOptions = EphemeralMongo.MongoRunnerOptions;
|
||||
using StellaOps.Excititor.Attestation.Signing;
|
||||
using StellaOps.Excititor.Connectors.Abstractions;
|
||||
using StellaOps.Excititor.Policy;
|
||||
using StellaOps.Excititor.Core;
|
||||
|
||||
namespace StellaOps.Excititor.WebService.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for OpenAPI discovery endpoints (WEB-OAS-61-001).
|
||||
/// Validates /.well-known/openapi and /openapi/excititor.json endpoints.
|
||||
/// </summary>
|
||||
public sealed class OpenApiDiscoveryEndpointTests : IDisposable
|
||||
{
|
||||
private readonly TestWebApplicationFactory _factory;
|
||||
private readonly IMongoRunner _runner;
|
||||
|
||||
public OpenApiDiscoveryEndpointTests()
|
||||
{
|
||||
_runner = MongoRunner.Run(new MongoRunnerOptions { UseSingleNodeReplicaSet = true });
|
||||
_factory = new TestWebApplicationFactory(
|
||||
configureConfiguration: config =>
|
||||
{
|
||||
var rootPath = Path.Combine(Path.GetTempPath(), "excititor-openapi-tests");
|
||||
Directory.CreateDirectory(rootPath);
|
||||
var settings = new Dictionary<string, string?>
|
||||
{
|
||||
["Excititor:Storage:Mongo:ConnectionString"] = _runner.ConnectionString,
|
||||
["Excititor:Storage:Mongo:DatabaseName"] = "excititor-openapi-tests",
|
||||
["Excititor:Storage:Mongo:RawBucketName"] = "vex.raw",
|
||||
["Excititor:Storage:Mongo:GridFsInlineThresholdBytes"] = "256",
|
||||
["Excititor:Artifacts:FileSystem:RootPath"] = rootPath,
|
||||
};
|
||||
config.AddInMemoryCollection(settings!);
|
||||
},
|
||||
configureServices: services =>
|
||||
{
|
||||
TestServiceOverrides.Apply(services);
|
||||
services.AddSingleton<IVexSigner, FakeSigner>();
|
||||
services.AddSingleton<IVexPolicyEvaluator, FakePolicyEvaluator>();
|
||||
services.AddSingleton(new VexConnectorDescriptor("excititor:test", VexProviderKind.Distro, "Test Connector"));
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WellKnownOpenApi_ReturnsServiceMetadata()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.GetAsync("/.well-known/openapi");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
|
||||
Assert.Equal("excititor", root.GetProperty("service").GetString());
|
||||
Assert.Equal("3.1.0", root.GetProperty("specVersion").GetString());
|
||||
Assert.Equal("application/json", root.GetProperty("format").GetString());
|
||||
Assert.Equal("/openapi/excititor.json", root.GetProperty("url").GetString());
|
||||
Assert.Equal("#/components/schemas/Error", root.GetProperty("errorEnvelopeSchema").GetString());
|
||||
Assert.True(root.TryGetProperty("version", out _), "Response should include version");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenApiSpec_ReturnsValidOpenApi31Document()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.GetAsync("/openapi/excititor.json");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
|
||||
// Verify OpenAPI version
|
||||
Assert.Equal("3.1.0", root.GetProperty("openapi").GetString());
|
||||
|
||||
// Verify info object
|
||||
var info = root.GetProperty("info");
|
||||
Assert.Equal("StellaOps Excititor API", info.GetProperty("title").GetString());
|
||||
Assert.True(info.TryGetProperty("version", out _), "Info should include version");
|
||||
Assert.True(info.TryGetProperty("description", out _), "Info should include description");
|
||||
|
||||
// Verify paths exist
|
||||
Assert.True(root.TryGetProperty("paths", out var paths), "Spec should include paths");
|
||||
Assert.True(paths.TryGetProperty("/excititor/status", out _), "Paths should include /excititor/status");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenApiSpec_IncludesErrorSchemaComponent()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.GetAsync("/openapi/excititor.json");
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
|
||||
// Verify components/schemas/Error exists
|
||||
Assert.True(root.TryGetProperty("components", out var components), "Spec should include components");
|
||||
Assert.True(components.TryGetProperty("schemas", out var schemas), "Components should include schemas");
|
||||
Assert.True(schemas.TryGetProperty("Error", out var errorSchema), "Schemas should include Error");
|
||||
|
||||
// Verify Error schema structure
|
||||
Assert.Equal("object", errorSchema.GetProperty("type").GetString());
|
||||
Assert.True(errorSchema.TryGetProperty("properties", out var props), "Error schema should have properties");
|
||||
Assert.True(props.TryGetProperty("error", out _), "Error schema should have error property");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenApiSpec_IncludesTimelineEndpoint()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.GetAsync("/openapi/excititor.json");
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
|
||||
var paths = root.GetProperty("paths");
|
||||
Assert.True(paths.TryGetProperty("/obs/excititor/timeline", out var timelinePath),
|
||||
"Paths should include /obs/excititor/timeline");
|
||||
|
||||
// Verify it has a GET operation
|
||||
Assert.True(timelinePath.TryGetProperty("get", out var getOp), "Timeline path should have GET operation");
|
||||
Assert.True(getOp.TryGetProperty("summary", out _), "GET operation should have summary");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenApiSpec_IncludesLinkHeaderExample()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.GetAsync("/openapi/excititor.json");
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Verify the spec contains a Link header reference for OpenAPI describedby
|
||||
// JSON escapes quotes, so check for the essential parts
|
||||
Assert.Contains("/openapi/excititor.json", json);
|
||||
Assert.Contains("describedby", json);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WellKnownOpenApi_ContentTypeIsJson()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.GetAsync("/.well-known/openapi");
|
||||
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenApiSpec_ContentTypeIsJson()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.GetAsync("/openapi/excititor.json");
|
||||
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_factory.Dispose();
|
||||
_runner.Dispose();
|
||||
}
|
||||
|
||||
private sealed class FakeSigner : IVexSigner
|
||||
{
|
||||
public ValueTask<VexSignedPayload> SignAsync(ReadOnlyMemory<byte> payload, CancellationToken cancellationToken)
|
||||
=> ValueTask.FromResult(new VexSignedPayload("signature", "key"));
|
||||
}
|
||||
|
||||
private sealed class FakePolicyEvaluator : IVexPolicyEvaluator
|
||||
{
|
||||
public string Version => "test";
|
||||
|
||||
public VexPolicySnapshot Snapshot => VexPolicySnapshot.Default;
|
||||
|
||||
public double GetProviderWeight(VexProvider provider) => 1.0;
|
||||
|
||||
public bool IsClaimEligible(VexClaim claim, VexProvider provider, out string? rejectionReason)
|
||||
{
|
||||
rejectionReason = null;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,5 +40,6 @@
|
||||
<Compile Include="GraphStatusFactoryTests.cs" />
|
||||
<Compile Include="GraphTooltipFactoryTests.cs" />
|
||||
<Compile Include="AttestationVerifyEndpointTests.cs" />
|
||||
<Compile Include="OpenApiDiscoveryEndpointTests.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -16,7 +16,9 @@ using StellaOps.Aoc;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Core.Aoc;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.Core.Orchestration;
|
||||
using StellaOps.Excititor.Worker.Options;
|
||||
using StellaOps.Excititor.Worker.Orchestration;
|
||||
using StellaOps.Excititor.Worker.Scheduling;
|
||||
using StellaOps.Excititor.Worker.Signature;
|
||||
using StellaOps.Plugin;
|
||||
@@ -115,7 +117,8 @@ public sealed class DefaultVexProviderRunnerIntegrationTests : IAsyncLifetime
|
||||
storedCount.Should().Be(9); // documents before the failing digest persist
|
||||
|
||||
guard.FailDigest = null;
|
||||
time.Advance(TimeSpan.FromMinutes(10));
|
||||
// Advance past the quarantine duration (30 mins) since AOC guard failures are non-retryable
|
||||
time.Advance(TimeSpan.FromMinutes(35));
|
||||
await runner.RunAsync(schedule, CancellationToken.None);
|
||||
|
||||
var finalCount = await rawCollection.CountDocumentsAsync(FilterDefinition<BsonDocument>.Empty);
|
||||
@@ -177,12 +180,23 @@ public sealed class DefaultVexProviderRunnerIntegrationTests : IAsyncLifetime
|
||||
},
|
||||
};
|
||||
|
||||
var orchestratorOptions = Microsoft.Extensions.Options.Options.Create(new VexWorkerOrchestratorOptions { Enabled = false });
|
||||
var orchestratorClient = new NoopOrchestratorClient();
|
||||
var heartbeatService = new VexWorkerHeartbeatService(
|
||||
orchestratorClient,
|
||||
orchestratorOptions,
|
||||
timeProvider,
|
||||
NullLogger<VexWorkerHeartbeatService>.Instance);
|
||||
|
||||
return new DefaultVexProviderRunner(
|
||||
services,
|
||||
new PluginCatalog(),
|
||||
orchestratorClient,
|
||||
heartbeatService,
|
||||
NullLogger<DefaultVexProviderRunner>.Instance,
|
||||
timeProvider,
|
||||
Microsoft.Extensions.Options.Options.Create(options));
|
||||
Microsoft.Extensions.Options.Options.Create(options),
|
||||
orchestratorOptions);
|
||||
}
|
||||
|
||||
private static List<DocumentSpec> CreateDocumentSpecs(int count)
|
||||
@@ -330,6 +344,39 @@ public sealed class DefaultVexProviderRunnerIntegrationTests : IAsyncLifetime
|
||||
=> ValueTask.FromResult<VexSignatureMetadata?>(null);
|
||||
}
|
||||
|
||||
private sealed class NoopOrchestratorClient : IVexWorkerOrchestratorClient
|
||||
{
|
||||
public ValueTask<VexWorkerJobContext> StartJobAsync(string tenant, string connectorId, string? checkpoint, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult(new VexWorkerJobContext(tenant, connectorId, Guid.NewGuid(), checkpoint, DateTimeOffset.UtcNow));
|
||||
|
||||
public ValueTask SendHeartbeatAsync(VexWorkerJobContext context, VexWorkerHeartbeat heartbeat, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask RecordArtifactAsync(VexWorkerJobContext context, VexWorkerArtifact artifact, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask CompleteJobAsync(VexWorkerJobContext context, VexWorkerJobResult result, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask FailJobAsync(VexWorkerJobContext context, string errorCode, string? errorMessage, int? retryAfterSeconds, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask FailJobAsync(VexWorkerJobContext context, VexWorkerError error, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask<VexWorkerCommand?> GetPendingCommandAsync(VexWorkerJobContext context, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult<VexWorkerCommand?>(null);
|
||||
|
||||
public ValueTask AcknowledgeCommandAsync(VexWorkerJobContext context, long commandSequence, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask SaveCheckpointAsync(VexWorkerJobContext context, VexWorkerCheckpoint checkpoint, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask<VexWorkerCheckpoint?> LoadCheckpointAsync(string connectorId, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult<VexWorkerCheckpoint?>(null);
|
||||
}
|
||||
|
||||
private sealed class DirectSessionProvider : IVexMongoSessionProvider
|
||||
{
|
||||
private readonly IMongoClient _client;
|
||||
|
||||
@@ -19,13 +19,15 @@ using StellaOps.Excititor.Connectors.Abstractions;
|
||||
using StellaOps.Excititor.Core;
|
||||
using StellaOps.Excititor.Core.Aoc;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.Worker.Options;
|
||||
using StellaOps.Excititor.Worker.Scheduling;
|
||||
using StellaOps.Excititor.Worker.Signature;
|
||||
using StellaOps.Aoc;
|
||||
using Xunit;
|
||||
using System.Runtime.CompilerServices;
|
||||
using StellaOps.IssuerDirectory.Client;
|
||||
using StellaOps.Excititor.Core.Orchestration;
|
||||
using StellaOps.Excititor.Worker.Options;
|
||||
using StellaOps.Excititor.Worker.Orchestration;
|
||||
using StellaOps.Excititor.Worker.Scheduling;
|
||||
using StellaOps.Excititor.Worker.Signature;
|
||||
using StellaOps.Aoc;
|
||||
using Xunit;
|
||||
using System.Runtime.CompilerServices;
|
||||
using StellaOps.IssuerDirectory.Client;
|
||||
|
||||
namespace StellaOps.Excititor.Worker.Tests;
|
||||
|
||||
@@ -286,12 +288,12 @@ public sealed class DefaultVexProviderRunnerTests
|
||||
.Add("verification.issuer", "issuer-from-verifier")
|
||||
.Add("verification.keyId", "key-from-verifier");
|
||||
|
||||
var attestationVerifier = new StubAttestationVerifier(true, diagnostics);
|
||||
var signatureVerifier = new WorkerSignatureVerifier(
|
||||
NullLogger<WorkerSignatureVerifier>.Instance,
|
||||
attestationVerifier,
|
||||
time,
|
||||
TestIssuerDirectoryClient.Instance);
|
||||
var attestationVerifier = new StubAttestationVerifier(true, diagnostics);
|
||||
var signatureVerifier = new WorkerSignatureVerifier(
|
||||
NullLogger<WorkerSignatureVerifier>.Instance,
|
||||
attestationVerifier,
|
||||
time,
|
||||
TestIssuerDirectoryClient.Instance);
|
||||
|
||||
var connector = TestConnector.WithDocuments("excititor:test", document);
|
||||
var stateRepository = new InMemoryStateRepository();
|
||||
@@ -332,6 +334,45 @@ public sealed class DefaultVexProviderRunnerTests
|
||||
{
|
||||
var now = new DateTimeOffset(2025, 10, 21, 17, 0, 0, TimeSpan.Zero);
|
||||
var time = new FixedTimeProvider(now);
|
||||
// Use a network exception which is classified as retryable
|
||||
var connector = TestConnector.Failure("excititor:test", new System.Net.Http.HttpRequestException("network failure"));
|
||||
var stateRepository = new InMemoryStateRepository();
|
||||
stateRepository.Save(new VexConnectorState(
|
||||
"excititor:test",
|
||||
LastUpdated: now.AddDays(-2),
|
||||
DocumentDigests: ImmutableArray<string>.Empty,
|
||||
ResumeTokens: ImmutableDictionary<string, string>.Empty,
|
||||
LastSuccessAt: now.AddDays(-1),
|
||||
FailureCount: 1,
|
||||
NextEligibleRun: null,
|
||||
LastFailureReason: null));
|
||||
|
||||
var services = CreateServiceProvider(connector, stateRepository);
|
||||
var runner = CreateRunner(services, time, options =>
|
||||
{
|
||||
options.Retry.BaseDelay = TimeSpan.FromMinutes(5);
|
||||
options.Retry.MaxDelay = TimeSpan.FromMinutes(60);
|
||||
options.Retry.FailureThreshold = 3;
|
||||
options.Retry.QuarantineDuration = TimeSpan.FromHours(12);
|
||||
options.Retry.JitterRatio = 0;
|
||||
});
|
||||
|
||||
await Assert.ThrowsAsync<System.Net.Http.HttpRequestException>(async () => await runner.RunAsync(new VexWorkerSchedule(connector.Id, TimeSpan.FromMinutes(10), TimeSpan.Zero, EmptySettings), CancellationToken.None).AsTask());
|
||||
|
||||
var state = stateRepository.Get("excititor:test");
|
||||
state.Should().NotBeNull();
|
||||
state!.FailureCount.Should().Be(2);
|
||||
state.LastFailureReason.Should().Be("network failure");
|
||||
// Exponential backoff: 5 mins * 2^(2-1) = 10 mins
|
||||
state.NextEligibleRun.Should().Be(now + TimeSpan.FromMinutes(10));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_NonRetryableFailure_AppliesQuarantine()
|
||||
{
|
||||
var now = new DateTimeOffset(2025, 10, 21, 17, 0, 0, TimeSpan.Zero);
|
||||
var time = new FixedTimeProvider(now);
|
||||
// InvalidOperationException is classified as non-retryable
|
||||
var connector = TestConnector.Failure("excititor:test", new InvalidOperationException("boom"));
|
||||
var stateRepository = new InMemoryStateRepository();
|
||||
stateRepository.Save(new VexConnectorState(
|
||||
@@ -360,7 +401,8 @@ public sealed class DefaultVexProviderRunnerTests
|
||||
state.Should().NotBeNull();
|
||||
state!.FailureCount.Should().Be(2);
|
||||
state.LastFailureReason.Should().Be("boom");
|
||||
state.NextEligibleRun.Should().Be(now + TimeSpan.FromMinutes(10));
|
||||
// Non-retryable errors apply quarantine immediately
|
||||
state.NextEligibleRun.Should().Be(now + TimeSpan.FromHours(12));
|
||||
}
|
||||
|
||||
private static ServiceProvider CreateServiceProvider(
|
||||
@@ -390,12 +432,22 @@ public sealed class DefaultVexProviderRunnerTests
|
||||
{
|
||||
var options = new VexWorkerOptions();
|
||||
configure(options);
|
||||
var orchestratorOptions = Microsoft.Extensions.Options.Options.Create(new VexWorkerOrchestratorOptions { Enabled = false });
|
||||
var orchestratorClient = new NoopOrchestratorClient();
|
||||
var heartbeatService = new VexWorkerHeartbeatService(
|
||||
orchestratorClient,
|
||||
orchestratorOptions,
|
||||
timeProvider,
|
||||
NullLogger<VexWorkerHeartbeatService>.Instance);
|
||||
return new DefaultVexProviderRunner(
|
||||
serviceProvider,
|
||||
new PluginCatalog(),
|
||||
orchestratorClient,
|
||||
heartbeatService,
|
||||
NullLogger<DefaultVexProviderRunner>.Instance,
|
||||
timeProvider,
|
||||
Microsoft.Extensions.Options.Options.Create(options));
|
||||
Microsoft.Extensions.Options.Options.Create(options),
|
||||
orchestratorOptions);
|
||||
}
|
||||
|
||||
private sealed class FixedTimeProvider : TimeProvider
|
||||
@@ -467,64 +519,97 @@ public sealed class DefaultVexProviderRunnerTests
|
||||
=> ValueTask.FromResult(new VexClaimBatch(document, ImmutableArray<VexClaim>.Empty, ImmutableDictionary<string, string>.Empty));
|
||||
}
|
||||
|
||||
private sealed class StubNormalizerRouter : IVexNormalizerRouter
|
||||
{
|
||||
private readonly ImmutableArray<VexClaim> _claims;
|
||||
|
||||
public StubNormalizerRouter(IEnumerable<VexClaim> claims)
|
||||
{
|
||||
_claims = claims.ToImmutableArray();
|
||||
}
|
||||
|
||||
public int CallCount { get; private set; }
|
||||
|
||||
public ValueTask<VexClaimBatch> NormalizeAsync(VexRawDocument document, CancellationToken cancellationToken)
|
||||
{
|
||||
CallCount++;
|
||||
return ValueTask.FromResult(new VexClaimBatch(document, _claims, ImmutableDictionary<string, string>.Empty));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TestIssuerDirectoryClient : IIssuerDirectoryClient
|
||||
{
|
||||
public static TestIssuerDirectoryClient Instance { get; } = new();
|
||||
|
||||
private static readonly IssuerTrustResponseModel DefaultTrust = new(null, null, 1m);
|
||||
|
||||
public ValueTask<IReadOnlyList<IssuerKeyModel>> GetIssuerKeysAsync(
|
||||
string tenantId,
|
||||
string issuerId,
|
||||
bool includeGlobal,
|
||||
CancellationToken cancellationToken)
|
||||
=> ValueTask.FromResult<IReadOnlyList<IssuerKeyModel>>(Array.Empty<IssuerKeyModel>());
|
||||
|
||||
public ValueTask<IssuerTrustResponseModel> GetIssuerTrustAsync(
|
||||
string tenantId,
|
||||
string issuerId,
|
||||
bool includeGlobal,
|
||||
CancellationToken cancellationToken)
|
||||
=> ValueTask.FromResult(DefaultTrust);
|
||||
|
||||
public ValueTask<IssuerTrustResponseModel> SetIssuerTrustAsync(
|
||||
string tenantId,
|
||||
string issuerId,
|
||||
decimal weight,
|
||||
string? reason,
|
||||
CancellationToken cancellationToken)
|
||||
=> ValueTask.FromResult(DefaultTrust);
|
||||
|
||||
public ValueTask DeleteIssuerTrustAsync(
|
||||
string tenantId,
|
||||
string issuerId,
|
||||
string? reason,
|
||||
CancellationToken cancellationToken)
|
||||
=> ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private sealed class NoopSignatureVerifier : IVexSignatureVerifier
|
||||
{
|
||||
public ValueTask<VexSignatureMetadata?> VerifyAsync(VexRawDocument document, CancellationToken cancellationToken)
|
||||
=> ValueTask.FromResult<VexSignatureMetadata?>(null);
|
||||
private sealed class StubNormalizerRouter : IVexNormalizerRouter
|
||||
{
|
||||
private readonly ImmutableArray<VexClaim> _claims;
|
||||
|
||||
public StubNormalizerRouter(IEnumerable<VexClaim> claims)
|
||||
{
|
||||
_claims = claims.ToImmutableArray();
|
||||
}
|
||||
|
||||
public int CallCount { get; private set; }
|
||||
|
||||
public ValueTask<VexClaimBatch> NormalizeAsync(VexRawDocument document, CancellationToken cancellationToken)
|
||||
{
|
||||
CallCount++;
|
||||
return ValueTask.FromResult(new VexClaimBatch(document, _claims, ImmutableDictionary<string, string>.Empty));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TestIssuerDirectoryClient : IIssuerDirectoryClient
|
||||
{
|
||||
public static TestIssuerDirectoryClient Instance { get; } = new();
|
||||
|
||||
private static readonly IssuerTrustResponseModel DefaultTrust = new(null, null, 1m);
|
||||
|
||||
public ValueTask<IReadOnlyList<IssuerKeyModel>> GetIssuerKeysAsync(
|
||||
string tenantId,
|
||||
string issuerId,
|
||||
bool includeGlobal,
|
||||
CancellationToken cancellationToken)
|
||||
=> ValueTask.FromResult<IReadOnlyList<IssuerKeyModel>>(Array.Empty<IssuerKeyModel>());
|
||||
|
||||
public ValueTask<IssuerTrustResponseModel> GetIssuerTrustAsync(
|
||||
string tenantId,
|
||||
string issuerId,
|
||||
bool includeGlobal,
|
||||
CancellationToken cancellationToken)
|
||||
=> ValueTask.FromResult(DefaultTrust);
|
||||
|
||||
public ValueTask<IssuerTrustResponseModel> SetIssuerTrustAsync(
|
||||
string tenantId,
|
||||
string issuerId,
|
||||
decimal weight,
|
||||
string? reason,
|
||||
CancellationToken cancellationToken)
|
||||
=> ValueTask.FromResult(DefaultTrust);
|
||||
|
||||
public ValueTask DeleteIssuerTrustAsync(
|
||||
string tenantId,
|
||||
string issuerId,
|
||||
string? reason,
|
||||
CancellationToken cancellationToken)
|
||||
=> ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private sealed class NoopSignatureVerifier : IVexSignatureVerifier
|
||||
{
|
||||
public ValueTask<VexSignatureMetadata?> VerifyAsync(VexRawDocument document, CancellationToken cancellationToken)
|
||||
=> ValueTask.FromResult<VexSignatureMetadata?>(null);
|
||||
}
|
||||
|
||||
private sealed class NoopOrchestratorClient : IVexWorkerOrchestratorClient
|
||||
{
|
||||
public ValueTask<VexWorkerJobContext> StartJobAsync(string tenant, string connectorId, string? checkpoint, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult(new VexWorkerJobContext(tenant, connectorId, Guid.NewGuid(), checkpoint, DateTimeOffset.UtcNow));
|
||||
|
||||
public ValueTask SendHeartbeatAsync(VexWorkerJobContext context, VexWorkerHeartbeat heartbeat, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask RecordArtifactAsync(VexWorkerJobContext context, VexWorkerArtifact artifact, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask CompleteJobAsync(VexWorkerJobContext context, VexWorkerJobResult result, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask FailJobAsync(VexWorkerJobContext context, string errorCode, string? errorMessage, int? retryAfterSeconds, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask FailJobAsync(VexWorkerJobContext context, VexWorkerError error, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask<VexWorkerCommand?> GetPendingCommandAsync(VexWorkerJobContext context, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult<VexWorkerCommand?>(null);
|
||||
|
||||
public ValueTask AcknowledgeCommandAsync(VexWorkerJobContext context, long commandSequence, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask SaveCheckpointAsync(VexWorkerJobContext context, VexWorkerCheckpoint checkpoint, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.CompletedTask;
|
||||
|
||||
public ValueTask<VexWorkerCheckpoint?> LoadCheckpointAsync(string connectorId, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult<VexWorkerCheckpoint?>(null);
|
||||
}
|
||||
|
||||
private sealed class InMemoryStateRepository : IVexConnectorStateRepository
|
||||
@@ -545,6 +630,9 @@ public sealed class DefaultVexProviderRunnerTests
|
||||
Save(state);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
public ValueTask<IReadOnlyCollection<VexConnectorState>> ListAsync(CancellationToken cancellationToken, IClientSessionHandle? session = null)
|
||||
=> ValueTask.FromResult<IReadOnlyCollection<VexConnectorState>>(_states.Values.ToList());
|
||||
}
|
||||
|
||||
private sealed class TestConnector : IVexConnector
|
||||
@@ -670,25 +758,25 @@ public sealed class DefaultVexProviderRunnerTests
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class StubAttestationVerifier : IVexAttestationVerifier
|
||||
{
|
||||
private readonly bool _isValid;
|
||||
private readonly VexAttestationDiagnostics _diagnostics;
|
||||
|
||||
public StubAttestationVerifier(bool isValid, ImmutableDictionary<string, string> diagnostics)
|
||||
{
|
||||
_isValid = isValid;
|
||||
_diagnostics = VexAttestationDiagnostics.FromBuilder(diagnostics.ToBuilder());
|
||||
}
|
||||
|
||||
public int Invocations { get; private set; }
|
||||
|
||||
public ValueTask<VexAttestationVerification> VerifyAsync(VexAttestationVerificationRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Invocations++;
|
||||
return ValueTask.FromResult(new VexAttestationVerification(_isValid, _diagnostics));
|
||||
}
|
||||
}
|
||||
private sealed class StubAttestationVerifier : IVexAttestationVerifier
|
||||
{
|
||||
private readonly bool _isValid;
|
||||
private readonly VexAttestationDiagnostics _diagnostics;
|
||||
|
||||
public StubAttestationVerifier(bool isValid, ImmutableDictionary<string, string> diagnostics)
|
||||
{
|
||||
_isValid = isValid;
|
||||
_diagnostics = VexAttestationDiagnostics.FromBuilder(diagnostics.ToBuilder());
|
||||
}
|
||||
|
||||
public int Invocations { get; private set; }
|
||||
|
||||
public ValueTask<VexAttestationVerification> VerifyAsync(VexAttestationVerificationRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Invocations++;
|
||||
return ValueTask.FromResult(new VexAttestationVerification(_isValid, _diagnostics));
|
||||
}
|
||||
}
|
||||
|
||||
private static VexRawDocument CreateAttestationRawDocument(DateTimeOffset observedAt)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Excititor.Core.Orchestration;
|
||||
using StellaOps.Excititor.Storage.Mongo;
|
||||
using StellaOps.Excititor.Worker.Options;
|
||||
using StellaOps.Excititor.Worker.Orchestration;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Excititor.Worker.Tests.Orchestration;
|
||||
|
||||
public class VexWorkerOrchestratorClientTests
|
||||
{
|
||||
private readonly InMemoryConnectorStateRepository _stateRepository = new();
|
||||
private readonly FakeTimeProvider _timeProvider = new();
|
||||
private readonly IOptions<VexWorkerOrchestratorOptions> _options = Microsoft.Extensions.Options.Options.Create(new VexWorkerOrchestratorOptions
|
||||
{
|
||||
Enabled = true,
|
||||
DefaultTenant = "test-tenant"
|
||||
});
|
||||
|
||||
[Fact]
|
||||
public async Task StartJobAsync_CreatesJobContext()
|
||||
{
|
||||
var client = CreateClient();
|
||||
|
||||
var context = await client.StartJobAsync("tenant-a", "connector-001", "checkpoint-123");
|
||||
|
||||
Assert.NotNull(context);
|
||||
Assert.Equal("tenant-a", context.Tenant);
|
||||
Assert.Equal("connector-001", context.ConnectorId);
|
||||
Assert.Equal("checkpoint-123", context.Checkpoint);
|
||||
Assert.NotEqual(Guid.Empty, context.RunId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendHeartbeatAsync_UpdatesConnectorState()
|
||||
{
|
||||
var client = CreateClient();
|
||||
var context = await client.StartJobAsync("tenant-a", "connector-001", null);
|
||||
|
||||
var heartbeat = new VexWorkerHeartbeat(
|
||||
VexWorkerHeartbeatStatus.Running,
|
||||
Progress: 50,
|
||||
QueueDepth: null,
|
||||
LastArtifactHash: "sha256:abc123",
|
||||
LastArtifactKind: "vex-document",
|
||||
ErrorCode: null,
|
||||
RetryAfterSeconds: null);
|
||||
|
||||
await client.SendHeartbeatAsync(context, heartbeat);
|
||||
|
||||
var state = await _stateRepository.GetAsync("connector-001", CancellationToken.None);
|
||||
Assert.NotNull(state);
|
||||
Assert.Equal("Running", state.LastHeartbeatStatus);
|
||||
Assert.NotNull(state.LastHeartbeatAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordArtifactAsync_TracksArtifactHash()
|
||||
{
|
||||
var client = CreateClient();
|
||||
var context = await client.StartJobAsync("tenant-a", "connector-001", null);
|
||||
|
||||
var artifact = new VexWorkerArtifact(
|
||||
"sha256:deadbeef",
|
||||
"vex-raw-document",
|
||||
"provider-001",
|
||||
"doc-001",
|
||||
_timeProvider.GetUtcNow());
|
||||
|
||||
await client.RecordArtifactAsync(context, artifact);
|
||||
|
||||
var state = await _stateRepository.GetAsync("connector-001", CancellationToken.None);
|
||||
Assert.NotNull(state);
|
||||
Assert.Equal("sha256:deadbeef", state.LastArtifactHash);
|
||||
Assert.Equal("vex-raw-document", state.LastArtifactKind);
|
||||
Assert.Contains("sha256:deadbeef", state.DocumentDigests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteJobAsync_UpdatesStateWithResults()
|
||||
{
|
||||
var client = CreateClient();
|
||||
var context = await client.StartJobAsync("tenant-a", "connector-001", null);
|
||||
var completedAt = _timeProvider.GetUtcNow();
|
||||
|
||||
var result = new VexWorkerJobResult(
|
||||
DocumentsProcessed: 10,
|
||||
ClaimsGenerated: 25,
|
||||
LastCheckpoint: "checkpoint-new",
|
||||
LastArtifactHash: "sha256:final",
|
||||
CompletedAt: completedAt);
|
||||
|
||||
await client.CompleteJobAsync(context, result);
|
||||
|
||||
var state = await _stateRepository.GetAsync("connector-001", CancellationToken.None);
|
||||
Assert.NotNull(state);
|
||||
Assert.Equal("Succeeded", state.LastHeartbeatStatus);
|
||||
Assert.Equal("checkpoint-new", state.LastCheckpoint);
|
||||
Assert.Equal("sha256:final", state.LastArtifactHash);
|
||||
Assert.Equal(0, state.FailureCount);
|
||||
Assert.Null(state.NextEligibleRun);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FailJobAsync_UpdatesStateWithError()
|
||||
{
|
||||
var client = CreateClient();
|
||||
var context = await client.StartJobAsync("tenant-a", "connector-001", null);
|
||||
|
||||
await client.FailJobAsync(context, "CONN_ERROR", "Connection failed", retryAfterSeconds: 60);
|
||||
|
||||
var state = await _stateRepository.GetAsync("connector-001", CancellationToken.None);
|
||||
Assert.NotNull(state);
|
||||
Assert.Equal("Failed", state.LastHeartbeatStatus);
|
||||
Assert.Equal(1, state.FailureCount);
|
||||
Assert.Contains("CONN_ERROR", state.LastFailureReason);
|
||||
Assert.NotNull(state.NextEligibleRun);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VexWorkerJobContext_SequenceIncrements()
|
||||
{
|
||||
var context = new VexWorkerJobContext(
|
||||
"tenant-a",
|
||||
"connector-001",
|
||||
Guid.NewGuid(),
|
||||
null,
|
||||
DateTimeOffset.UtcNow);
|
||||
|
||||
Assert.Equal(0, context.Sequence);
|
||||
Assert.Equal(1, context.NextSequence());
|
||||
Assert.Equal(2, context.NextSequence());
|
||||
Assert.Equal(3, context.NextSequence());
|
||||
}
|
||||
|
||||
private VexWorkerOrchestratorClient CreateClient()
|
||||
=> new(
|
||||
_stateRepository,
|
||||
_timeProvider,
|
||||
_options,
|
||||
NullLogger<VexWorkerOrchestratorClient>.Instance);
|
||||
|
||||
private sealed class FakeTimeProvider : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now = new(2025, 11, 27, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
|
||||
public void Advance(TimeSpan duration) => _now = _now.Add(duration);
|
||||
}
|
||||
|
||||
private sealed class InMemoryConnectorStateRepository : IVexConnectorStateRepository
|
||||
{
|
||||
private readonly Dictionary<string, VexConnectorState> _states = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public ValueTask<VexConnectorState?> GetAsync(string connectorId, CancellationToken cancellationToken, MongoDB.Driver.IClientSessionHandle? session = null)
|
||||
{
|
||||
_states.TryGetValue(connectorId, out var state);
|
||||
return ValueTask.FromResult(state);
|
||||
}
|
||||
|
||||
public ValueTask SaveAsync(VexConnectorState state, CancellationToken cancellationToken, MongoDB.Driver.IClientSessionHandle? session = null)
|
||||
{
|
||||
_states[state.ConnectorId] = state;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
public ValueTask<IReadOnlyCollection<VexConnectorState>> ListAsync(CancellationToken cancellationToken, MongoDB.Driver.IClientSessionHandle? session = null)
|
||||
=> ValueTask.FromResult<IReadOnlyCollection<VexConnectorState>>(_states.Values.ToList());
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ public sealed class TenantAuthorityClientFactoryTests
|
||||
{
|
||||
var options = new TenantAuthorityOptions();
|
||||
options.BaseUrls.Add("tenant-a", "https://authority.example/");
|
||||
var factory = new TenantAuthorityClientFactory(Options.Create(options));
|
||||
var factory = new TenantAuthorityClientFactory(Microsoft.Extensions.Options.Options.Create(options));
|
||||
|
||||
using var client = factory.Create("tenant-a");
|
||||
|
||||
@@ -29,7 +29,7 @@ public sealed class TenantAuthorityClientFactoryTests
|
||||
{
|
||||
var options = new TenantAuthorityOptions();
|
||||
options.BaseUrls.Add("tenant-a", "https://authority.example/");
|
||||
var factory = new TenantAuthorityClientFactory(Options.Create(options));
|
||||
var factory = new TenantAuthorityClientFactory(Microsoft.Extensions.Options.Options.Create(options));
|
||||
|
||||
FluentActions.Invoking(() => factory.Create(string.Empty))
|
||||
.Should().Throw<ArgumentException>();
|
||||
@@ -40,7 +40,7 @@ public sealed class TenantAuthorityClientFactoryTests
|
||||
{
|
||||
var options = new TenantAuthorityOptions();
|
||||
options.BaseUrls.Add("tenant-a", "https://authority.example/");
|
||||
var factory = new TenantAuthorityClientFactory(Options.Create(options));
|
||||
var factory = new TenantAuthorityClientFactory(Microsoft.Extensions.Options.Options.Create(options));
|
||||
|
||||
FluentActions.Invoking(() => factory.Create("tenant-b"))
|
||||
.Should().Throw<InvalidOperationException>();
|
||||
|
||||
Reference in New Issue
Block a user