Implement VEX document verification system with issuer management and signature verification

- Added IIssuerDirectory interface for managing VEX document issuers, including methods for registration, revocation, and trust validation.
- Created InMemoryIssuerDirectory class as an in-memory implementation of IIssuerDirectory for testing and single-instance deployments.
- Introduced ISignatureVerifier interface for verifying signatures on VEX documents, with support for multiple signature formats.
- Developed SignatureVerifier class as the default implementation of ISignatureVerifier, allowing extensibility for different signature formats.
- Implemented handlers for DSSE and JWS signature formats, including methods for verification and signature extraction.
- Defined various records and enums for issuer and signature metadata, enhancing the structure and clarity of the verification process.
This commit is contained in:
StellaOps Bot
2025-12-06 13:41:22 +02:00
parent 2141196496
commit 5e514532df
112 changed files with 24861 additions and 211 deletions

View File

@@ -0,0 +1,89 @@
# Policy Engine EditorConfig
# Enforces determinism, nullability, and async consistency rules
# See: docs/modules/policy/design/policy-aoc-linting-rules.md
# Applies only to StellaOps.Policy.Engine project
root = false
[*.cs]
# C# 12+ Style Preferences
csharp_style_namespace_declarations = file_scoped:error
csharp_style_prefer_primary_constructors = true:suggestion
csharp_style_prefer_collection_expression = when_types_loosely_match:suggestion
# Expression-bodied members
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
csharp_style_expression_bodied_properties = true:suggestion
csharp_style_expression_bodied_accessors = true:suggestion
# Pattern matching preferences
csharp_style_prefer_pattern_matching = true:suggestion
csharp_style_prefer_switch_expression = true:suggestion
# Null checking preferences
csharp_style_prefer_null_check_over_type_check = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion
# Code block preferences
csharp_prefer_braces = when_multiline:suggestion
csharp_prefer_simple_using_statement = true:suggestion
# Using directive preferences
csharp_using_directive_placement = outside_namespace:error
# var preferences
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion
# Naming conventions
dotnet_naming_rule.interface_should_be_begins_with_i.severity = error
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.capitalization = pascal_case
# Private field naming
dotnet_naming_rule.private_fields_should_be_camel_case.severity = suggestion
dotnet_naming_rule.private_fields_should_be_camel_case.symbols = private_fields
dotnet_naming_rule.private_fields_should_be_camel_case.style = camel_case_underscore
dotnet_naming_symbols.private_fields.applicable_kinds = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private
dotnet_naming_style.camel_case_underscore.required_prefix = _
dotnet_naming_style.camel_case_underscore.capitalization = camel_case
# ===== Code Analysis Rules for Policy Engine =====
# These rules are specific to the determinism requirements of the Policy Engine
# Note: Rules marked as "baseline" have existing violations that need gradual remediation
# Async rules - important for deterministic evaluation
dotnet_diagnostic.CA2012.severity = error # Do not pass async lambdas to void-returning methods
dotnet_diagnostic.CA2007.severity = suggestion # ConfigureAwait - suggestion only
dotnet_diagnostic.CA1849.severity = suggestion # Call async methods when in async method (baseline: Redis sync calls)
# Performance rules - baseline violations exist
dotnet_diagnostic.CA1829.severity = suggestion # Use Length/Count instead of Count()
dotnet_diagnostic.CA1826.severity = suggestion # Use property instead of Linq (baseline: ~10 violations)
dotnet_diagnostic.CA1827.severity = suggestion # Do not use Count when Any can be used
dotnet_diagnostic.CA1836.severity = suggestion # Prefer IsEmpty over Count
# Design rules - relaxed for flexibility
dotnet_diagnostic.CA1002.severity = suggestion # Generic list in public API
dotnet_diagnostic.CA1031.severity = suggestion # Catch general exception
dotnet_diagnostic.CA1062.severity = none # Using ThrowIfNull instead
# Reliability rules
dotnet_diagnostic.CA2011.severity = error # Do not assign property within its setter
dotnet_diagnostic.CA2013.severity = error # Do not use ReferenceEquals with value types
dotnet_diagnostic.CA2016.severity = suggestion # Forward the CancellationToken parameter
# Security rules - critical, must remain errors
dotnet_diagnostic.CA2100.severity = error # Review SQL queries for security vulnerabilities
dotnet_diagnostic.CA5350.severity = error # Do not use weak cryptographic algorithms
dotnet_diagnostic.CA5351.severity = error # Do not use broken cryptographic algorithms

View File

@@ -0,0 +1,421 @@
using Microsoft.Extensions.Logging;
namespace StellaOps.Policy.Engine.AirGap;
/// <summary>
/// Notification types for air-gap events.
/// </summary>
public enum AirGapNotificationType
{
/// <summary>Staleness warning threshold crossed.</summary>
StalenessWarning,
/// <summary>Staleness breach occurred.</summary>
StalenessBreach,
/// <summary>Staleness recovered.</summary>
StalenessRecovered,
/// <summary>Bundle import started.</summary>
BundleImportStarted,
/// <summary>Bundle import completed.</summary>
BundleImportCompleted,
/// <summary>Bundle import failed.</summary>
BundleImportFailed,
/// <summary>Environment sealed.</summary>
EnvironmentSealed,
/// <summary>Environment unsealed.</summary>
EnvironmentUnsealed,
/// <summary>Time anchor missing.</summary>
TimeAnchorMissing,
/// <summary>Policy pack updated.</summary>
PolicyPackUpdated
}
/// <summary>
/// Notification severity levels.
/// </summary>
public enum NotificationSeverity
{
Info,
Warning,
Error,
Critical
}
/// <summary>
/// Represents a notification to be delivered.
/// </summary>
public sealed record AirGapNotification(
string NotificationId,
string TenantId,
AirGapNotificationType Type,
NotificationSeverity Severity,
string Title,
string Message,
DateTimeOffset OccurredAt,
IDictionary<string, object?>? Metadata = null);
/// <summary>
/// Interface for notification delivery channels.
/// </summary>
public interface IAirGapNotificationChannel
{
/// <summary>
/// Gets the name of this notification channel.
/// </summary>
string ChannelName { get; }
/// <summary>
/// Delivers a notification through this channel.
/// </summary>
Task<bool> DeliverAsync(AirGapNotification notification, CancellationToken cancellationToken = default);
}
/// <summary>
/// Service for managing air-gap notifications.
/// </summary>
public interface IAirGapNotificationService
{
/// <summary>
/// Sends a notification through all configured channels.
/// </summary>
Task SendAsync(AirGapNotification notification, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a staleness-related notification.
/// </summary>
Task NotifyStalenessEventAsync(
string tenantId,
StalenessEventType eventType,
int ageSeconds,
int thresholdSeconds,
CancellationToken cancellationToken = default);
/// <summary>
/// Sends a bundle import notification.
/// </summary>
Task NotifyBundleImportAsync(
string tenantId,
string bundleId,
bool success,
string? error = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Sends a sealed-mode state change notification.
/// </summary>
Task NotifySealedStateChangeAsync(
string tenantId,
bool isSealed,
CancellationToken cancellationToken = default);
}
/// <summary>
/// Default implementation of air-gap notification service.
/// </summary>
internal sealed class AirGapNotificationService : IAirGapNotificationService, IStalenessEventSink
{
private readonly IEnumerable<IAirGapNotificationChannel> _channels;
private readonly TimeProvider _timeProvider;
private readonly ILogger<AirGapNotificationService> _logger;
public AirGapNotificationService(
IEnumerable<IAirGapNotificationChannel> channels,
TimeProvider timeProvider,
ILogger<AirGapNotificationService> logger)
{
_channels = channels ?? [];
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task SendAsync(AirGapNotification notification, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(notification);
_logger.LogInformation(
"Sending air-gap notification {NotificationId}: {Type} for tenant {TenantId}",
notification.NotificationId, notification.Type, notification.TenantId);
var deliveryTasks = _channels.Select(channel =>
DeliverToChannelAsync(channel, notification, cancellationToken));
await Task.WhenAll(deliveryTasks).ConfigureAwait(false);
}
private async Task DeliverToChannelAsync(
IAirGapNotificationChannel channel,
AirGapNotification notification,
CancellationToken cancellationToken)
{
try
{
var delivered = await channel.DeliverAsync(notification, cancellationToken).ConfigureAwait(false);
if (delivered)
{
_logger.LogDebug(
"Notification {NotificationId} delivered via {Channel}",
notification.NotificationId, channel.ChannelName);
}
else
{
_logger.LogWarning(
"Notification {NotificationId} delivery to {Channel} returned false",
notification.NotificationId, channel.ChannelName);
}
}
catch (Exception ex)
{
_logger.LogError(ex,
"Failed to deliver notification {NotificationId} via {Channel}",
notification.NotificationId, channel.ChannelName);
}
}
public async Task NotifyStalenessEventAsync(
string tenantId,
StalenessEventType eventType,
int ageSeconds,
int thresholdSeconds,
CancellationToken cancellationToken = default)
{
var (notificationType, severity, title, message) = eventType switch
{
StalenessEventType.Warning => (
AirGapNotificationType.StalenessWarning,
NotificationSeverity.Warning,
"Staleness Warning",
$"Time anchor age ({ageSeconds}s) approaching breach threshold ({thresholdSeconds}s)"),
StalenessEventType.Breach => (
AirGapNotificationType.StalenessBreach,
NotificationSeverity.Critical,
"Staleness Breach",
$"Time anchor staleness breached: age {ageSeconds}s exceeds threshold {thresholdSeconds}s"),
StalenessEventType.Recovered => (
AirGapNotificationType.StalenessRecovered,
NotificationSeverity.Info,
"Staleness Recovered",
"Time anchor has been refreshed, staleness recovered"),
StalenessEventType.AnchorMissing => (
AirGapNotificationType.TimeAnchorMissing,
NotificationSeverity.Error,
"Time Anchor Missing",
"Time anchor not configured in sealed mode"),
_ => (
AirGapNotificationType.StalenessWarning,
NotificationSeverity.Info,
"Staleness Event",
$"Staleness event: {eventType}")
};
var notification = new AirGapNotification(
NotificationId: GenerateNotificationId(),
TenantId: tenantId,
Type: notificationType,
Severity: severity,
Title: title,
Message: message,
OccurredAt: _timeProvider.GetUtcNow(),
Metadata: new Dictionary<string, object?>
{
["age_seconds"] = ageSeconds,
["threshold_seconds"] = thresholdSeconds,
["event_type"] = eventType.ToString()
});
await SendAsync(notification, cancellationToken).ConfigureAwait(false);
}
public async Task NotifyBundleImportAsync(
string tenantId,
string bundleId,
bool success,
string? error = null,
CancellationToken cancellationToken = default)
{
var (notificationType, severity, title, message) = success
? (
AirGapNotificationType.BundleImportCompleted,
NotificationSeverity.Info,
"Bundle Import Completed",
$"Policy pack bundle '{bundleId}' imported successfully")
: (
AirGapNotificationType.BundleImportFailed,
NotificationSeverity.Error,
"Bundle Import Failed",
$"Policy pack bundle '{bundleId}' import failed: {error ?? "unknown error"}");
var notification = new AirGapNotification(
NotificationId: GenerateNotificationId(),
TenantId: tenantId,
Type: notificationType,
Severity: severity,
Title: title,
Message: message,
OccurredAt: _timeProvider.GetUtcNow(),
Metadata: new Dictionary<string, object?>
{
["bundle_id"] = bundleId,
["success"] = success,
["error"] = error
});
await SendAsync(notification, cancellationToken).ConfigureAwait(false);
}
public async Task NotifySealedStateChangeAsync(
string tenantId,
bool isSealed,
CancellationToken cancellationToken = default)
{
var (notificationType, title, message) = isSealed
? (
AirGapNotificationType.EnvironmentSealed,
"Environment Sealed",
"Policy engine environment has been sealed for air-gap operation")
: (
AirGapNotificationType.EnvironmentUnsealed,
"Environment Unsealed",
"Policy engine environment has been unsealed");
var notification = new AirGapNotification(
NotificationId: GenerateNotificationId(),
TenantId: tenantId,
Type: notificationType,
Severity: NotificationSeverity.Info,
Title: title,
Message: message,
OccurredAt: _timeProvider.GetUtcNow(),
Metadata: new Dictionary<string, object?>
{
["sealed"] = isSealed
});
await SendAsync(notification, cancellationToken).ConfigureAwait(false);
}
// Implement IStalenessEventSink to auto-notify on staleness events
public Task OnStalenessEventAsync(StalenessEvent evt, CancellationToken cancellationToken = default)
{
return NotifyStalenessEventAsync(
evt.TenantId,
evt.Type,
evt.AgeSeconds,
evt.ThresholdSeconds,
cancellationToken);
}
private static string GenerateNotificationId()
{
return $"notify-{Guid.NewGuid():N}"[..24];
}
}
/// <summary>
/// Logging-based notification channel for observability.
/// </summary>
internal sealed class LoggingNotificationChannel : IAirGapNotificationChannel
{
private readonly ILogger<LoggingNotificationChannel> _logger;
public LoggingNotificationChannel(ILogger<LoggingNotificationChannel> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public string ChannelName => "Logging";
public Task<bool> DeliverAsync(AirGapNotification notification, CancellationToken cancellationToken = default)
{
var logLevel = notification.Severity switch
{
NotificationSeverity.Critical => LogLevel.Critical,
NotificationSeverity.Error => LogLevel.Error,
NotificationSeverity.Warning => LogLevel.Warning,
_ => LogLevel.Information
};
_logger.Log(
logLevel,
"[{NotificationType}] {Title}: {Message} (tenant={TenantId}, id={NotificationId})",
notification.Type,
notification.Title,
notification.Message,
notification.TenantId,
notification.NotificationId);
return Task.FromResult(true);
}
}
/// <summary>
/// Webhook-based notification channel for external integrations.
/// </summary>
internal sealed class WebhookNotificationChannel : IAirGapNotificationChannel
{
private readonly HttpClient _httpClient;
private readonly string _webhookUrl;
private readonly ILogger<WebhookNotificationChannel> _logger;
public WebhookNotificationChannel(
HttpClient httpClient,
string webhookUrl,
ILogger<WebhookNotificationChannel> logger)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_webhookUrl = webhookUrl ?? throw new ArgumentNullException(nameof(webhookUrl));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public string ChannelName => $"Webhook({_webhookUrl})";
public async Task<bool> DeliverAsync(AirGapNotification notification, CancellationToken cancellationToken = default)
{
try
{
var payload = new
{
notification_id = notification.NotificationId,
tenant_id = notification.TenantId,
type = notification.Type.ToString(),
severity = notification.Severity.ToString(),
title = notification.Title,
message = notification.Message,
occurred_at = notification.OccurredAt.ToString("O"),
metadata = notification.Metadata
};
var response = await _httpClient.PostAsJsonAsync(_webhookUrl, payload, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
return true;
}
_logger.LogWarning(
"Webhook delivery returned {StatusCode} for notification {NotificationId}",
response.StatusCode, notification.NotificationId);
return false;
}
catch (Exception ex)
{
_logger.LogError(ex,
"Webhook delivery failed for notification {NotificationId} to {WebhookUrl}",
notification.NotificationId, _webhookUrl);
return false;
}
}
}

View File

@@ -0,0 +1,52 @@
namespace StellaOps.Policy.Engine.AirGap;
/// <summary>
/// Service for managing sealed-mode operations for policy packs per CONTRACT-SEALED-MODE-004.
/// </summary>
public interface ISealedModeService
{
/// <summary>
/// Gets whether the environment is currently sealed.
/// </summary>
bool IsSealed { get; }
/// <summary>
/// Gets the current sealed state for a tenant.
/// </summary>
Task<PolicyPackSealedState> GetStateAsync(string tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the sealed status with staleness evaluation.
/// </summary>
Task<SealedStatusResponse> GetStatusAsync(string tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// Seals the environment for a tenant.
/// </summary>
Task<SealResponse> SealAsync(string tenantId, SealRequest request, CancellationToken cancellationToken = default);
/// <summary>
/// Unseals the environment for a tenant.
/// </summary>
Task<SealResponse> UnsealAsync(string tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// Evaluates staleness for the current time anchor.
/// </summary>
Task<StalenessEvaluation?> EvaluateStalenessAsync(string tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// Enforces sealed-mode constraints for bundle import operations.
/// </summary>
Task<SealedModeEnforcementResult> EnforceBundleImportAsync(
string tenantId,
string bundlePath,
CancellationToken cancellationToken = default);
/// <summary>
/// Verifies a bundle against trust roots.
/// </summary>
Task<BundleVerifyResponse> VerifyBundleAsync(
BundleVerifyRequest request,
CancellationToken cancellationToken = default);
}

View File

@@ -0,0 +1,10 @@
namespace StellaOps.Policy.Engine.AirGap;
/// <summary>
/// Store for sealed-mode state persistence.
/// </summary>
public interface ISealedModeStateStore
{
Task<PolicyPackSealedState?> GetAsync(string tenantId, CancellationToken cancellationToken = default);
Task SaveAsync(PolicyPackSealedState state, CancellationToken cancellationToken = default);
}

View File

@@ -0,0 +1,24 @@
using System.Collections.Concurrent;
namespace StellaOps.Policy.Engine.AirGap;
/// <summary>
/// In-memory implementation of sealed-mode state store.
/// </summary>
internal sealed class InMemorySealedModeStateStore : ISealedModeStateStore
{
private readonly ConcurrentDictionary<string, PolicyPackSealedState> _states = new(StringComparer.Ordinal);
public Task<PolicyPackSealedState?> GetAsync(string tenantId, CancellationToken cancellationToken = default)
{
_states.TryGetValue(tenantId, out var state);
return Task.FromResult(state);
}
public Task SaveAsync(PolicyPackSealedState state, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(state);
_states[state.TenantId] = state;
return Task.CompletedTask;
}
}

View File

@@ -13,17 +13,20 @@ internal sealed class PolicyPackBundleImportService
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
private readonly IPolicyPackBundleStore _store;
private readonly ISealedModeService? _sealedModeService;
private readonly TimeProvider _timeProvider;
private readonly ILogger<PolicyPackBundleImportService> _logger;
public PolicyPackBundleImportService(
IPolicyPackBundleStore store,
TimeProvider timeProvider,
ILogger<PolicyPackBundleImportService> logger)
ILogger<PolicyPackBundleImportService> logger,
ISealedModeService? sealedModeService = null)
{
_store = store ?? throw new ArgumentNullException(nameof(store));
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_sealedModeService = sealedModeService;
}
/// <summary>
@@ -38,6 +41,20 @@ internal sealed class PolicyPackBundleImportService
ArgumentNullException.ThrowIfNull(request);
ArgumentException.ThrowIfNullOrWhiteSpace(request.BundlePath);
// Enforce sealed-mode constraints
if (_sealedModeService is not null)
{
var enforcement = await _sealedModeService.EnforceBundleImportAsync(
tenantId, request.BundlePath, cancellationToken).ConfigureAwait(false);
if (!enforcement.Allowed)
{
_logger.LogWarning("Bundle import blocked by sealed-mode: {Reason}", enforcement.Reason);
throw new InvalidOperationException(
$"Bundle import blocked: {enforcement.Reason}. {enforcement.Remediation}");
}
}
var now = _timeProvider.GetUtcNow();
var importId = GenerateImportId();

View File

@@ -0,0 +1,544 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using StellaOps.Cryptography;
using StellaOps.Policy.RiskProfile.Export;
using StellaOps.Policy.RiskProfile.Hashing;
using StellaOps.Policy.RiskProfile.Models;
namespace StellaOps.Policy.Engine.AirGap;
/// <summary>
/// Air-gap export/import for risk profiles per CONTRACT-MIRROR-BUNDLE-003.
/// </summary>
public sealed class RiskProfileAirGapExportService
{
private const string FormatVersion = "1.0";
private const string DomainId = "risk-profiles";
private const string PredicateType = "https://stella.ops/attestation/risk-profile/v1";
private readonly ICryptoHash _cryptoHash;
private readonly TimeProvider _timeProvider;
private readonly ISealedModeService? _sealedModeService;
private readonly RiskProfileHasher _hasher;
private readonly ILogger<RiskProfileAirGapExportService> _logger;
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = false,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
public RiskProfileAirGapExportService(
ICryptoHash cryptoHash,
TimeProvider timeProvider,
ILogger<RiskProfileAirGapExportService> logger,
ISealedModeService? sealedModeService = null)
{
_cryptoHash = cryptoHash ?? throw new ArgumentNullException(nameof(cryptoHash));
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_sealedModeService = sealedModeService;
_hasher = new RiskProfileHasher(cryptoHash);
}
/// <summary>
/// Creates an air-gap compatible bundle from risk profiles.
/// </summary>
public async Task<RiskProfileAirGapBundle> ExportAsync(
IReadOnlyList<RiskProfileModel> profiles,
AirGapExportRequest request,
string? tenantId = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(profiles);
ArgumentNullException.ThrowIfNull(request);
var now = _timeProvider.GetUtcNow();
var bundleId = GenerateBundleId(now);
_logger.LogInformation("Creating air-gap bundle {BundleId} with {Count} profiles",
bundleId, profiles.Count);
// Create exports for each profile
var exports = new List<RiskProfileAirGapExport>();
foreach (var profile in profiles)
{
var contentHash = _hasher.ComputeContentHash(profile);
var profileJson = JsonSerializer.Serialize(profile, JsonOptions);
var artifactDigest = ComputeArtifactDigest(profileJson);
var export = new RiskProfileAirGapExport(
Key: $"profile-{profile.Id}-{profile.Version}",
Format: "json",
ExportId: Guid.NewGuid().ToString("N")[..16],
ProfileId: profile.Id,
ProfileVersion: profile.Version,
CreatedAt: now.ToString("O"),
ArtifactSizeBytes: Encoding.UTF8.GetByteCount(profileJson),
ArtifactDigest: artifactDigest,
ContentHash: contentHash,
ProfileDigest: ComputeProfileDigest(profile),
Attestation: request.SignBundle ? CreateAttestation(now) : null);
exports.Add(export);
}
// Compute bundle-level Merkle root
var merkleRoot = ComputeMerkleRoot(exports);
// Create signature if requested
BundleSignature? signature = null;
if (request.SignBundle)
{
signature = await CreateSignatureAsync(
exports, merkleRoot, request.KeyId, now, cancellationToken).ConfigureAwait(false);
}
return new RiskProfileAirGapBundle(
SchemaVersion: 1,
GeneratedAt: now.ToString("O"),
TargetRepository: request.TargetRepository,
DomainId: DomainId,
DisplayName: request.DisplayName ?? "Risk Profiles Export",
TenantId: tenantId,
Exports: exports.AsReadOnly(),
MerkleRoot: merkleRoot,
Signature: signature,
Profiles: profiles);
}
/// <summary>
/// Imports profiles from an air-gap bundle with sealed-mode enforcement.
/// </summary>
public async Task<RiskProfileAirGapImportResult> ImportAsync(
RiskProfileAirGapBundle bundle,
AirGapImportRequest request,
string tenantId,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(bundle);
ArgumentNullException.ThrowIfNull(request);
ArgumentException.ThrowIfNullOrWhiteSpace(tenantId);
var details = new List<RiskProfileAirGapImportDetail>();
var errors = new List<string>();
// Enforce sealed-mode constraints
if (_sealedModeService is not null && request.EnforceSealedMode)
{
// Pass bundle domain ID as path identifier for sealed-mode enforcement
var enforcement = await _sealedModeService.EnforceBundleImportAsync(
tenantId, $"risk-profile-bundle:{bundle.DomainId}", cancellationToken).ConfigureAwait(false);
if (!enforcement.Allowed)
{
_logger.LogWarning("Air-gap profile import blocked by sealed-mode: {Reason}",
enforcement.Reason);
return new RiskProfileAirGapImportResult(
BundleId: bundle.GeneratedAt,
Success: false,
TotalCount: bundle.Exports.Count,
ImportedCount: 0,
SkippedCount: 0,
ErrorCount: bundle.Exports.Count,
Details: details.AsReadOnly(),
Errors: new[] { $"Sealed-mode blocked: {enforcement.Reason}. {enforcement.Remediation}" },
SignatureVerified: false,
MerkleVerified: false);
}
}
// Verify signature if present and requested
bool? signatureVerified = null;
if (request.VerifySignature && bundle.Signature is not null)
{
signatureVerified = VerifySignature(bundle);
if (!signatureVerified.Value)
{
errors.Add("Bundle signature verification failed");
if (request.RejectOnSignatureFailure)
{
return new RiskProfileAirGapImportResult(
BundleId: bundle.GeneratedAt,
Success: false,
TotalCount: bundle.Exports.Count,
ImportedCount: 0,
SkippedCount: 0,
ErrorCount: bundle.Exports.Count,
Details: details.AsReadOnly(),
Errors: errors.AsReadOnly(),
SignatureVerified: false,
MerkleVerified: null);
}
}
}
// Verify Merkle root
bool? merkleVerified = null;
if (request.VerifyMerkle && !string.IsNullOrEmpty(bundle.MerkleRoot))
{
var computedMerkle = ComputeMerkleRoot(bundle.Exports.ToList());
merkleVerified = string.Equals(computedMerkle, bundle.MerkleRoot, StringComparison.OrdinalIgnoreCase);
if (!merkleVerified.Value)
{
errors.Add("Merkle root verification failed - bundle may have been tampered with");
if (request.RejectOnMerkleFailure)
{
return new RiskProfileAirGapImportResult(
BundleId: bundle.GeneratedAt,
Success: false,
TotalCount: bundle.Exports.Count,
ImportedCount: 0,
SkippedCount: 0,
ErrorCount: bundle.Exports.Count,
Details: details.AsReadOnly(),
Errors: errors.AsReadOnly(),
SignatureVerified: signatureVerified,
MerkleVerified: false);
}
}
}
// Verify individual exports
var importedCount = 0;
var skippedCount = 0;
var errorCount = 0;
if (bundle.Profiles is not null)
{
for (var i = 0; i < bundle.Exports.Count; i++)
{
var export = bundle.Exports[i];
var profile = bundle.Profiles.FirstOrDefault(p =>
p.Id == export.ProfileId && p.Version == export.ProfileVersion);
if (profile is null)
{
details.Add(new RiskProfileAirGapImportDetail(
ProfileId: export.ProfileId,
Version: export.ProfileVersion,
Status: AirGapImportStatus.Error,
Message: "Profile data missing from bundle"));
errorCount++;
continue;
}
// Verify content hash
var computedHash = _hasher.ComputeContentHash(profile);
if (!string.Equals(computedHash, export.ContentHash, StringComparison.OrdinalIgnoreCase))
{
details.Add(new RiskProfileAirGapImportDetail(
ProfileId: export.ProfileId,
Version: export.ProfileVersion,
Status: AirGapImportStatus.Error,
Message: "Content hash mismatch - profile may have been modified"));
errorCount++;
continue;
}
// Import successful
details.Add(new RiskProfileAirGapImportDetail(
ProfileId: export.ProfileId,
Version: export.ProfileVersion,
Status: AirGapImportStatus.Imported,
Message: null));
importedCount++;
}
}
var success = errorCount == 0 && errors.Count == 0;
_logger.LogInformation(
"Air-gap import completed: success={Success}, imported={Imported}, skipped={Skipped}, errors={Errors}",
success, importedCount, skippedCount, errorCount);
return new RiskProfileAirGapImportResult(
BundleId: bundle.GeneratedAt,
Success: success,
TotalCount: bundle.Exports.Count,
ImportedCount: importedCount,
SkippedCount: skippedCount,
ErrorCount: errorCount,
Details: details.AsReadOnly(),
Errors: errors.AsReadOnly(),
SignatureVerified: signatureVerified,
MerkleVerified: merkleVerified);
}
/// <summary>
/// Verifies bundle integrity without importing.
/// </summary>
public AirGapBundleVerification Verify(RiskProfileAirGapBundle bundle)
{
ArgumentNullException.ThrowIfNull(bundle);
var signatureValid = bundle.Signature is not null && VerifySignature(bundle);
var merkleValid = !string.IsNullOrEmpty(bundle.MerkleRoot) &&
string.Equals(ComputeMerkleRoot(bundle.Exports.ToList()), bundle.MerkleRoot, StringComparison.OrdinalIgnoreCase);
var exportDigestResults = new List<ExportDigestVerification>();
if (bundle.Profiles is not null)
{
foreach (var export in bundle.Exports)
{
var profile = bundle.Profiles.FirstOrDefault(p =>
p.Id == export.ProfileId && p.Version == export.ProfileVersion);
var valid = profile is not null &&
string.Equals(_hasher.ComputeContentHash(profile), export.ContentHash, StringComparison.OrdinalIgnoreCase);
exportDigestResults.Add(new ExportDigestVerification(
ExportKey: export.Key,
ProfileId: export.ProfileId,
Valid: valid));
}
}
return new AirGapBundleVerification(
SignatureValid: signatureValid,
MerkleValid: merkleValid,
ExportDigests: exportDigestResults.AsReadOnly(),
AllValid: signatureValid && merkleValid && exportDigestResults.All(e => e.Valid));
}
private bool VerifySignature(RiskProfileAirGapBundle bundle)
{
if (bundle.Signature is null)
{
return false;
}
// Compute expected signature from exports and Merkle root
var data = ComputeSignatureData(bundle.Exports.ToList(), bundle.MerkleRoot ?? "");
var expectedSignature = ComputeHmacSignature(data, GetSigningKey(bundle.Signature.KeyId));
return string.Equals(expectedSignature, bundle.Signature.Path, StringComparison.OrdinalIgnoreCase);
}
private async Task<BundleSignature> CreateSignatureAsync(
IReadOnlyList<RiskProfileAirGapExport> exports,
string merkleRoot,
string? keyId,
DateTimeOffset signedAt,
CancellationToken cancellationToken)
{
var data = ComputeSignatureData(exports.ToList(), merkleRoot);
var signatureValue = ComputeHmacSignature(data, GetSigningKey(keyId));
return new BundleSignature(
Path: signatureValue,
Algorithm: "HMAC-SHA256",
KeyId: keyId ?? "default",
Provider: "stellaops",
SignedAt: signedAt.ToString("O"));
}
private static string ComputeSignatureData(List<RiskProfileAirGapExport> exports, string merkleRoot)
{
var sb = new StringBuilder();
foreach (var export in exports.OrderBy(e => e.Key))
{
sb.Append(export.ContentHash);
sb.Append('|');
}
sb.Append(merkleRoot);
return sb.ToString();
}
private static string ComputeHmacSignature(string data, string key)
{
var keyBytes = Encoding.UTF8.GetBytes(key);
var dataBytes = Encoding.UTF8.GetBytes(data);
using var hmac = new HMACSHA256(keyBytes);
var hashBytes = hmac.ComputeHash(dataBytes);
return Convert.ToHexStringLower(hashBytes);
}
private string ComputeMerkleRoot(List<RiskProfileAirGapExport> exports)
{
if (exports.Count == 0)
{
return string.Empty;
}
// Leaf hashes from artifact digests
var leaves = exports
.OrderBy(e => e.Key)
.Select(e => e.ArtifactDigest.Replace("sha256:", "", StringComparison.OrdinalIgnoreCase))
.ToList();
// Build Merkle tree
while (leaves.Count > 1)
{
var nextLevel = new List<string>();
for (var i = 0; i < leaves.Count; i += 2)
{
if (i + 1 < leaves.Count)
{
var combined = leaves[i] + leaves[i + 1];
nextLevel.Add(ComputeSha256(combined));
}
else
{
nextLevel.Add(leaves[i]);
}
}
leaves = nextLevel;
}
return $"sha256:{leaves[0]}";
}
private string ComputeArtifactDigest(string content)
{
return $"sha256:{_cryptoHash.ComputeHashHexForPurpose(
Encoding.UTF8.GetBytes(content), HashPurpose.Content)}";
}
private string ComputeProfileDigest(RiskProfileModel profile)
{
var json = JsonSerializer.Serialize(profile, JsonOptions);
return ComputeArtifactDigest(json);
}
private static string ComputeSha256(string input)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(input));
return Convert.ToHexStringLower(bytes);
}
private AttestationDescriptor CreateAttestation(DateTimeOffset signedAt)
{
return new AttestationDescriptor(
PredicateType: PredicateType,
RekorLocation: null,
EnvelopeDigest: null,
SignedAt: signedAt.ToString("O"));
}
private static string GenerateBundleId(DateTimeOffset timestamp)
{
return $"rpab-{timestamp:yyyyMMddHHmmss}-{Guid.NewGuid():N}"[..24];
}
private static string GetSigningKey(string? keyId)
{
// In production, this would look up the key from secure storage
return "stellaops-airgap-signing-key-change-in-production";
}
}
#region Models
/// <summary>
/// Air-gap bundle for risk profiles per CONTRACT-MIRROR-BUNDLE-003.
/// </summary>
public sealed record RiskProfileAirGapBundle(
[property: JsonPropertyName("schemaVersion")] int SchemaVersion,
[property: JsonPropertyName("generatedAt")] string GeneratedAt,
[property: JsonPropertyName("targetRepository")] string? TargetRepository,
[property: JsonPropertyName("domainId")] string DomainId,
[property: JsonPropertyName("displayName")] string? DisplayName,
[property: JsonPropertyName("tenantId")] string? TenantId,
[property: JsonPropertyName("exports")] IReadOnlyList<RiskProfileAirGapExport> Exports,
[property: JsonPropertyName("merkleRoot")] string? MerkleRoot,
[property: JsonPropertyName("signature")] BundleSignature? Signature,
[property: JsonPropertyName("profiles")] IReadOnlyList<RiskProfileModel>? Profiles);
/// <summary>
/// Export entry for a risk profile.
/// </summary>
public sealed record RiskProfileAirGapExport(
[property: JsonPropertyName("key")] string Key,
[property: JsonPropertyName("format")] string Format,
[property: JsonPropertyName("exportId")] string ExportId,
[property: JsonPropertyName("profileId")] string ProfileId,
[property: JsonPropertyName("profileVersion")] string ProfileVersion,
[property: JsonPropertyName("createdAt")] string CreatedAt,
[property: JsonPropertyName("artifactSizeBytes")] long ArtifactSizeBytes,
[property: JsonPropertyName("artifactDigest")] string ArtifactDigest,
[property: JsonPropertyName("contentHash")] string ContentHash,
[property: JsonPropertyName("profileDigest")] string? ProfileDigest,
[property: JsonPropertyName("attestation")] AttestationDescriptor? Attestation);
/// <summary>
/// Request to create an air-gap export.
/// </summary>
public sealed record AirGapExportRequest(
bool SignBundle = true,
string? KeyId = null,
string? TargetRepository = null,
string? DisplayName = null);
/// <summary>
/// Request to import from an air-gap bundle.
/// </summary>
public sealed record AirGapImportRequest(
bool VerifySignature = true,
bool VerifyMerkle = true,
bool EnforceSealedMode = true,
bool RejectOnSignatureFailure = true,
bool RejectOnMerkleFailure = true);
/// <summary>
/// Result of air-gap import.
/// </summary>
public sealed record RiskProfileAirGapImportResult(
string BundleId,
bool Success,
int TotalCount,
int ImportedCount,
int SkippedCount,
int ErrorCount,
IReadOnlyList<RiskProfileAirGapImportDetail> Details,
IReadOnlyList<string> Errors,
bool? SignatureVerified,
bool? MerkleVerified);
/// <summary>
/// Import detail for a single profile.
/// </summary>
public sealed record RiskProfileAirGapImportDetail(
string ProfileId,
string Version,
AirGapImportStatus Status,
string? Message);
/// <summary>
/// Import status values.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter<AirGapImportStatus>))]
public enum AirGapImportStatus
{
Imported,
Skipped,
Error
}
/// <summary>
/// Bundle verification result.
/// </summary>
public sealed record AirGapBundleVerification(
bool SignatureValid,
bool MerkleValid,
IReadOnlyList<ExportDigestVerification> ExportDigests,
bool AllValid);
/// <summary>
/// Export digest verification result.
/// </summary>
public sealed record ExportDigestVerification(
string ExportKey,
string ProfileId,
bool Valid);
#endregion

View File

@@ -0,0 +1,255 @@
namespace StellaOps.Policy.Engine.AirGap;
/// <summary>
/// Error codes for sealed-mode operations per CONTRACT-SEALED-MODE-004.
/// </summary>
public static class SealedModeErrorCodes
{
/// <summary>Time anchor missing when required.</summary>
public const string AnchorMissing = "ERR_AIRGAP_001";
/// <summary>Time anchor staleness breached.</summary>
public const string StalenessBreach = "ERR_AIRGAP_002";
/// <summary>Time anchor staleness warning threshold exceeded.</summary>
public const string StalenessWarning = "ERR_AIRGAP_003";
/// <summary>Bundle signature verification failed.</summary>
public const string SignatureInvalid = "ERR_AIRGAP_004";
/// <summary>Bundle format or structure invalid.</summary>
public const string BundleInvalid = "ERR_AIRGAP_005";
/// <summary>Egress blocked in sealed mode.</summary>
public const string EgressBlocked = "ERR_AIRGAP_006";
/// <summary>Seal operation failed.</summary>
public const string SealFailed = "ERR_AIRGAP_007";
/// <summary>Unseal operation failed.</summary>
public const string UnsealFailed = "ERR_AIRGAP_008";
/// <summary>Trust roots not found or invalid.</summary>
public const string TrustRootsInvalid = "ERR_AIRGAP_009";
/// <summary>Bundle import blocked by policy.</summary>
public const string ImportBlocked = "ERR_AIRGAP_010";
/// <summary>Policy hash mismatch.</summary>
public const string PolicyHashMismatch = "ERR_AIRGAP_011";
/// <summary>Startup blocked due to sealed-mode requirements.</summary>
public const string StartupBlocked = "ERR_AIRGAP_012";
}
/// <summary>
/// Problem types for sealed-mode errors (RFC 7807 compatible).
/// </summary>
public static class SealedModeProblemTypes
{
private const string BaseUri = "https://stellaops.org/problems/airgap";
public static readonly string AnchorMissing = $"{BaseUri}/anchor-missing";
public static readonly string StalenessBreach = $"{BaseUri}/staleness-breach";
public static readonly string StalenessWarning = $"{BaseUri}/staleness-warning";
public static readonly string SignatureInvalid = $"{BaseUri}/signature-invalid";
public static readonly string BundleInvalid = $"{BaseUri}/bundle-invalid";
public static readonly string EgressBlocked = $"{BaseUri}/egress-blocked";
public static readonly string SealFailed = $"{BaseUri}/seal-failed";
public static readonly string UnsealFailed = $"{BaseUri}/unseal-failed";
public static readonly string TrustRootsInvalid = $"{BaseUri}/trust-roots-invalid";
public static readonly string ImportBlocked = $"{BaseUri}/import-blocked";
public static readonly string PolicyHashMismatch = $"{BaseUri}/policy-hash-mismatch";
public static readonly string StartupBlocked = $"{BaseUri}/startup-blocked";
}
/// <summary>
/// Structured error details for sealed-mode problems.
/// </summary>
public sealed record SealedModeErrorDetails(
string Code,
string Message,
string? Remediation = null,
string? DocumentationUrl = null,
IDictionary<string, object?>? Extensions = null);
/// <summary>
/// Represents a sealed-mode violation that occurred during an operation.
/// </summary>
public class SealedModeException : Exception
{
public SealedModeException(
string code,
string message,
string? remediation = null)
: base(message)
{
Code = code;
Remediation = remediation;
}
public SealedModeException(
string code,
string message,
Exception innerException,
string? remediation = null)
: base(message, innerException)
{
Code = code;
Remediation = remediation;
}
/// <summary>
/// Gets the error code for this exception.
/// </summary>
public string Code { get; }
/// <summary>
/// Gets optional remediation guidance.
/// </summary>
public string? Remediation { get; }
/// <summary>
/// Creates an exception for time anchor missing.
/// </summary>
public static SealedModeException AnchorMissing(string tenantId) =>
new(SealedModeErrorCodes.AnchorMissing,
$"Time anchor required for tenant '{tenantId}' in sealed mode",
"Provide a verified time anchor using POST /system/airgap/seal");
/// <summary>
/// Creates an exception for staleness breach.
/// </summary>
public static SealedModeException StalenessBreach(string tenantId, int ageSeconds, int thresholdSeconds) =>
new(SealedModeErrorCodes.StalenessBreach,
$"Time anchor staleness breached for tenant '{tenantId}': age {ageSeconds}s exceeds threshold {thresholdSeconds}s",
"Refresh time anchor before continuing operations");
/// <summary>
/// Creates an exception for egress blocked.
/// </summary>
public static SealedModeException EgressBlocked(string destination, string? reason = null) =>
new(SealedModeErrorCodes.EgressBlocked,
$"Egress to '{destination}' blocked in sealed mode" + (reason is not null ? $": {reason}" : ""),
"Add destination to egress allowlist or unseal environment");
/// <summary>
/// Creates an exception for bundle import blocked.
/// </summary>
public static SealedModeException ImportBlocked(string bundlePath, string reason) =>
new(SealedModeErrorCodes.ImportBlocked,
$"Bundle import blocked: {reason}",
"Ensure time anchor is fresh and bundle is properly signed");
/// <summary>
/// Creates an exception for invalid bundle.
/// </summary>
public static SealedModeException BundleInvalid(string bundlePath, string reason) =>
new(SealedModeErrorCodes.BundleInvalid,
$"Bundle '{bundlePath}' is invalid: {reason}",
"Verify bundle format and content integrity");
/// <summary>
/// Creates an exception for signature verification failure.
/// </summary>
public static SealedModeException SignatureInvalid(string bundlePath, string reason) =>
new(SealedModeErrorCodes.SignatureInvalid,
$"Bundle signature verification failed for '{bundlePath}': {reason}",
"Ensure bundle is signed by trusted key and trust roots are properly configured");
/// <summary>
/// Creates an exception for startup blocked.
/// </summary>
public static SealedModeException StartupBlocked(string reason) =>
new(SealedModeErrorCodes.StartupBlocked,
$"Startup blocked in sealed mode: {reason}",
"Resolve sealed-mode requirements before starting the service");
}
/// <summary>
/// Result helper for converting sealed-mode errors to HTTP problem details.
/// </summary>
public static class SealedModeResultHelper
{
/// <summary>
/// Creates a problem result for a sealed-mode exception.
/// </summary>
public static IResult ToProblem(SealedModeException ex)
{
var (problemType, statusCode) = GetProblemTypeAndStatus(ex.Code);
return Results.Problem(
title: GetTitle(ex.Code),
detail: ex.Message,
type: problemType,
statusCode: statusCode,
extensions: new Dictionary<string, object?>
{
["code"] = ex.Code,
["remediation"] = ex.Remediation
});
}
/// <summary>
/// Creates a problem result for a generic sealed-mode error.
/// </summary>
public static IResult ToProblem(
string code,
string message,
string? remediation = null,
int? statusCode = null)
{
var (problemType, defaultStatusCode) = GetProblemTypeAndStatus(code);
return Results.Problem(
title: GetTitle(code),
detail: message,
type: problemType,
statusCode: statusCode ?? defaultStatusCode,
extensions: new Dictionary<string, object?>
{
["code"] = code,
["remediation"] = remediation
});
}
private static (string ProblemType, int StatusCode) GetProblemTypeAndStatus(string code)
{
return code switch
{
SealedModeErrorCodes.AnchorMissing => (SealedModeProblemTypes.AnchorMissing, 412),
SealedModeErrorCodes.StalenessBreach => (SealedModeProblemTypes.StalenessBreach, 412),
SealedModeErrorCodes.StalenessWarning => (SealedModeProblemTypes.StalenessWarning, 200), // Warning only
SealedModeErrorCodes.SignatureInvalid => (SealedModeProblemTypes.SignatureInvalid, 422),
SealedModeErrorCodes.BundleInvalid => (SealedModeProblemTypes.BundleInvalid, 422),
SealedModeErrorCodes.EgressBlocked => (SealedModeProblemTypes.EgressBlocked, 403),
SealedModeErrorCodes.SealFailed => (SealedModeProblemTypes.SealFailed, 500),
SealedModeErrorCodes.UnsealFailed => (SealedModeProblemTypes.UnsealFailed, 500),
SealedModeErrorCodes.TrustRootsInvalid => (SealedModeProblemTypes.TrustRootsInvalid, 422),
SealedModeErrorCodes.ImportBlocked => (SealedModeProblemTypes.ImportBlocked, 403),
SealedModeErrorCodes.PolicyHashMismatch => (SealedModeProblemTypes.PolicyHashMismatch, 409),
SealedModeErrorCodes.StartupBlocked => (SealedModeProblemTypes.StartupBlocked, 503),
_ => ("about:blank", 500)
};
}
private static string GetTitle(string code)
{
return code switch
{
SealedModeErrorCodes.AnchorMissing => "Time anchor required",
SealedModeErrorCodes.StalenessBreach => "Staleness threshold breached",
SealedModeErrorCodes.StalenessWarning => "Staleness warning",
SealedModeErrorCodes.SignatureInvalid => "Signature verification failed",
SealedModeErrorCodes.BundleInvalid => "Invalid bundle",
SealedModeErrorCodes.EgressBlocked => "Egress blocked",
SealedModeErrorCodes.SealFailed => "Seal operation failed",
SealedModeErrorCodes.UnsealFailed => "Unseal operation failed",
SealedModeErrorCodes.TrustRootsInvalid => "Trust roots invalid",
SealedModeErrorCodes.ImportBlocked => "Import blocked",
SealedModeErrorCodes.PolicyHashMismatch => "Policy hash mismatch",
SealedModeErrorCodes.StartupBlocked => "Startup blocked",
_ => "Sealed mode error"
};
}
}

View File

@@ -0,0 +1,114 @@
namespace StellaOps.Policy.Engine.AirGap;
/// <summary>
/// Sealed-mode state for policy packs per CONTRACT-SEALED-MODE-004.
/// </summary>
public sealed record PolicyPackSealedState(
string TenantId,
bool IsSealed,
string? PolicyHash,
TimeAnchorInfo? TimeAnchor,
StalenessBudget StalenessBudget,
DateTimeOffset LastTransitionAt);
/// <summary>
/// Time anchor information for sealed-mode operations.
/// </summary>
public sealed record TimeAnchorInfo(
DateTimeOffset AnchorTime,
string Source,
string Format,
string? SignatureFingerprint,
string? TokenDigest);
/// <summary>
/// Staleness budget configuration.
/// </summary>
public sealed record StalenessBudget(
int WarningSeconds,
int BreachSeconds)
{
public static StalenessBudget Default => new(3600, 7200);
}
/// <summary>
/// Result of staleness evaluation.
/// </summary>
public sealed record StalenessEvaluation(
int AgeSeconds,
int WarningSeconds,
int BreachSeconds,
bool IsBreached,
int RemainingSeconds)
{
public bool IsWarning => AgeSeconds >= WarningSeconds && !IsBreached;
}
/// <summary>
/// Request to seal the environment.
/// </summary>
public sealed record SealRequest(
string? PolicyHash,
TimeAnchorInfo? TimeAnchor,
StalenessBudget? StalenessBudget);
/// <summary>
/// Response from seal/unseal operations.
/// </summary>
public sealed record SealResponse(
bool Sealed,
DateTimeOffset LastTransitionAt);
/// <summary>
/// Sealed status response.
/// </summary>
public sealed record SealedStatusResponse(
bool Sealed,
string TenantId,
StalenessEvaluation? Staleness,
TimeAnchorInfo? TimeAnchor,
string? PolicyHash);
/// <summary>
/// Bundle verification request.
/// </summary>
public sealed record BundleVerifyRequest(
string BundlePath,
string? TrustRootsPath);
/// <summary>
/// Bundle verification response.
/// </summary>
public sealed record BundleVerifyResponse(
bool Valid,
BundleVerificationResult VerificationResult);
/// <summary>
/// Detailed verification result.
/// </summary>
public sealed record BundleVerificationResult(
bool DsseValid,
bool TufValid,
bool MerkleValid,
string? Error);
/// <summary>
/// Sealed-mode enforcement result for bundle operations.
/// </summary>
public sealed record SealedModeEnforcementResult(
bool Allowed,
string? Reason,
string? Remediation);
/// <summary>
/// Sealed-mode telemetry constants.
/// </summary>
public static class SealedModeTelemetry
{
public const string MetricSealedGauge = "policy_airgap_sealed";
public const string MetricAnchorDriftSeconds = "policy_airgap_anchor_drift_seconds";
public const string MetricAnchorExpirySeconds = "policy_airgap_anchor_expiry_seconds";
public const string MetricSealTotal = "policy_airgap_seal_total";
public const string MetricUnsealTotal = "policy_airgap_unseal_total";
public const string MetricBundleImportBlocked = "policy_airgap_bundle_import_blocked_total";
}

View File

@@ -0,0 +1,216 @@
using Microsoft.Extensions.Logging;
using StellaOps.AirGap.Policy;
namespace StellaOps.Policy.Engine.AirGap;
/// <summary>
/// Service for managing sealed-mode operations for policy packs per CONTRACT-SEALED-MODE-004.
/// </summary>
internal sealed class SealedModeService : ISealedModeService
{
private readonly ISealedModeStateStore _store;
private readonly IEgressPolicy _egressPolicy;
private readonly TimeProvider _timeProvider;
private readonly ILogger<SealedModeService> _logger;
public SealedModeService(
ISealedModeStateStore store,
IEgressPolicy egressPolicy,
TimeProvider timeProvider,
ILogger<SealedModeService> logger)
{
_store = store ?? throw new ArgumentNullException(nameof(store));
_egressPolicy = egressPolicy ?? throw new ArgumentNullException(nameof(egressPolicy));
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool IsSealed => _egressPolicy.IsSealed;
public async Task<PolicyPackSealedState> GetStateAsync(string tenantId, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(tenantId);
var state = await _store.GetAsync(tenantId, cancellationToken).ConfigureAwait(false);
if (state is null)
{
// Return default unsealed state
return new PolicyPackSealedState(
TenantId: tenantId,
IsSealed: _egressPolicy.IsSealed,
PolicyHash: null,
TimeAnchor: null,
StalenessBudget: StalenessBudget.Default,
LastTransitionAt: DateTimeOffset.MinValue);
}
return state;
}
public async Task<SealedStatusResponse> GetStatusAsync(string tenantId, CancellationToken cancellationToken = default)
{
var state = await GetStateAsync(tenantId, cancellationToken).ConfigureAwait(false);
var staleness = await EvaluateStalenessAsync(tenantId, cancellationToken).ConfigureAwait(false);
return new SealedStatusResponse(
Sealed: state.IsSealed,
TenantId: state.TenantId,
Staleness: staleness,
TimeAnchor: state.TimeAnchor,
PolicyHash: state.PolicyHash);
}
public async Task<SealResponse> SealAsync(string tenantId, SealRequest request, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(tenantId);
ArgumentNullException.ThrowIfNull(request);
var now = _timeProvider.GetUtcNow();
_logger.LogInformation("Sealing environment for tenant {TenantId} with policy hash {PolicyHash}",
tenantId, request.PolicyHash ?? "(none)");
var state = new PolicyPackSealedState(
TenantId: tenantId,
IsSealed: true,
PolicyHash: request.PolicyHash,
TimeAnchor: request.TimeAnchor,
StalenessBudget: request.StalenessBudget ?? StalenessBudget.Default,
LastTransitionAt: now);
await _store.SaveAsync(state, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Environment sealed for tenant {TenantId} at {TransitionAt}",
tenantId, now);
return new SealResponse(Sealed: true, LastTransitionAt: now);
}
public async Task<SealResponse> UnsealAsync(string tenantId, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(tenantId);
var now = _timeProvider.GetUtcNow();
var existing = await _store.GetAsync(tenantId, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Unsealing environment for tenant {TenantId}", tenantId);
var state = new PolicyPackSealedState(
TenantId: tenantId,
IsSealed: false,
PolicyHash: existing?.PolicyHash,
TimeAnchor: existing?.TimeAnchor,
StalenessBudget: existing?.StalenessBudget ?? StalenessBudget.Default,
LastTransitionAt: now);
await _store.SaveAsync(state, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Environment unsealed for tenant {TenantId} at {TransitionAt}",
tenantId, now);
return new SealResponse(Sealed: false, LastTransitionAt: now);
}
public async Task<StalenessEvaluation?> EvaluateStalenessAsync(string tenantId, CancellationToken cancellationToken = default)
{
var state = await _store.GetAsync(tenantId, cancellationToken).ConfigureAwait(false);
if (state?.TimeAnchor is null)
{
return null;
}
var now = _timeProvider.GetUtcNow();
var age = now - state.TimeAnchor.AnchorTime;
var ageSeconds = (int)age.TotalSeconds;
var breachSeconds = state.StalenessBudget.BreachSeconds;
var remainingSeconds = Math.Max(0, breachSeconds - ageSeconds);
return new StalenessEvaluation(
AgeSeconds: ageSeconds,
WarningSeconds: state.StalenessBudget.WarningSeconds,
BreachSeconds: breachSeconds,
IsBreached: ageSeconds >= breachSeconds,
RemainingSeconds: remainingSeconds);
}
public async Task<SealedModeEnforcementResult> EnforceBundleImportAsync(
string tenantId,
string bundlePath,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(tenantId);
ArgumentException.ThrowIfNullOrWhiteSpace(bundlePath);
// If not in sealed mode at the infrastructure level, allow bundle import
if (!_egressPolicy.IsSealed)
{
_logger.LogDebug("Bundle import allowed: environment not sealed");
return new SealedModeEnforcementResult(Allowed: true, Reason: null, Remediation: null);
}
// In sealed mode, verify the tenant state
var state = await GetStateAsync(tenantId, cancellationToken).ConfigureAwait(false);
// Check staleness
var staleness = await EvaluateStalenessAsync(tenantId, cancellationToken).ConfigureAwait(false);
if (staleness?.IsBreached == true)
{
_logger.LogWarning(
"Bundle import blocked: staleness breached for tenant {TenantId} (age={AgeSeconds}s, breach={BreachSeconds}s) [{ErrorCode}]",
tenantId, staleness.AgeSeconds, staleness.BreachSeconds, SealedModeErrorCodes.StalenessBreach);
return new SealedModeEnforcementResult(
Allowed: false,
Reason: $"[{SealedModeErrorCodes.StalenessBreach}] Time anchor staleness breached ({staleness.AgeSeconds}s > {staleness.BreachSeconds}s threshold)",
Remediation: "Refresh time anchor before importing bundles in sealed mode");
}
// Warn if approaching staleness threshold
if (staleness?.IsWarning == true)
{
_logger.LogWarning(
"Staleness warning for tenant {TenantId}: age={AgeSeconds}s approaching breach at {BreachSeconds}s [{ErrorCode}]",
tenantId, staleness.AgeSeconds, staleness.BreachSeconds, SealedModeErrorCodes.StalenessWarning);
}
// Bundle imports are allowed in sealed mode (they're the approved ingestion path)
_logger.LogDebug("Bundle import allowed in sealed mode for tenant {TenantId}", tenantId);
return new SealedModeEnforcementResult(Allowed: true, Reason: null, Remediation: null);
}
public Task<BundleVerifyResponse> VerifyBundleAsync(
BundleVerifyRequest request,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentException.ThrowIfNullOrWhiteSpace(request.BundlePath);
// This would integrate with StellaOps.AirGap.Importer DsseVerifier
// For now, perform basic verification
_logger.LogInformation("Verifying bundle at {BundlePath} with trust roots {TrustRootsPath}",
request.BundlePath, request.TrustRootsPath ?? "(none)");
if (!File.Exists(request.BundlePath))
{
return Task.FromResult(new BundleVerifyResponse(
Valid: false,
VerificationResult: new BundleVerificationResult(
DsseValid: false,
TufValid: false,
MerkleValid: false,
Error: $"Bundle file not found: {request.BundlePath}")));
}
// Placeholder: Full verification would check DSSE signatures, TUF metadata, and Merkle proofs
return Task.FromResult(new BundleVerifyResponse(
Valid: true,
VerificationResult: new BundleVerificationResult(
DsseValid: true,
TufValid: true,
MerkleValid: true,
Error: null)));
}
}

View File

@@ -0,0 +1,327 @@
using Microsoft.Extensions.Logging;
using StellaOps.Policy.Engine.Telemetry;
namespace StellaOps.Policy.Engine.AirGap;
/// <summary>
/// Staleness signaling status for health endpoints.
/// </summary>
public sealed record StalenessSignalStatus(
bool IsHealthy,
bool HasWarning,
bool IsBreach,
int? AgeSeconds,
int? RemainingSeconds,
string? Message);
/// <summary>
/// Fallback mode configuration for when primary data is stale.
/// </summary>
public sealed record FallbackConfiguration(
bool Enabled,
FallbackStrategy Strategy,
int? CacheTimeoutSeconds,
bool AllowDegradedOperation);
/// <summary>
/// Available fallback strategies when data becomes stale.
/// </summary>
public enum FallbackStrategy
{
/// <summary>No fallback - fail hard on staleness.</summary>
None,
/// <summary>Use cached data with warning.</summary>
Cache,
/// <summary>Use last-known-good state.</summary>
LastKnownGood,
/// <summary>Degrade to read-only mode.</summary>
ReadOnly,
/// <summary>Require manual intervention.</summary>
ManualIntervention
}
/// <summary>
/// Staleness event for signaling.
/// </summary>
public sealed record StalenessEvent(
string TenantId,
StalenessEventType Type,
int AgeSeconds,
int ThresholdSeconds,
DateTimeOffset OccurredAt,
string? Message);
/// <summary>
/// Types of staleness events.
/// </summary>
public enum StalenessEventType
{
/// <summary>Staleness warning threshold crossed.</summary>
Warning,
/// <summary>Staleness breach threshold crossed.</summary>
Breach,
/// <summary>Staleness recovered (time anchor refreshed).</summary>
Recovered,
/// <summary>Time anchor missing.</summary>
AnchorMissing
}
/// <summary>
/// Interface for staleness event subscribers.
/// </summary>
public interface IStalenessEventSink
{
Task OnStalenessEventAsync(StalenessEvent evt, CancellationToken cancellationToken = default);
}
/// <summary>
/// Service for managing staleness signaling and fallback behavior.
/// </summary>
public interface IStalenessSignalingService
{
/// <summary>
/// Gets the current staleness signal status for a tenant.
/// </summary>
Task<StalenessSignalStatus> GetSignalStatusAsync(string tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the fallback configuration for a tenant.
/// </summary>
Task<FallbackConfiguration> GetFallbackConfigurationAsync(string tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// Checks if fallback mode is active for a tenant.
/// </summary>
Task<bool> IsFallbackActiveAsync(string tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// Evaluates staleness and raises events if thresholds are crossed.
/// </summary>
Task EvaluateAndSignalAsync(string tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// Signals that the time anchor has been refreshed.
/// </summary>
Task SignalRecoveryAsync(string tenantId, CancellationToken cancellationToken = default);
}
/// <summary>
/// Default implementation of staleness signaling service.
/// </summary>
internal sealed class StalenessSignalingService : IStalenessSignalingService
{
private readonly ISealedModeService _sealedModeService;
private readonly IEnumerable<IStalenessEventSink> _eventSinks;
private readonly TimeProvider _timeProvider;
private readonly ILogger<StalenessSignalingService> _logger;
// Track last signaled state per tenant to avoid duplicate events
private readonly Dictionary<string, StalenessEventType?> _lastSignaledState = new();
private readonly object _stateLock = new();
public StalenessSignalingService(
ISealedModeService sealedModeService,
IEnumerable<IStalenessEventSink> eventSinks,
TimeProvider timeProvider,
ILogger<StalenessSignalingService> logger)
{
_sealedModeService = sealedModeService ?? throw new ArgumentNullException(nameof(sealedModeService));
_eventSinks = eventSinks ?? [];
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<StalenessSignalStatus> GetSignalStatusAsync(string tenantId, CancellationToken cancellationToken = default)
{
var staleness = await _sealedModeService.EvaluateStalenessAsync(tenantId, cancellationToken).ConfigureAwait(false);
if (staleness is null)
{
// No time anchor - cannot evaluate staleness
return new StalenessSignalStatus(
IsHealthy: !_sealedModeService.IsSealed, // Healthy if not sealed (anchor not required)
HasWarning: _sealedModeService.IsSealed,
IsBreach: false,
AgeSeconds: null,
RemainingSeconds: null,
Message: _sealedModeService.IsSealed ? "Time anchor not configured" : null);
}
var message = staleness.IsBreached
? $"Staleness breach: data is {staleness.AgeSeconds}s old (threshold: {staleness.BreachSeconds}s)"
: staleness.IsWarning
? $"Staleness warning: data is {staleness.AgeSeconds}s old (breach at: {staleness.BreachSeconds}s)"
: null;
return new StalenessSignalStatus(
IsHealthy: !staleness.IsBreached,
HasWarning: staleness.IsWarning,
IsBreach: staleness.IsBreached,
AgeSeconds: staleness.AgeSeconds,
RemainingSeconds: staleness.RemainingSeconds,
Message: message);
}
public Task<FallbackConfiguration> GetFallbackConfigurationAsync(string tenantId, CancellationToken cancellationToken = default)
{
// Default fallback configuration - could be extended to read from configuration
return Task.FromResult(new FallbackConfiguration(
Enabled: true,
Strategy: FallbackStrategy.LastKnownGood,
CacheTimeoutSeconds: 3600,
AllowDegradedOperation: true));
}
public async Task<bool> IsFallbackActiveAsync(string tenantId, CancellationToken cancellationToken = default)
{
var status = await GetSignalStatusAsync(tenantId, cancellationToken).ConfigureAwait(false);
var config = await GetFallbackConfigurationAsync(tenantId, cancellationToken).ConfigureAwait(false);
return config.Enabled && (status.IsBreach || status.HasWarning);
}
public async Task EvaluateAndSignalAsync(string tenantId, CancellationToken cancellationToken = default)
{
var staleness = await _sealedModeService.EvaluateStalenessAsync(tenantId, cancellationToken).ConfigureAwait(false);
var now = _timeProvider.GetUtcNow();
StalenessEventType? currentState = null;
string? message = null;
if (staleness is null && _sealedModeService.IsSealed)
{
currentState = StalenessEventType.AnchorMissing;
message = "Time anchor not configured in sealed mode";
}
else if (staleness?.IsBreached == true)
{
currentState = StalenessEventType.Breach;
message = $"Staleness breach: {staleness.AgeSeconds}s > {staleness.BreachSeconds}s";
}
else if (staleness?.IsWarning == true)
{
currentState = StalenessEventType.Warning;
message = $"Staleness warning: {staleness.AgeSeconds}s approaching {staleness.BreachSeconds}s";
}
// Only signal if state changed
lock (_stateLock)
{
_lastSignaledState.TryGetValue(tenantId, out var lastState);
if (currentState == lastState)
{
return; // No change
}
_lastSignaledState[tenantId] = currentState;
}
if (currentState.HasValue)
{
var evt = new StalenessEvent(
TenantId: tenantId,
Type: currentState.Value,
AgeSeconds: staleness?.AgeSeconds ?? 0,
ThresholdSeconds: staleness?.BreachSeconds ?? 0,
OccurredAt: now,
Message: message);
await RaiseEventAsync(evt, cancellationToken).ConfigureAwait(false);
// Record telemetry
PolicyEngineTelemetry.RecordStalenessEvent(tenantId, currentState.Value.ToString());
}
}
public async Task SignalRecoveryAsync(string tenantId, CancellationToken cancellationToken = default)
{
var now = _timeProvider.GetUtcNow();
lock (_stateLock)
{
_lastSignaledState.TryGetValue(tenantId, out var lastState);
if (lastState is null)
{
return; // Nothing to recover from
}
_lastSignaledState[tenantId] = null;
}
var evt = new StalenessEvent(
TenantId: tenantId,
Type: StalenessEventType.Recovered,
AgeSeconds: 0,
ThresholdSeconds: 0,
OccurredAt: now,
Message: "Time anchor refreshed, staleness recovered");
await RaiseEventAsync(evt, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Staleness recovered for tenant {TenantId}", tenantId);
}
private async Task RaiseEventAsync(StalenessEvent evt, CancellationToken cancellationToken)
{
_logger.LogInformation(
"Staleness event {EventType} for tenant {TenantId}: {Message}",
evt.Type, evt.TenantId, evt.Message);
foreach (var sink in _eventSinks)
{
try
{
await sink.OnStalenessEventAsync(evt, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to deliver staleness event to sink {SinkType}", sink.GetType().Name);
}
}
}
}
/// <summary>
/// Logging-based staleness event sink for observability.
/// </summary>
internal sealed class LoggingStalenessEventSink : IStalenessEventSink
{
private readonly ILogger<LoggingStalenessEventSink> _logger;
public LoggingStalenessEventSink(ILogger<LoggingStalenessEventSink> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public Task OnStalenessEventAsync(StalenessEvent evt, CancellationToken cancellationToken = default)
{
var logLevel = evt.Type switch
{
StalenessEventType.Breach => LogLevel.Error,
StalenessEventType.Warning => LogLevel.Warning,
StalenessEventType.AnchorMissing => LogLevel.Warning,
StalenessEventType.Recovered => LogLevel.Information,
_ => LogLevel.Information
};
_logger.Log(
logLevel,
"Staleness {EventType} for tenant {TenantId}: age={AgeSeconds}s, threshold={ThresholdSeconds}s - {Message}",
evt.Type,
evt.TenantId,
evt.AgeSeconds,
evt.ThresholdSeconds,
evt.Message);
return Task.CompletedTask;
}
}

View File

@@ -0,0 +1,178 @@
using System.Text.Json.Serialization;
namespace StellaOps.Policy.Engine.Attestation;
/// <summary>
/// Status of an attestation report section.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter<AttestationReportStatus>))]
public enum AttestationReportStatus
{
Pass,
Fail,
Warn,
Skipped,
Pending
}
/// <summary>
/// Aggregated attestation report for an artifact per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
public sealed record ArtifactAttestationReport(
[property: JsonPropertyName("artifact_digest")] string ArtifactDigest,
[property: JsonPropertyName("artifact_uri")] string? ArtifactUri,
[property: JsonPropertyName("overall_status")] AttestationReportStatus OverallStatus,
[property: JsonPropertyName("attestation_count")] int AttestationCount,
[property: JsonPropertyName("verification_results")] IReadOnlyList<AttestationVerificationSummary> VerificationResults,
[property: JsonPropertyName("policy_compliance")] PolicyComplianceSummary PolicyCompliance,
[property: JsonPropertyName("coverage")] AttestationCoverageSummary Coverage,
[property: JsonPropertyName("evaluated_at")] DateTimeOffset EvaluatedAt);
/// <summary>
/// Summary of a single attestation verification.
/// </summary>
public sealed record AttestationVerificationSummary(
[property: JsonPropertyName("attestation_id")] string AttestationId,
[property: JsonPropertyName("predicate_type")] string PredicateType,
[property: JsonPropertyName("status")] AttestationReportStatus Status,
[property: JsonPropertyName("policy_id")] string? PolicyId,
[property: JsonPropertyName("policy_version")] string? PolicyVersion,
[property: JsonPropertyName("signature_status")] SignatureVerificationStatus SignatureStatus,
[property: JsonPropertyName("freshness_status")] FreshnessVerificationStatus FreshnessStatus,
[property: JsonPropertyName("transparency_status")] TransparencyVerificationStatus TransparencyStatus,
[property: JsonPropertyName("issues")] IReadOnlyList<string> Issues,
[property: JsonPropertyName("created_at")] DateTimeOffset CreatedAt);
/// <summary>
/// Signature verification status.
/// </summary>
public sealed record SignatureVerificationStatus(
[property: JsonPropertyName("status")] AttestationReportStatus Status,
[property: JsonPropertyName("total_signatures")] int TotalSignatures,
[property: JsonPropertyName("verified_signatures")] int VerifiedSignatures,
[property: JsonPropertyName("required_signatures")] int RequiredSignatures,
[property: JsonPropertyName("signers")] IReadOnlyList<SignerVerificationInfo> Signers);
/// <summary>
/// Signer verification information.
/// </summary>
public sealed record SignerVerificationInfo(
[property: JsonPropertyName("key_fingerprint")] string KeyFingerprint,
[property: JsonPropertyName("issuer")] string? Issuer,
[property: JsonPropertyName("subject")] string? Subject,
[property: JsonPropertyName("algorithm")] string Algorithm,
[property: JsonPropertyName("verified")] bool Verified,
[property: JsonPropertyName("trusted")] bool Trusted);
/// <summary>
/// Freshness verification status.
/// </summary>
public sealed record FreshnessVerificationStatus(
[property: JsonPropertyName("status")] AttestationReportStatus Status,
[property: JsonPropertyName("created_at")] DateTimeOffset CreatedAt,
[property: JsonPropertyName("age_seconds")] int AgeSeconds,
[property: JsonPropertyName("max_age_seconds")] int? MaxAgeSeconds,
[property: JsonPropertyName("is_fresh")] bool IsFresh);
/// <summary>
/// Transparency log verification status.
/// </summary>
public sealed record TransparencyVerificationStatus(
[property: JsonPropertyName("status")] AttestationReportStatus Status,
[property: JsonPropertyName("rekor_entry")] RekorEntryInfo? RekorEntry,
[property: JsonPropertyName("inclusion_verified")] bool InclusionVerified);
/// <summary>
/// Rekor transparency log entry information.
/// </summary>
public sealed record RekorEntryInfo(
[property: JsonPropertyName("uuid")] string Uuid,
[property: JsonPropertyName("log_index")] long LogIndex,
[property: JsonPropertyName("log_url")] string? LogUrl,
[property: JsonPropertyName("integrated_time")] DateTimeOffset IntegratedTime);
/// <summary>
/// Summary of policy compliance for an artifact.
/// </summary>
public sealed record PolicyComplianceSummary(
[property: JsonPropertyName("status")] AttestationReportStatus Status,
[property: JsonPropertyName("policies_evaluated")] int PoliciesEvaluated,
[property: JsonPropertyName("policies_passed")] int PoliciesPassed,
[property: JsonPropertyName("policies_failed")] int PoliciesFailed,
[property: JsonPropertyName("policies_warned")] int PoliciesWarned,
[property: JsonPropertyName("policy_results")] IReadOnlyList<PolicyEvaluationSummary> PolicyResults);
/// <summary>
/// Summary of a policy evaluation.
/// </summary>
public sealed record PolicyEvaluationSummary(
[property: JsonPropertyName("policy_id")] string PolicyId,
[property: JsonPropertyName("policy_version")] string PolicyVersion,
[property: JsonPropertyName("status")] AttestationReportStatus Status,
[property: JsonPropertyName("verdict")] string Verdict,
[property: JsonPropertyName("issues")] IReadOnlyList<string> Issues);
/// <summary>
/// Summary of attestation coverage for an artifact.
/// </summary>
public sealed record AttestationCoverageSummary(
[property: JsonPropertyName("predicate_types_required")] IReadOnlyList<string> PredicateTypesRequired,
[property: JsonPropertyName("predicate_types_present")] IReadOnlyList<string> PredicateTypesPresent,
[property: JsonPropertyName("predicate_types_missing")] IReadOnlyList<string> PredicateTypesMissing,
[property: JsonPropertyName("coverage_percentage")] double CoveragePercentage,
[property: JsonPropertyName("is_complete")] bool IsComplete);
/// <summary>
/// Query options for attestation reports.
/// </summary>
public sealed record AttestationReportQuery(
[property: JsonPropertyName("artifact_digests")] IReadOnlyList<string>? ArtifactDigests,
[property: JsonPropertyName("artifact_uri_pattern")] string? ArtifactUriPattern,
[property: JsonPropertyName("policy_ids")] IReadOnlyList<string>? PolicyIds,
[property: JsonPropertyName("predicate_types")] IReadOnlyList<string>? PredicateTypes,
[property: JsonPropertyName("status_filter")] IReadOnlyList<AttestationReportStatus>? StatusFilter,
[property: JsonPropertyName("from_time")] DateTimeOffset? FromTime,
[property: JsonPropertyName("to_time")] DateTimeOffset? ToTime,
[property: JsonPropertyName("include_details")] bool IncludeDetails,
[property: JsonPropertyName("limit")] int Limit = 100,
[property: JsonPropertyName("offset")] int Offset = 0);
/// <summary>
/// Response containing attestation reports.
/// </summary>
public sealed record AttestationReportListResponse(
[property: JsonPropertyName("reports")] IReadOnlyList<ArtifactAttestationReport> Reports,
[property: JsonPropertyName("total")] int Total,
[property: JsonPropertyName("limit")] int Limit,
[property: JsonPropertyName("offset")] int Offset);
/// <summary>
/// Aggregated attestation statistics.
/// </summary>
public sealed record AttestationStatistics(
[property: JsonPropertyName("total_artifacts")] int TotalArtifacts,
[property: JsonPropertyName("total_attestations")] int TotalAttestations,
[property: JsonPropertyName("status_distribution")] IReadOnlyDictionary<AttestationReportStatus, int> StatusDistribution,
[property: JsonPropertyName("predicate_type_distribution")] IReadOnlyDictionary<string, int> PredicateTypeDistribution,
[property: JsonPropertyName("policy_distribution")] IReadOnlyDictionary<string, int> PolicyDistribution,
[property: JsonPropertyName("average_age_seconds")] double AverageAgeSeconds,
[property: JsonPropertyName("coverage_rate")] double CoverageRate,
[property: JsonPropertyName("evaluated_at")] DateTimeOffset EvaluatedAt);
/// <summary>
/// Request to verify attestations for an artifact.
/// </summary>
public sealed record VerifyArtifactRequest(
[property: JsonPropertyName("artifact_digest")] string ArtifactDigest,
[property: JsonPropertyName("artifact_uri")] string? ArtifactUri,
[property: JsonPropertyName("policy_ids")] IReadOnlyList<string>? PolicyIds,
[property: JsonPropertyName("include_transparency")] bool IncludeTransparency = true);
/// <summary>
/// Stored attestation report entry.
/// </summary>
public sealed record StoredAttestationReport(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("report")] ArtifactAttestationReport Report,
[property: JsonPropertyName("stored_at")] DateTimeOffset StoredAt,
[property: JsonPropertyName("expires_at")] DateTimeOffset? ExpiresAt);

View File

@@ -0,0 +1,394 @@
using Microsoft.Extensions.Logging;
namespace StellaOps.Policy.Engine.Attestation;
/// <summary>
/// Service for managing attestation reports per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
internal sealed class AttestationReportService : IAttestationReportService
{
private readonly IAttestationReportStore _store;
private readonly IVerificationPolicyStore _policyStore;
private readonly TimeProvider _timeProvider;
private readonly ILogger<AttestationReportService> _logger;
private static readonly TimeSpan DefaultTtl = TimeSpan.FromDays(7);
public AttestationReportService(
IAttestationReportStore store,
IVerificationPolicyStore policyStore,
TimeProvider timeProvider,
ILogger<AttestationReportService> logger)
{
_store = store ?? throw new ArgumentNullException(nameof(store));
_policyStore = policyStore ?? throw new ArgumentNullException(nameof(policyStore));
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<ArtifactAttestationReport?> GetReportAsync(string artifactDigest, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(artifactDigest);
var stored = await _store.GetAsync(artifactDigest, cancellationToken).ConfigureAwait(false);
if (stored == null)
{
return null;
}
// Check if expired
if (stored.ExpiresAt.HasValue && stored.ExpiresAt.Value <= _timeProvider.GetUtcNow())
{
_logger.LogDebug("Report for artifact {ArtifactDigest} has expired", artifactDigest);
return null;
}
return stored.Report;
}
public async Task<AttestationReportListResponse> ListReportsAsync(AttestationReportQuery query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
var reports = await _store.ListAsync(query, cancellationToken).ConfigureAwait(false);
var total = await _store.CountAsync(query, cancellationToken).ConfigureAwait(false);
var artifactReports = reports
.Where(r => !r.ExpiresAt.HasValue || r.ExpiresAt.Value > _timeProvider.GetUtcNow())
.Select(r => r.Report)
.ToList();
return new AttestationReportListResponse(
Reports: artifactReports,
Total: total,
Limit: query.Limit,
Offset: query.Offset);
}
public async Task<ArtifactAttestationReport> GenerateReportAsync(VerifyArtifactRequest request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentException.ThrowIfNullOrWhiteSpace(request.ArtifactDigest);
var now = _timeProvider.GetUtcNow();
// Get applicable policies
var policies = await GetApplicablePoliciesAsync(request.PolicyIds, cancellationToken).ConfigureAwait(false);
// Generate verification results (simulated - would connect to actual Attestor service)
var verificationResults = await GenerateVerificationResultsAsync(request, policies, now, cancellationToken).ConfigureAwait(false);
// Calculate policy compliance
var policyCompliance = CalculatePolicyCompliance(policies, verificationResults);
// Calculate coverage
var coverage = CalculateCoverage(policies, verificationResults);
// Determine overall status
var overallStatus = DetermineOverallStatus(verificationResults, policyCompliance);
var report = new ArtifactAttestationReport(
ArtifactDigest: request.ArtifactDigest,
ArtifactUri: request.ArtifactUri,
OverallStatus: overallStatus,
AttestationCount: verificationResults.Count,
VerificationResults: verificationResults,
PolicyCompliance: policyCompliance,
Coverage: coverage,
EvaluatedAt: now);
_logger.LogInformation(
"Generated attestation report for artifact {ArtifactDigest} with status {Status}",
request.ArtifactDigest,
overallStatus);
return report;
}
public async Task<StoredAttestationReport> StoreReportAsync(ArtifactAttestationReport report, TimeSpan? ttl = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(report);
var now = _timeProvider.GetUtcNow();
var expiresAt = now.Add(ttl ?? DefaultTtl);
var storedReport = new StoredAttestationReport(
Id: $"report-{report.ArtifactDigest}-{now.Ticks}",
Report: report,
StoredAt: now,
ExpiresAt: expiresAt);
await _store.CreateAsync(storedReport, cancellationToken).ConfigureAwait(false);
_logger.LogDebug(
"Stored attestation report for artifact {ArtifactDigest}, expires at {ExpiresAt}",
report.ArtifactDigest,
expiresAt);
return storedReport;
}
public async Task<AttestationStatistics> GetStatisticsAsync(AttestationReportQuery? filter = null, CancellationToken cancellationToken = default)
{
var query = filter ?? new AttestationReportQuery(
ArtifactDigests: null,
ArtifactUriPattern: null,
PolicyIds: null,
PredicateTypes: null,
StatusFilter: null,
FromTime: null,
ToTime: null,
IncludeDetails: false,
Limit: int.MaxValue,
Offset: 0);
var reports = await _store.ListAsync(query, cancellationToken).ConfigureAwait(false);
var now = _timeProvider.GetUtcNow();
// Filter expired
var validReports = reports
.Where(r => !r.ExpiresAt.HasValue || r.ExpiresAt.Value > now)
.ToList();
var statusDistribution = validReports
.GroupBy(r => r.Report.OverallStatus)
.ToDictionary(g => g.Key, g => g.Count());
var predicateTypeDistribution = validReports
.SelectMany(r => r.Report.VerificationResults)
.GroupBy(v => v.PredicateType)
.ToDictionary(g => g.Key, g => g.Count());
var policyDistribution = validReports
.SelectMany(r => r.Report.VerificationResults)
.Where(v => v.PolicyId != null)
.GroupBy(v => v.PolicyId!)
.ToDictionary(g => g.Key, g => g.Count());
var totalAttestations = validReports.Sum(r => r.Report.AttestationCount);
var averageAgeSeconds = validReports.Count > 0
? validReports.Average(r => (now - r.Report.EvaluatedAt).TotalSeconds)
: 0;
var coverageRate = validReports.Count > 0
? validReports.Average(r => r.Report.Coverage.CoveragePercentage)
: 0;
return new AttestationStatistics(
TotalArtifacts: validReports.Count,
TotalAttestations: totalAttestations,
StatusDistribution: statusDistribution,
PredicateTypeDistribution: predicateTypeDistribution,
PolicyDistribution: policyDistribution,
AverageAgeSeconds: averageAgeSeconds,
CoverageRate: coverageRate,
EvaluatedAt: now);
}
public async Task<int> PurgeExpiredReportsAsync(CancellationToken cancellationToken = default)
{
var now = _timeProvider.GetUtcNow();
var count = await _store.DeleteExpiredAsync(now, cancellationToken).ConfigureAwait(false);
if (count > 0)
{
_logger.LogInformation("Purged {Count} expired attestation reports", count);
}
return count;
}
private async Task<IReadOnlyList<VerificationPolicy>> GetApplicablePoliciesAsync(
IReadOnlyList<string>? policyIds,
CancellationToken cancellationToken)
{
if (policyIds is { Count: > 0 })
{
var policies = new List<VerificationPolicy>();
foreach (var policyId in policyIds)
{
var policy = await _policyStore.GetAsync(policyId, cancellationToken).ConfigureAwait(false);
if (policy != null)
{
policies.Add(policy);
}
}
return policies;
}
// Get all policies if none specified
return await _policyStore.ListAsync(null, cancellationToken).ConfigureAwait(false);
}
private Task<IReadOnlyList<AttestationVerificationSummary>> GenerateVerificationResultsAsync(
VerifyArtifactRequest request,
IReadOnlyList<VerificationPolicy> policies,
DateTimeOffset now,
CancellationToken cancellationToken)
{
// This would normally connect to the Attestor service to verify actual attestations
// For now, generate placeholder results based on policies
var results = new List<AttestationVerificationSummary>();
foreach (var policy in policies)
{
foreach (var predicateType in policy.PredicateTypes)
{
// Simulated verification result
results.Add(new AttestationVerificationSummary(
AttestationId: $"attest-{Guid.NewGuid():N}",
PredicateType: predicateType,
Status: AttestationReportStatus.Pending,
PolicyId: policy.PolicyId,
PolicyVersion: policy.Version,
SignatureStatus: new SignatureVerificationStatus(
Status: AttestationReportStatus.Pending,
TotalSignatures: 0,
VerifiedSignatures: 0,
RequiredSignatures: policy.SignerRequirements.MinimumSignatures,
Signers: []),
FreshnessStatus: new FreshnessVerificationStatus(
Status: AttestationReportStatus.Pending,
CreatedAt: now,
AgeSeconds: 0,
MaxAgeSeconds: policy.ValidityWindow?.MaxAttestationAge,
IsFresh: true),
TransparencyStatus: new TransparencyVerificationStatus(
Status: policy.SignerRequirements.RequireRekor
? AttestationReportStatus.Pending
: AttestationReportStatus.Skipped,
RekorEntry: null,
InclusionVerified: false),
Issues: [],
CreatedAt: now));
}
}
return Task.FromResult<IReadOnlyList<AttestationVerificationSummary>>(results);
}
private static PolicyComplianceSummary CalculatePolicyCompliance(
IReadOnlyList<VerificationPolicy> policies,
IReadOnlyList<AttestationVerificationSummary> results)
{
var policyResults = new List<PolicyEvaluationSummary>();
var passed = 0;
var failed = 0;
var warned = 0;
foreach (var policy in policies)
{
var policyVerifications = results.Where(r => r.PolicyId == policy.PolicyId).ToList();
var status = AttestationReportStatus.Pending;
var verdict = "pending";
var issues = new List<string>();
if (policyVerifications.All(v => v.Status == AttestationReportStatus.Pass))
{
status = AttestationReportStatus.Pass;
verdict = "compliant";
passed++;
}
else if (policyVerifications.Any(v => v.Status == AttestationReportStatus.Fail))
{
status = AttestationReportStatus.Fail;
verdict = "non-compliant";
failed++;
issues.AddRange(policyVerifications.SelectMany(v => v.Issues));
}
else if (policyVerifications.Any(v => v.Status == AttestationReportStatus.Warn))
{
status = AttestationReportStatus.Warn;
verdict = "warning";
warned++;
}
policyResults.Add(new PolicyEvaluationSummary(
PolicyId: policy.PolicyId,
PolicyVersion: policy.Version,
Status: status,
Verdict: verdict,
Issues: issues));
}
var overallStatus = failed > 0
? AttestationReportStatus.Fail
: warned > 0
? AttestationReportStatus.Warn
: passed > 0
? AttestationReportStatus.Pass
: AttestationReportStatus.Pending;
return new PolicyComplianceSummary(
Status: overallStatus,
PoliciesEvaluated: policies.Count,
PoliciesPassed: passed,
PoliciesFailed: failed,
PoliciesWarned: warned,
PolicyResults: policyResults);
}
private static AttestationCoverageSummary CalculateCoverage(
IReadOnlyList<VerificationPolicy> policies,
IReadOnlyList<AttestationVerificationSummary> results)
{
var requiredTypes = policies
.SelectMany(p => p.PredicateTypes)
.Distinct()
.ToList();
var presentTypes = results
.Select(r => r.PredicateType)
.Distinct()
.ToList();
var missingTypes = requiredTypes.Except(presentTypes).ToList();
var coveragePercentage = requiredTypes.Count > 0
? (double)(requiredTypes.Count - missingTypes.Count) / requiredTypes.Count * 100
: 100;
return new AttestationCoverageSummary(
PredicateTypesRequired: requiredTypes,
PredicateTypesPresent: presentTypes,
PredicateTypesMissing: missingTypes,
CoveragePercentage: Math.Round(coveragePercentage, 2),
IsComplete: missingTypes.Count == 0);
}
private static AttestationReportStatus DetermineOverallStatus(
IReadOnlyList<AttestationVerificationSummary> results,
PolicyComplianceSummary compliance)
{
if (compliance.Status == AttestationReportStatus.Fail)
{
return AttestationReportStatus.Fail;
}
if (results.Any(r => r.Status == AttestationReportStatus.Fail))
{
return AttestationReportStatus.Fail;
}
if (compliance.Status == AttestationReportStatus.Warn ||
results.Any(r => r.Status == AttestationReportStatus.Warn))
{
return AttestationReportStatus.Warn;
}
if (results.All(r => r.Status == AttestationReportStatus.Pass))
{
return AttestationReportStatus.Pass;
}
if (results.All(r => r.Status == AttestationReportStatus.Pending))
{
return AttestationReportStatus.Pending;
}
return AttestationReportStatus.Skipped;
}
}

View File

@@ -0,0 +1,97 @@
namespace StellaOps.Policy.Engine.Attestation;
/// <summary>
/// Service for managing and querying attestation reports per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
public interface IAttestationReportService
{
/// <summary>
/// Gets an attestation report for a specific artifact.
/// </summary>
Task<ArtifactAttestationReport?> GetReportAsync(
string artifactDigest,
CancellationToken cancellationToken = default);
/// <summary>
/// Lists attestation reports matching the query.
/// </summary>
Task<AttestationReportListResponse> ListReportsAsync(
AttestationReportQuery query,
CancellationToken cancellationToken = default);
/// <summary>
/// Generates an attestation report for an artifact by verifying its attestations.
/// </summary>
Task<ArtifactAttestationReport> GenerateReportAsync(
VerifyArtifactRequest request,
CancellationToken cancellationToken = default);
/// <summary>
/// Stores an attestation report.
/// </summary>
Task<StoredAttestationReport> StoreReportAsync(
ArtifactAttestationReport report,
TimeSpan? ttl = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Gets aggregated attestation statistics.
/// </summary>
Task<AttestationStatistics> GetStatisticsAsync(
AttestationReportQuery? filter = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Deletes expired attestation reports.
/// </summary>
Task<int> PurgeExpiredReportsAsync(CancellationToken cancellationToken = default);
}
/// <summary>
/// Store for persisting attestation reports.
/// </summary>
public interface IAttestationReportStore
{
/// <summary>
/// Gets a stored report by artifact digest.
/// </summary>
Task<StoredAttestationReport?> GetAsync(
string artifactDigest,
CancellationToken cancellationToken = default);
/// <summary>
/// Lists stored reports matching the query.
/// </summary>
Task<IReadOnlyList<StoredAttestationReport>> ListAsync(
AttestationReportQuery query,
CancellationToken cancellationToken = default);
/// <summary>
/// Counts stored reports matching the query.
/// </summary>
Task<int> CountAsync(
AttestationReportQuery? query = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Stores a report.
/// </summary>
Task<StoredAttestationReport> CreateAsync(
StoredAttestationReport report,
CancellationToken cancellationToken = default);
/// <summary>
/// Updates a stored report.
/// </summary>
Task<StoredAttestationReport?> UpdateAsync(
string artifactDigest,
Func<StoredAttestationReport, StoredAttestationReport> update,
CancellationToken cancellationToken = default);
/// <summary>
/// Deletes expired reports.
/// </summary>
Task<int> DeleteExpiredAsync(
DateTimeOffset now,
CancellationToken cancellationToken = default);
}

View File

@@ -0,0 +1,44 @@
namespace StellaOps.Policy.Engine.Attestation;
/// <summary>
/// Interface for persisting verification policies per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
public interface IVerificationPolicyStore
{
/// <summary>
/// Gets a policy by ID.
/// </summary>
Task<VerificationPolicy?> GetAsync(string policyId, CancellationToken cancellationToken = default);
/// <summary>
/// Gets all policies for a tenant scope.
/// </summary>
Task<IReadOnlyList<VerificationPolicy>> ListAsync(
string? tenantScope = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Creates a new policy.
/// </summary>
Task<VerificationPolicy> CreateAsync(
VerificationPolicy policy,
CancellationToken cancellationToken = default);
/// <summary>
/// Updates an existing policy.
/// </summary>
Task<VerificationPolicy?> UpdateAsync(
string policyId,
Func<VerificationPolicy, VerificationPolicy> update,
CancellationToken cancellationToken = default);
/// <summary>
/// Deletes a policy.
/// </summary>
Task<bool> DeleteAsync(string policyId, CancellationToken cancellationToken = default);
/// <summary>
/// Checks if a policy exists.
/// </summary>
Task<bool> ExistsAsync(string policyId, CancellationToken cancellationToken = default);
}

View File

@@ -0,0 +1,188 @@
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
namespace StellaOps.Policy.Engine.Attestation;
/// <summary>
/// In-memory implementation of attestation report store per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
internal sealed class InMemoryAttestationReportStore : IAttestationReportStore
{
private readonly ConcurrentDictionary<string, StoredAttestationReport> _reports = new(StringComparer.OrdinalIgnoreCase);
public Task<StoredAttestationReport?> GetAsync(string artifactDigest, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(artifactDigest);
_reports.TryGetValue(artifactDigest, out var report);
return Task.FromResult(report);
}
public Task<IReadOnlyList<StoredAttestationReport>> ListAsync(AttestationReportQuery query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
IEnumerable<StoredAttestationReport> reports = _reports.Values;
// Filter by artifact digests
if (query.ArtifactDigests is { Count: > 0 })
{
var digestSet = query.ArtifactDigests.ToHashSet(StringComparer.OrdinalIgnoreCase);
reports = reports.Where(r => digestSet.Contains(r.Report.ArtifactDigest));
}
// Filter by artifact URI pattern
if (!string.IsNullOrWhiteSpace(query.ArtifactUriPattern))
{
var pattern = new Regex(query.ArtifactUriPattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
reports = reports.Where(r => r.Report.ArtifactUri != null && pattern.IsMatch(r.Report.ArtifactUri));
}
// Filter by policy IDs
if (query.PolicyIds is { Count: > 0 })
{
var policySet = query.PolicyIds.ToHashSet(StringComparer.OrdinalIgnoreCase);
reports = reports.Where(r =>
r.Report.VerificationResults.Any(v =>
v.PolicyId != null && policySet.Contains(v.PolicyId)));
}
// Filter by predicate types
if (query.PredicateTypes is { Count: > 0 })
{
var predicateSet = query.PredicateTypes.ToHashSet(StringComparer.Ordinal);
reports = reports.Where(r =>
r.Report.VerificationResults.Any(v => predicateSet.Contains(v.PredicateType)));
}
// Filter by status
if (query.StatusFilter is { Count: > 0 })
{
var statusSet = query.StatusFilter.ToHashSet();
reports = reports.Where(r => statusSet.Contains(r.Report.OverallStatus));
}
// Filter by time range
if (query.FromTime.HasValue)
{
reports = reports.Where(r => r.Report.EvaluatedAt >= query.FromTime.Value);
}
if (query.ToTime.HasValue)
{
reports = reports.Where(r => r.Report.EvaluatedAt <= query.ToTime.Value);
}
// Order by evaluated time descending
var result = reports
.OrderByDescending(r => r.Report.EvaluatedAt)
.Skip(query.Offset)
.Take(query.Limit)
.ToList() as IReadOnlyList<StoredAttestationReport>;
return Task.FromResult(result);
}
public Task<int> CountAsync(AttestationReportQuery? query = null, CancellationToken cancellationToken = default)
{
if (query == null)
{
return Task.FromResult(_reports.Count);
}
IEnumerable<StoredAttestationReport> reports = _reports.Values;
// Apply same filters as ListAsync but only count
if (query.ArtifactDigests is { Count: > 0 })
{
var digestSet = query.ArtifactDigests.ToHashSet(StringComparer.OrdinalIgnoreCase);
reports = reports.Where(r => digestSet.Contains(r.Report.ArtifactDigest));
}
if (!string.IsNullOrWhiteSpace(query.ArtifactUriPattern))
{
var pattern = new Regex(query.ArtifactUriPattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
reports = reports.Where(r => r.Report.ArtifactUri != null && pattern.IsMatch(r.Report.ArtifactUri));
}
if (query.PolicyIds is { Count: > 0 })
{
var policySet = query.PolicyIds.ToHashSet(StringComparer.OrdinalIgnoreCase);
reports = reports.Where(r =>
r.Report.VerificationResults.Any(v =>
v.PolicyId != null && policySet.Contains(v.PolicyId)));
}
if (query.PredicateTypes is { Count: > 0 })
{
var predicateSet = query.PredicateTypes.ToHashSet(StringComparer.Ordinal);
reports = reports.Where(r =>
r.Report.VerificationResults.Any(v => predicateSet.Contains(v.PredicateType)));
}
if (query.StatusFilter is { Count: > 0 })
{
var statusSet = query.StatusFilter.ToHashSet();
reports = reports.Where(r => statusSet.Contains(r.Report.OverallStatus));
}
if (query.FromTime.HasValue)
{
reports = reports.Where(r => r.Report.EvaluatedAt >= query.FromTime.Value);
}
if (query.ToTime.HasValue)
{
reports = reports.Where(r => r.Report.EvaluatedAt <= query.ToTime.Value);
}
return Task.FromResult(reports.Count());
}
public Task<StoredAttestationReport> CreateAsync(StoredAttestationReport report, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(report);
// Upsert behavior - replace if exists
_reports[report.Report.ArtifactDigest] = report;
return Task.FromResult(report);
}
public Task<StoredAttestationReport?> UpdateAsync(
string artifactDigest,
Func<StoredAttestationReport, StoredAttestationReport> update,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(artifactDigest);
ArgumentNullException.ThrowIfNull(update);
if (!_reports.TryGetValue(artifactDigest, out var existing))
{
return Task.FromResult<StoredAttestationReport?>(null);
}
var updated = update(existing);
_reports[artifactDigest] = updated;
return Task.FromResult<StoredAttestationReport?>(updated);
}
public Task<int> DeleteExpiredAsync(DateTimeOffset now, CancellationToken cancellationToken = default)
{
var expired = _reports.Values
.Where(r => r.ExpiresAt.HasValue && r.ExpiresAt.Value <= now)
.Select(r => r.Report.ArtifactDigest)
.ToList();
var count = 0;
foreach (var digest in expired)
{
if (_reports.TryRemove(digest, out _))
{
count++;
}
}
return Task.FromResult(count);
}
}

View File

@@ -0,0 +1,86 @@
using System.Collections.Concurrent;
namespace StellaOps.Policy.Engine.Attestation;
/// <summary>
/// In-memory implementation of verification policy store per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
internal sealed class InMemoryVerificationPolicyStore : IVerificationPolicyStore
{
private readonly ConcurrentDictionary<string, VerificationPolicy> _policies = new(StringComparer.OrdinalIgnoreCase);
public Task<VerificationPolicy?> GetAsync(string policyId, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(policyId);
_policies.TryGetValue(policyId, out var policy);
return Task.FromResult(policy);
}
public Task<IReadOnlyList<VerificationPolicy>> ListAsync(
string? tenantScope = null,
CancellationToken cancellationToken = default)
{
IEnumerable<VerificationPolicy> policies = _policies.Values;
if (!string.IsNullOrWhiteSpace(tenantScope))
{
policies = policies.Where(p =>
p.TenantScope == "*" ||
p.TenantScope.Equals(tenantScope, StringComparison.OrdinalIgnoreCase));
}
var result = policies
.OrderBy(p => p.PolicyId)
.ToList() as IReadOnlyList<VerificationPolicy>;
return Task.FromResult(result);
}
public Task<VerificationPolicy> CreateAsync(
VerificationPolicy policy,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(policy);
if (!_policies.TryAdd(policy.PolicyId, policy))
{
throw new InvalidOperationException($"Policy '{policy.PolicyId}' already exists.");
}
return Task.FromResult(policy);
}
public Task<VerificationPolicy?> UpdateAsync(
string policyId,
Func<VerificationPolicy, VerificationPolicy> update,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(policyId);
ArgumentNullException.ThrowIfNull(update);
if (!_policies.TryGetValue(policyId, out var existing))
{
return Task.FromResult<VerificationPolicy?>(null);
}
var updated = update(existing);
_policies[policyId] = updated;
return Task.FromResult<VerificationPolicy?>(updated);
}
public Task<bool> DeleteAsync(string policyId, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(policyId);
return Task.FromResult(_policies.TryRemove(policyId, out _));
}
public Task<bool> ExistsAsync(string policyId, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(policyId);
return Task.FromResult(_policies.ContainsKey(policyId));
}
}

View File

@@ -0,0 +1,264 @@
using System.Text.Json.Serialization;
namespace StellaOps.Policy.Engine.Attestation;
/// <summary>
/// Editor metadata for verification policy forms per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
public sealed record VerificationPolicyEditorMetadata(
[property: JsonPropertyName("available_predicate_types")] IReadOnlyList<PredicateTypeInfo> AvailablePredicateTypes,
[property: JsonPropertyName("available_algorithms")] IReadOnlyList<AlgorithmInfo> AvailableAlgorithms,
[property: JsonPropertyName("default_signer_requirements")] SignerRequirements DefaultSignerRequirements,
[property: JsonPropertyName("validation_constraints")] ValidationConstraintsInfo ValidationConstraints);
/// <summary>
/// Information about a predicate type for editor dropdowns.
/// </summary>
public sealed record PredicateTypeInfo(
[property: JsonPropertyName("type")] string Type,
[property: JsonPropertyName("name")] string Name,
[property: JsonPropertyName("description")] string Description,
[property: JsonPropertyName("category")] PredicateCategory Category,
[property: JsonPropertyName("is_default")] bool IsDefault);
/// <summary>
/// Category of predicate type.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter<PredicateCategory>))]
public enum PredicateCategory
{
StellaOps,
Slsa,
Sbom,
Vex
}
/// <summary>
/// Information about a signing algorithm for editor dropdowns.
/// </summary>
public sealed record AlgorithmInfo(
[property: JsonPropertyName("algorithm")] string Algorithm,
[property: JsonPropertyName("name")] string Name,
[property: JsonPropertyName("description")] string Description,
[property: JsonPropertyName("key_type")] string KeyType,
[property: JsonPropertyName("is_recommended")] bool IsRecommended);
/// <summary>
/// Validation constraints exposed to the editor.
/// </summary>
public sealed record ValidationConstraintsInfo(
[property: JsonPropertyName("max_policy_id_length")] int MaxPolicyIdLength,
[property: JsonPropertyName("max_version_length")] int MaxVersionLength,
[property: JsonPropertyName("max_description_length")] int MaxDescriptionLength,
[property: JsonPropertyName("max_predicate_types")] int MaxPredicateTypes,
[property: JsonPropertyName("max_trusted_key_fingerprints")] int MaxTrustedKeyFingerprints,
[property: JsonPropertyName("max_trusted_issuers")] int MaxTrustedIssuers,
[property: JsonPropertyName("max_algorithms")] int MaxAlgorithms,
[property: JsonPropertyName("max_metadata_entries")] int MaxMetadataEntries,
[property: JsonPropertyName("max_attestation_age_seconds")] int MaxAttestationAgeSeconds);
/// <summary>
/// Editor view of a verification policy with validation state.
/// </summary>
public sealed record VerificationPolicyEditorView(
[property: JsonPropertyName("policy")] VerificationPolicy Policy,
[property: JsonPropertyName("validation")] VerificationPolicyValidationResult Validation,
[property: JsonPropertyName("suggestions")] IReadOnlyList<PolicySuggestion>? Suggestions,
[property: JsonPropertyName("can_delete")] bool CanDelete,
[property: JsonPropertyName("is_referenced")] bool IsReferenced);
/// <summary>
/// Suggestion for policy improvement.
/// </summary>
public sealed record PolicySuggestion(
[property: JsonPropertyName("code")] string Code,
[property: JsonPropertyName("field")] string Field,
[property: JsonPropertyName("message")] string Message,
[property: JsonPropertyName("suggested_value")] object? SuggestedValue);
/// <summary>
/// Request to validate a verification policy without persisting.
/// </summary>
public sealed record ValidatePolicyRequest(
[property: JsonPropertyName("policy_id")] string? PolicyId,
[property: JsonPropertyName("version")] string? Version,
[property: JsonPropertyName("description")] string? Description,
[property: JsonPropertyName("tenant_scope")] string? TenantScope,
[property: JsonPropertyName("predicate_types")] IReadOnlyList<string>? PredicateTypes,
[property: JsonPropertyName("signer_requirements")] SignerRequirements? SignerRequirements,
[property: JsonPropertyName("validity_window")] ValidityWindow? ValidityWindow,
[property: JsonPropertyName("metadata")] IReadOnlyDictionary<string, object?>? Metadata);
/// <summary>
/// Response from policy validation.
/// </summary>
public sealed record ValidatePolicyResponse(
[property: JsonPropertyName("valid")] bool Valid,
[property: JsonPropertyName("errors")] IReadOnlyList<VerificationPolicyValidationError> Errors,
[property: JsonPropertyName("warnings")] IReadOnlyList<VerificationPolicyValidationError> Warnings,
[property: JsonPropertyName("suggestions")] IReadOnlyList<PolicySuggestion> Suggestions);
/// <summary>
/// Request to clone a verification policy.
/// </summary>
public sealed record ClonePolicyRequest(
[property: JsonPropertyName("source_policy_id")] string SourcePolicyId,
[property: JsonPropertyName("new_policy_id")] string NewPolicyId,
[property: JsonPropertyName("new_version")] string? NewVersion);
/// <summary>
/// Request to compare two verification policies.
/// </summary>
public sealed record ComparePoliciesRequest(
[property: JsonPropertyName("policy_id_a")] string PolicyIdA,
[property: JsonPropertyName("policy_id_b")] string PolicyIdB);
/// <summary>
/// Result of comparing two verification policies.
/// </summary>
public sealed record ComparePoliciesResponse(
[property: JsonPropertyName("policy_a")] VerificationPolicy PolicyA,
[property: JsonPropertyName("policy_b")] VerificationPolicy PolicyB,
[property: JsonPropertyName("differences")] IReadOnlyList<PolicyDifference> Differences);
/// <summary>
/// A difference between two policies.
/// </summary>
public sealed record PolicyDifference(
[property: JsonPropertyName("field")] string Field,
[property: JsonPropertyName("value_a")] object? ValueA,
[property: JsonPropertyName("value_b")] object? ValueB,
[property: JsonPropertyName("change_type")] DifferenceType ChangeType);
/// <summary>
/// Type of difference between policies.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter<DifferenceType>))]
public enum DifferenceType
{
Added,
Removed,
Modified
}
/// <summary>
/// Provider of editor metadata for verification policies.
/// </summary>
public static class VerificationPolicyEditorMetadataProvider
{
private static readonly IReadOnlyList<PredicateTypeInfo> AvailablePredicateTypes =
[
// StellaOps types
new(PredicateTypes.SbomV1, "StellaOps SBOM", "Software Bill of Materials attestation", PredicateCategory.StellaOps, true),
new(PredicateTypes.VexV1, "StellaOps VEX", "Vulnerability Exploitability Exchange attestation", PredicateCategory.StellaOps, true),
new(PredicateTypes.VexDecisionV1, "StellaOps VEX Decision", "VEX decision record attestation", PredicateCategory.StellaOps, false),
new(PredicateTypes.PolicyV1, "StellaOps Policy", "Policy decision attestation", PredicateCategory.StellaOps, false),
new(PredicateTypes.PromotionV1, "StellaOps Promotion", "Artifact promotion attestation", PredicateCategory.StellaOps, false),
new(PredicateTypes.EvidenceV1, "StellaOps Evidence", "Evidence collection attestation", PredicateCategory.StellaOps, false),
new(PredicateTypes.GraphV1, "StellaOps Graph", "Dependency graph attestation", PredicateCategory.StellaOps, false),
new(PredicateTypes.ReplayV1, "StellaOps Replay", "Replay verification attestation", PredicateCategory.StellaOps, false),
// SLSA types
new(PredicateTypes.SlsaProvenanceV1, "SLSA Provenance v1", "SLSA v1.0 provenance attestation", PredicateCategory.Slsa, true),
new(PredicateTypes.SlsaProvenanceV02, "SLSA Provenance v0.2", "SLSA v0.2 provenance attestation (legacy)", PredicateCategory.Slsa, false),
// SBOM types
new(PredicateTypes.CycloneDxBom, "CycloneDX BOM", "CycloneDX Bill of Materials", PredicateCategory.Sbom, true),
new(PredicateTypes.SpdxDocument, "SPDX Document", "SPDX SBOM document", PredicateCategory.Sbom, true),
// VEX types
new(PredicateTypes.OpenVex, "OpenVEX", "OpenVEX vulnerability exchange", PredicateCategory.Vex, true)
];
private static readonly IReadOnlyList<AlgorithmInfo> AvailableAlgorithms =
[
new("ES256", "ECDSA P-256", "ECDSA with SHA-256 and P-256 curve", "EC", true),
new("ES384", "ECDSA P-384", "ECDSA with SHA-384 and P-384 curve", "EC", false),
new("ES512", "ECDSA P-521", "ECDSA with SHA-512 and P-521 curve", "EC", false),
new("RS256", "RSA-SHA256", "RSA with SHA-256", "RSA", true),
new("RS384", "RSA-SHA384", "RSA with SHA-384", "RSA", false),
new("RS512", "RSA-SHA512", "RSA with SHA-512", "RSA", false),
new("PS256", "RSA-PSS-SHA256", "RSA-PSS with SHA-256", "RSA", false),
new("PS384", "RSA-PSS-SHA384", "RSA-PSS with SHA-384", "RSA", false),
new("PS512", "RSA-PSS-SHA512", "RSA-PSS with SHA-512", "RSA", false),
new("EdDSA", "EdDSA", "Edwards-curve Digital Signature Algorithm (Ed25519)", "OKP", true)
];
/// <summary>
/// Gets the editor metadata for verification policy forms.
/// </summary>
public static VerificationPolicyEditorMetadata GetMetadata(
VerificationPolicyValidationConstraints? constraints = null)
{
var c = constraints ?? VerificationPolicyValidationConstraints.Default;
return new VerificationPolicyEditorMetadata(
AvailablePredicateTypes: AvailablePredicateTypes,
AvailableAlgorithms: AvailableAlgorithms,
DefaultSignerRequirements: SignerRequirements.Default,
ValidationConstraints: new ValidationConstraintsInfo(
MaxPolicyIdLength: c.MaxPolicyIdLength,
MaxVersionLength: c.MaxVersionLength,
MaxDescriptionLength: c.MaxDescriptionLength,
MaxPredicateTypes: c.MaxPredicateTypes,
MaxTrustedKeyFingerprints: c.MaxTrustedKeyFingerprints,
MaxTrustedIssuers: c.MaxTrustedIssuers,
MaxAlgorithms: c.MaxAlgorithms,
MaxMetadataEntries: c.MaxMetadataEntries,
MaxAttestationAgeSeconds: c.MaxAttestationAgeSeconds));
}
/// <summary>
/// Generates suggestions for a policy based on validation results.
/// </summary>
public static IReadOnlyList<PolicySuggestion> GenerateSuggestions(
CreateVerificationPolicyRequest request,
VerificationPolicyValidationResult validation)
{
var suggestions = new List<PolicySuggestion>();
// Suggest adding Rekor if not enabled
if (request.SignerRequirements is { RequireRekor: false })
{
suggestions.Add(new PolicySuggestion(
"SUG_VP_001",
"signer_requirements.require_rekor",
"Consider enabling Rekor for transparency log verification.",
true));
}
// Suggest adding trusted key fingerprints if empty
if (request.SignerRequirements is { TrustedKeyFingerprints.Count: 0 })
{
suggestions.Add(new PolicySuggestion(
"SUG_VP_002",
"signer_requirements.trusted_key_fingerprints",
"Consider adding trusted key fingerprints to restrict accepted signers.",
null));
}
// Suggest adding validity window if not set
if (request.ValidityWindow == null)
{
suggestions.Add(new PolicySuggestion(
"SUG_VP_003",
"validity_window",
"Consider setting a validity window to limit attestation age.",
new ValidityWindow(null, null, 2592000))); // 30 days default
}
// Suggest EdDSA if only RSA algorithms are selected
if (request.SignerRequirements?.Algorithms != null &&
request.SignerRequirements.Algorithms.All(a => a.StartsWith("RS", StringComparison.OrdinalIgnoreCase) ||
a.StartsWith("PS", StringComparison.OrdinalIgnoreCase)))
{
suggestions.Add(new PolicySuggestion(
"SUG_VP_004",
"signer_requirements.algorithms",
"Consider adding ES256 or EdDSA for better performance and smaller signatures.",
null));
}
return suggestions;
}
}

View File

@@ -0,0 +1,136 @@
using System.Text.Json.Serialization;
namespace StellaOps.Policy.Engine.Attestation;
/// <summary>
/// Verification policy for attestation validation per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
public sealed record VerificationPolicy(
[property: JsonPropertyName("policy_id")] string PolicyId,
[property: JsonPropertyName("version")] string Version,
[property: JsonPropertyName("description")] string? Description,
[property: JsonPropertyName("tenant_scope")] string TenantScope,
[property: JsonPropertyName("predicate_types")] IReadOnlyList<string> PredicateTypes,
[property: JsonPropertyName("signer_requirements")] SignerRequirements SignerRequirements,
[property: JsonPropertyName("validity_window")] ValidityWindow? ValidityWindow,
[property: JsonPropertyName("metadata")] IReadOnlyDictionary<string, object?>? Metadata,
[property: JsonPropertyName("created_at")] DateTimeOffset CreatedAt,
[property: JsonPropertyName("updated_at")] DateTimeOffset UpdatedAt);
/// <summary>
/// Signer requirements for attestation verification.
/// </summary>
public sealed record SignerRequirements(
[property: JsonPropertyName("minimum_signatures")] int MinimumSignatures,
[property: JsonPropertyName("trusted_key_fingerprints")] IReadOnlyList<string> TrustedKeyFingerprints,
[property: JsonPropertyName("trusted_issuers")] IReadOnlyList<string>? TrustedIssuers,
[property: JsonPropertyName("require_rekor")] bool RequireRekor,
[property: JsonPropertyName("algorithms")] IReadOnlyList<string>? Algorithms)
{
public static SignerRequirements Default => new(
MinimumSignatures: 1,
TrustedKeyFingerprints: [],
TrustedIssuers: null,
RequireRekor: false,
Algorithms: ["ES256", "RS256", "EdDSA"]);
}
/// <summary>
/// Validity window for attestations.
/// </summary>
public sealed record ValidityWindow(
[property: JsonPropertyName("not_before")] DateTimeOffset? NotBefore,
[property: JsonPropertyName("not_after")] DateTimeOffset? NotAfter,
[property: JsonPropertyName("max_attestation_age")] int? MaxAttestationAge);
/// <summary>
/// Request to create a verification policy.
/// </summary>
public sealed record CreateVerificationPolicyRequest(
[property: JsonPropertyName("policy_id")] string PolicyId,
[property: JsonPropertyName("version")] string Version,
[property: JsonPropertyName("description")] string? Description,
[property: JsonPropertyName("tenant_scope")] string? TenantScope,
[property: JsonPropertyName("predicate_types")] IReadOnlyList<string> PredicateTypes,
[property: JsonPropertyName("signer_requirements")] SignerRequirements? SignerRequirements,
[property: JsonPropertyName("validity_window")] ValidityWindow? ValidityWindow,
[property: JsonPropertyName("metadata")] IReadOnlyDictionary<string, object?>? Metadata);
/// <summary>
/// Request to update a verification policy.
/// </summary>
public sealed record UpdateVerificationPolicyRequest(
[property: JsonPropertyName("version")] string? Version,
[property: JsonPropertyName("description")] string? Description,
[property: JsonPropertyName("predicate_types")] IReadOnlyList<string>? PredicateTypes,
[property: JsonPropertyName("signer_requirements")] SignerRequirements? SignerRequirements,
[property: JsonPropertyName("validity_window")] ValidityWindow? ValidityWindow,
[property: JsonPropertyName("metadata")] IReadOnlyDictionary<string, object?>? Metadata);
/// <summary>
/// Result of verifying an attestation.
/// </summary>
public sealed record VerificationResult(
[property: JsonPropertyName("valid")] bool Valid,
[property: JsonPropertyName("predicate_type")] string? PredicateType,
[property: JsonPropertyName("signature_count")] int SignatureCount,
[property: JsonPropertyName("signers")] IReadOnlyList<SignerInfo> Signers,
[property: JsonPropertyName("rekor_entry")] RekorEntry? RekorEntry,
[property: JsonPropertyName("attestation_timestamp")] DateTimeOffset? AttestationTimestamp,
[property: JsonPropertyName("policy_id")] string PolicyId,
[property: JsonPropertyName("policy_version")] string PolicyVersion,
[property: JsonPropertyName("errors")] IReadOnlyList<string>? Errors);
/// <summary>
/// Information about a signer.
/// </summary>
public sealed record SignerInfo(
[property: JsonPropertyName("key_fingerprint")] string KeyFingerprint,
[property: JsonPropertyName("issuer")] string? Issuer,
[property: JsonPropertyName("algorithm")] string Algorithm,
[property: JsonPropertyName("verified")] bool Verified);
/// <summary>
/// Rekor transparency log entry.
/// </summary>
public sealed record RekorEntry(
[property: JsonPropertyName("uuid")] string Uuid,
[property: JsonPropertyName("log_index")] long LogIndex,
[property: JsonPropertyName("integrated_time")] DateTimeOffset IntegratedTime);
/// <summary>
/// Request to verify an attestation.
/// </summary>
public sealed record VerifyAttestationRequest(
[property: JsonPropertyName("envelope")] string Envelope,
[property: JsonPropertyName("policy_id")] string PolicyId);
/// <summary>
/// Standard predicate types supported by StellaOps.
/// </summary>
public static class PredicateTypes
{
// StellaOps types
public const string SbomV1 = "stella.ops/sbom@v1";
public const string VexV1 = "stella.ops/vex@v1";
public const string VexDecisionV1 = "stella.ops/vexDecision@v1";
public const string PolicyV1 = "stella.ops/policy@v1";
public const string PromotionV1 = "stella.ops/promotion@v1";
public const string EvidenceV1 = "stella.ops/evidence@v1";
public const string GraphV1 = "stella.ops/graph@v1";
public const string ReplayV1 = "stella.ops/replay@v1";
// Third-party types
public const string SlsaProvenanceV02 = "https://slsa.dev/provenance/v0.2";
public const string SlsaProvenanceV1 = "https://slsa.dev/provenance/v1";
public const string CycloneDxBom = "https://cyclonedx.org/bom";
public const string SpdxDocument = "https://spdx.dev/Document";
public const string OpenVex = "https://openvex.dev/ns";
public static readonly IReadOnlyList<string> DefaultAllowed = new[]
{
SbomV1, VexV1, VexDecisionV1, PolicyV1, PromotionV1,
EvidenceV1, GraphV1, ReplayV1,
SlsaProvenanceV1, CycloneDxBom, SpdxDocument, OpenVex
};
}

View File

@@ -0,0 +1,516 @@
using System.Text.RegularExpressions;
namespace StellaOps.Policy.Engine.Attestation;
/// <summary>
/// Validation result for verification policy per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
public sealed record VerificationPolicyValidationResult(
bool IsValid,
IReadOnlyList<VerificationPolicyValidationError> Errors)
{
public static VerificationPolicyValidationResult Success() =>
new(IsValid: true, Errors: Array.Empty<VerificationPolicyValidationError>());
public static VerificationPolicyValidationResult Failure(params VerificationPolicyValidationError[] errors) =>
new(IsValid: false, Errors: errors);
public static VerificationPolicyValidationResult Failure(IEnumerable<VerificationPolicyValidationError> errors) =>
new(IsValid: false, Errors: errors.ToList());
}
/// <summary>
/// Validation error for verification policy.
/// </summary>
public sealed record VerificationPolicyValidationError(
string Code,
string Field,
string Message,
ValidationSeverity Severity = ValidationSeverity.Error);
/// <summary>
/// Severity of validation error.
/// </summary>
public enum ValidationSeverity
{
Warning,
Error
}
/// <summary>
/// Constraints for verification policy validation.
/// </summary>
public sealed record VerificationPolicyValidationConstraints
{
public static VerificationPolicyValidationConstraints Default { get; } = new();
public int MaxPolicyIdLength { get; init; } = 256;
public int MaxVersionLength { get; init; } = 64;
public int MaxDescriptionLength { get; init; } = 2048;
public int MaxPredicateTypes { get; init; } = 50;
public int MaxTrustedKeyFingerprints { get; init; } = 100;
public int MaxTrustedIssuers { get; init; } = 50;
public int MaxAlgorithms { get; init; } = 20;
public int MaxMetadataEntries { get; init; } = 50;
public int MaxAttestationAgeSeconds { get; init; } = 31536000; // 1 year
}
/// <summary>
/// Validator for verification policies per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
public sealed class VerificationPolicyValidator
{
private static readonly Regex PolicyIdPattern = new(
@"^[a-zA-Z0-9][a-zA-Z0-9\-_.]*$",
RegexOptions.Compiled,
TimeSpan.FromSeconds(1));
private static readonly Regex VersionPattern = new(
@"^\d+\.\d+\.\d+(-[a-zA-Z0-9\-.]+)?(\+[a-zA-Z0-9\-.]+)?$",
RegexOptions.Compiled,
TimeSpan.FromSeconds(1));
private static readonly Regex FingerprintPattern = new(
@"^[0-9a-fA-F]{40,128}$",
RegexOptions.Compiled,
TimeSpan.FromSeconds(1));
private static readonly Regex TenantScopePattern = new(
@"^(\*|[a-zA-Z0-9][a-zA-Z0-9\-_.]*(\*[a-zA-Z0-9\-_.]*)?|[a-zA-Z0-9\-_.]*\*)$",
RegexOptions.Compiled,
TimeSpan.FromSeconds(1));
private static readonly HashSet<string> AllowedAlgorithms = new(StringComparer.OrdinalIgnoreCase)
{
"ES256", "ES384", "ES512",
"RS256", "RS384", "RS512",
"PS256", "PS384", "PS512",
"EdDSA"
};
private readonly VerificationPolicyValidationConstraints _constraints;
public VerificationPolicyValidator(VerificationPolicyValidationConstraints? constraints = null)
{
_constraints = constraints ?? VerificationPolicyValidationConstraints.Default;
}
/// <summary>
/// Validates a create request for verification policy.
/// </summary>
public VerificationPolicyValidationResult ValidateCreate(CreateVerificationPolicyRequest request)
{
ArgumentNullException.ThrowIfNull(request);
var errors = new List<VerificationPolicyValidationError>();
// Validate PolicyId
ValidatePolicyId(request.PolicyId, errors);
// Validate Version
ValidateVersion(request.Version, errors);
// Validate Description
ValidateDescription(request.Description, errors);
// Validate TenantScope
ValidateTenantScope(request.TenantScope, errors);
// Validate PredicateTypes
ValidatePredicateTypes(request.PredicateTypes, errors);
// Validate SignerRequirements
ValidateSignerRequirements(request.SignerRequirements, errors);
// Validate ValidityWindow
ValidateValidityWindow(request.ValidityWindow, errors);
// Validate Metadata
ValidateMetadata(request.Metadata, errors);
return errors.Count == 0
? VerificationPolicyValidationResult.Success()
: VerificationPolicyValidationResult.Failure(errors);
}
/// <summary>
/// Validates an update request for verification policy.
/// </summary>
public VerificationPolicyValidationResult ValidateUpdate(UpdateVerificationPolicyRequest request)
{
ArgumentNullException.ThrowIfNull(request);
var errors = new List<VerificationPolicyValidationError>();
// Version is optional in updates but must be valid if provided
if (request.Version != null)
{
ValidateVersion(request.Version, errors);
}
// Description is optional in updates
if (request.Description != null)
{
ValidateDescription(request.Description, errors);
}
// PredicateTypes is optional in updates
if (request.PredicateTypes != null)
{
ValidatePredicateTypes(request.PredicateTypes, errors);
}
// SignerRequirements is optional in updates
if (request.SignerRequirements != null)
{
ValidateSignerRequirements(request.SignerRequirements, errors);
}
// ValidityWindow is optional in updates
if (request.ValidityWindow != null)
{
ValidateValidityWindow(request.ValidityWindow, errors);
}
// Metadata is optional in updates
if (request.Metadata != null)
{
ValidateMetadata(request.Metadata, errors);
}
return errors.Count == 0
? VerificationPolicyValidationResult.Success()
: VerificationPolicyValidationResult.Failure(errors);
}
private void ValidatePolicyId(string? policyId, List<VerificationPolicyValidationError> errors)
{
if (string.IsNullOrWhiteSpace(policyId))
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_001",
"policy_id",
"Policy ID is required."));
return;
}
if (policyId.Length > _constraints.MaxPolicyIdLength)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_002",
"policy_id",
$"Policy ID exceeds maximum length of {_constraints.MaxPolicyIdLength} characters."));
return;
}
if (!PolicyIdPattern.IsMatch(policyId))
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_003",
"policy_id",
"Policy ID must start with alphanumeric and contain only alphanumeric, hyphens, underscores, or dots."));
}
}
private void ValidateVersion(string? version, List<VerificationPolicyValidationError> errors)
{
if (string.IsNullOrWhiteSpace(version))
{
// Version defaults to "1.0.0" if not provided, so this is a warning
errors.Add(new VerificationPolicyValidationError(
"WARN_VP_001",
"version",
"Version not provided; defaulting to 1.0.0.",
ValidationSeverity.Warning));
return;
}
if (version.Length > _constraints.MaxVersionLength)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_004",
"version",
$"Version exceeds maximum length of {_constraints.MaxVersionLength} characters."));
return;
}
if (!VersionPattern.IsMatch(version))
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_005",
"version",
"Version must follow semver format (e.g., 1.0.0, 2.1.0-alpha.1)."));
}
}
private void ValidateDescription(string? description, List<VerificationPolicyValidationError> errors)
{
if (description != null && description.Length > _constraints.MaxDescriptionLength)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_006",
"description",
$"Description exceeds maximum length of {_constraints.MaxDescriptionLength} characters."));
}
}
private void ValidateTenantScope(string? tenantScope, List<VerificationPolicyValidationError> errors)
{
if (string.IsNullOrWhiteSpace(tenantScope))
{
// Defaults to "*" if not provided
return;
}
if (!TenantScopePattern.IsMatch(tenantScope))
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_007",
"tenant_scope",
"Tenant scope must be '*' or a valid identifier with optional wildcard suffix."));
}
}
private void ValidatePredicateTypes(IReadOnlyList<string>? predicateTypes, List<VerificationPolicyValidationError> errors)
{
if (predicateTypes == null || predicateTypes.Count == 0)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_008",
"predicate_types",
"At least one predicate type is required."));
return;
}
if (predicateTypes.Count > _constraints.MaxPredicateTypes)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_009",
"predicate_types",
$"Predicate types exceeds maximum count of {_constraints.MaxPredicateTypes}."));
return;
}
var seen = new HashSet<string>(StringComparer.Ordinal);
for (var i = 0; i < predicateTypes.Count; i++)
{
var predicateType = predicateTypes[i];
if (string.IsNullOrWhiteSpace(predicateType))
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_010",
$"predicate_types[{i}]",
"Predicate type cannot be empty."));
continue;
}
if (!seen.Add(predicateType))
{
errors.Add(new VerificationPolicyValidationError(
"WARN_VP_002",
$"predicate_types[{i}]",
$"Duplicate predicate type '{predicateType}'.",
ValidationSeverity.Warning));
}
// Check if it's a known predicate type or valid URI format
if (!IsKnownPredicateType(predicateType) && !IsValidPredicateTypeUri(predicateType))
{
errors.Add(new VerificationPolicyValidationError(
"WARN_VP_003",
$"predicate_types[{i}]",
$"Predicate type '{predicateType}' is not a known StellaOps or standard type.",
ValidationSeverity.Warning));
}
}
}
private void ValidateSignerRequirements(SignerRequirements? requirements, List<VerificationPolicyValidationError> errors)
{
if (requirements == null)
{
// Defaults to SignerRequirements.Default if not provided
return;
}
if (requirements.MinimumSignatures < 1)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_011",
"signer_requirements.minimum_signatures",
"Minimum signatures must be at least 1."));
}
if (requirements.TrustedKeyFingerprints.Count > _constraints.MaxTrustedKeyFingerprints)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_012",
"signer_requirements.trusted_key_fingerprints",
$"Trusted key fingerprints exceeds maximum count of {_constraints.MaxTrustedKeyFingerprints}."));
}
var seenFingerprints = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < requirements.TrustedKeyFingerprints.Count; i++)
{
var fingerprint = requirements.TrustedKeyFingerprints[i];
if (string.IsNullOrWhiteSpace(fingerprint))
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_013",
$"signer_requirements.trusted_key_fingerprints[{i}]",
"Key fingerprint cannot be empty."));
continue;
}
if (!FingerprintPattern.IsMatch(fingerprint))
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_014",
$"signer_requirements.trusted_key_fingerprints[{i}]",
"Key fingerprint must be a 40-128 character hex string."));
}
if (!seenFingerprints.Add(fingerprint))
{
errors.Add(new VerificationPolicyValidationError(
"WARN_VP_004",
$"signer_requirements.trusted_key_fingerprints[{i}]",
$"Duplicate key fingerprint.",
ValidationSeverity.Warning));
}
}
if (requirements.TrustedIssuers != null)
{
if (requirements.TrustedIssuers.Count > _constraints.MaxTrustedIssuers)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_015",
"signer_requirements.trusted_issuers",
$"Trusted issuers exceeds maximum count of {_constraints.MaxTrustedIssuers}."));
}
for (var i = 0; i < requirements.TrustedIssuers.Count; i++)
{
var issuer = requirements.TrustedIssuers[i];
if (string.IsNullOrWhiteSpace(issuer))
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_016",
$"signer_requirements.trusted_issuers[{i}]",
"Issuer cannot be empty."));
}
}
}
if (requirements.Algorithms != null)
{
if (requirements.Algorithms.Count > _constraints.MaxAlgorithms)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_017",
"signer_requirements.algorithms",
$"Algorithms exceeds maximum count of {_constraints.MaxAlgorithms}."));
}
for (var i = 0; i < requirements.Algorithms.Count; i++)
{
var algorithm = requirements.Algorithms[i];
if (string.IsNullOrWhiteSpace(algorithm))
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_018",
$"signer_requirements.algorithms[{i}]",
"Algorithm cannot be empty."));
continue;
}
if (!AllowedAlgorithms.Contains(algorithm))
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_019",
$"signer_requirements.algorithms[{i}]",
$"Algorithm '{algorithm}' is not supported. Allowed: {string.Join(", ", AllowedAlgorithms)}."));
}
}
}
}
private void ValidateValidityWindow(ValidityWindow? window, List<VerificationPolicyValidationError> errors)
{
if (window == null)
{
return;
}
if (window.NotBefore.HasValue && window.NotAfter.HasValue)
{
if (window.NotBefore.Value >= window.NotAfter.Value)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_020",
"validity_window",
"not_before must be earlier than not_after."));
}
}
if (window.MaxAttestationAge.HasValue)
{
if (window.MaxAttestationAge.Value <= 0)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_021",
"validity_window.max_attestation_age",
"Maximum attestation age must be a positive integer (seconds)."));
}
else if (window.MaxAttestationAge.Value > _constraints.MaxAttestationAgeSeconds)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_022",
"validity_window.max_attestation_age",
$"Maximum attestation age exceeds limit of {_constraints.MaxAttestationAgeSeconds} seconds."));
}
}
}
private void ValidateMetadata(IReadOnlyDictionary<string, object?>? metadata, List<VerificationPolicyValidationError> errors)
{
if (metadata == null)
{
return;
}
if (metadata.Count > _constraints.MaxMetadataEntries)
{
errors.Add(new VerificationPolicyValidationError(
"ERR_VP_023",
"metadata",
$"Metadata exceeds maximum of {_constraints.MaxMetadataEntries} entries."));
}
}
private static bool IsKnownPredicateType(string predicateType)
{
return predicateType == PredicateTypes.SbomV1
|| predicateType == PredicateTypes.VexV1
|| predicateType == PredicateTypes.VexDecisionV1
|| predicateType == PredicateTypes.PolicyV1
|| predicateType == PredicateTypes.PromotionV1
|| predicateType == PredicateTypes.EvidenceV1
|| predicateType == PredicateTypes.GraphV1
|| predicateType == PredicateTypes.ReplayV1
|| predicateType == PredicateTypes.SlsaProvenanceV02
|| predicateType == PredicateTypes.SlsaProvenanceV1
|| predicateType == PredicateTypes.CycloneDxBom
|| predicateType == PredicateTypes.SpdxDocument
|| predicateType == PredicateTypes.OpenVex;
}
private static bool IsValidPredicateTypeUri(string predicateType)
{
// Predicate types are typically URIs or namespaced identifiers
return predicateType.Contains('/') || predicateType.Contains(':');
}
}

View File

@@ -0,0 +1,228 @@
using System.Collections.Immutable;
using System.Text.Json.Serialization;
using StellaOps.Policy.Engine.Attestation;
namespace StellaOps.Policy.Engine.ConsoleSurface;
/// <summary>
/// Console request for attestation report query per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
internal sealed record ConsoleAttestationReportRequest(
[property: JsonPropertyName("artifact_digests")] IReadOnlyList<string>? ArtifactDigests,
[property: JsonPropertyName("artifact_uri_pattern")] string? ArtifactUriPattern,
[property: JsonPropertyName("policy_ids")] IReadOnlyList<string>? PolicyIds,
[property: JsonPropertyName("predicate_types")] IReadOnlyList<string>? PredicateTypes,
[property: JsonPropertyName("status_filter")] IReadOnlyList<string>? StatusFilter,
[property: JsonPropertyName("from_time")] DateTimeOffset? FromTime,
[property: JsonPropertyName("to_time")] DateTimeOffset? ToTime,
[property: JsonPropertyName("group_by")] ConsoleReportGroupBy? GroupBy,
[property: JsonPropertyName("sort_by")] ConsoleReportSortBy? SortBy,
[property: JsonPropertyName("page")] int Page = 1,
[property: JsonPropertyName("page_size")] int PageSize = 25);
/// <summary>
/// Grouping options for Console attestation reports.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter<ConsoleReportGroupBy>))]
internal enum ConsoleReportGroupBy
{
None,
Policy,
PredicateType,
Status,
ArtifactUri
}
/// <summary>
/// Sorting options for Console attestation reports.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter<ConsoleReportSortBy>))]
internal enum ConsoleReportSortBy
{
EvaluatedAtDesc,
EvaluatedAtAsc,
StatusAsc,
StatusDesc,
CoverageDesc,
CoverageAsc
}
/// <summary>
/// Console response for attestation reports.
/// </summary>
internal sealed record ConsoleAttestationReportResponse(
[property: JsonPropertyName("schema_version")] string SchemaVersion,
[property: JsonPropertyName("summary")] ConsoleReportSummary Summary,
[property: JsonPropertyName("reports")] IReadOnlyList<ConsoleArtifactReport> Reports,
[property: JsonPropertyName("groups")] IReadOnlyList<ConsoleReportGroup>? Groups,
[property: JsonPropertyName("pagination")] ConsolePagination Pagination,
[property: JsonPropertyName("filters_applied")] ConsoleFiltersApplied FiltersApplied);
/// <summary>
/// Summary of attestation reports for Console.
/// </summary>
internal sealed record ConsoleReportSummary(
[property: JsonPropertyName("total_artifacts")] int TotalArtifacts,
[property: JsonPropertyName("total_attestations")] int TotalAttestations,
[property: JsonPropertyName("status_breakdown")] ImmutableDictionary<string, int> StatusBreakdown,
[property: JsonPropertyName("coverage_rate")] double CoverageRate,
[property: JsonPropertyName("compliance_rate")] double ComplianceRate,
[property: JsonPropertyName("average_age_hours")] double AverageAgeHours);
/// <summary>
/// Console-friendly artifact attestation report.
/// </summary>
internal sealed record ConsoleArtifactReport(
[property: JsonPropertyName("artifact_digest")] string ArtifactDigest,
[property: JsonPropertyName("artifact_uri")] string? ArtifactUri,
[property: JsonPropertyName("artifact_short_digest")] string ArtifactShortDigest,
[property: JsonPropertyName("status")] string Status,
[property: JsonPropertyName("status_label")] string StatusLabel,
[property: JsonPropertyName("status_icon")] string StatusIcon,
[property: JsonPropertyName("attestation_count")] int AttestationCount,
[property: JsonPropertyName("coverage_percentage")] double CoveragePercentage,
[property: JsonPropertyName("policies_passed")] int PoliciesPassed,
[property: JsonPropertyName("policies_failed")] int PoliciesFailed,
[property: JsonPropertyName("evaluated_at")] DateTimeOffset EvaluatedAt,
[property: JsonPropertyName("evaluated_at_relative")] string EvaluatedAtRelative,
[property: JsonPropertyName("details")] ConsoleReportDetails? Details);
/// <summary>
/// Detailed report information for Console.
/// </summary>
internal sealed record ConsoleReportDetails(
[property: JsonPropertyName("predicate_types")] IReadOnlyList<ConsolePredicateTypeStatus> PredicateTypes,
[property: JsonPropertyName("policies")] IReadOnlyList<ConsolePolicyStatus> Policies,
[property: JsonPropertyName("signers")] IReadOnlyList<ConsoleSignerInfo> Signers,
[property: JsonPropertyName("issues")] IReadOnlyList<ConsoleIssue> Issues);
/// <summary>
/// Predicate type status for Console.
/// </summary>
internal sealed record ConsolePredicateTypeStatus(
[property: JsonPropertyName("type")] string Type,
[property: JsonPropertyName("type_label")] string TypeLabel,
[property: JsonPropertyName("status")] string Status,
[property: JsonPropertyName("status_label")] string StatusLabel,
[property: JsonPropertyName("freshness")] string Freshness);
/// <summary>
/// Policy status for Console.
/// </summary>
internal sealed record ConsolePolicyStatus(
[property: JsonPropertyName("policy_id")] string PolicyId,
[property: JsonPropertyName("policy_version")] string PolicyVersion,
[property: JsonPropertyName("status")] string Status,
[property: JsonPropertyName("status_label")] string StatusLabel,
[property: JsonPropertyName("verdict")] string Verdict);
/// <summary>
/// Signer information for Console.
/// </summary>
internal sealed record ConsoleSignerInfo(
[property: JsonPropertyName("key_fingerprint_short")] string KeyFingerprintShort,
[property: JsonPropertyName("issuer")] string? Issuer,
[property: JsonPropertyName("subject")] string? Subject,
[property: JsonPropertyName("algorithm")] string Algorithm,
[property: JsonPropertyName("verified")] bool Verified,
[property: JsonPropertyName("trusted")] bool Trusted);
/// <summary>
/// Issue for Console display.
/// </summary>
internal sealed record ConsoleIssue(
[property: JsonPropertyName("severity")] string Severity,
[property: JsonPropertyName("message")] string Message,
[property: JsonPropertyName("field")] string? Field);
/// <summary>
/// Report group for Console.
/// </summary>
internal sealed record ConsoleReportGroup(
[property: JsonPropertyName("key")] string Key,
[property: JsonPropertyName("label")] string Label,
[property: JsonPropertyName("count")] int Count,
[property: JsonPropertyName("status_breakdown")] ImmutableDictionary<string, int> StatusBreakdown);
/// <summary>
/// Pagination information for Console.
/// </summary>
internal sealed record ConsolePagination(
[property: JsonPropertyName("page")] int Page,
[property: JsonPropertyName("page_size")] int PageSize,
[property: JsonPropertyName("total_pages")] int TotalPages,
[property: JsonPropertyName("total_items")] int TotalItems,
[property: JsonPropertyName("has_next")] bool HasNext,
[property: JsonPropertyName("has_previous")] bool HasPrevious);
/// <summary>
/// Applied filters information for Console.
/// </summary>
internal sealed record ConsoleFiltersApplied(
[property: JsonPropertyName("artifact_count")] int ArtifactCount,
[property: JsonPropertyName("policy_ids")] IReadOnlyList<string>? PolicyIds,
[property: JsonPropertyName("predicate_types")] IReadOnlyList<string>? PredicateTypes,
[property: JsonPropertyName("status_filter")] IReadOnlyList<string>? StatusFilter,
[property: JsonPropertyName("time_range")] ConsoleTimeRange? TimeRange);
/// <summary>
/// Time range for Console filters.
/// </summary>
internal sealed record ConsoleTimeRange(
[property: JsonPropertyName("from")] DateTimeOffset? From,
[property: JsonPropertyName("to")] DateTimeOffset? To);
/// <summary>
/// Console request for attestation statistics dashboard.
/// </summary>
internal sealed record ConsoleAttestationDashboardRequest(
[property: JsonPropertyName("time_range")] string? TimeRange,
[property: JsonPropertyName("policy_ids")] IReadOnlyList<string>? PolicyIds,
[property: JsonPropertyName("artifact_uri_pattern")] string? ArtifactUriPattern);
/// <summary>
/// Console response for attestation statistics dashboard.
/// </summary>
internal sealed record ConsoleAttestationDashboardResponse(
[property: JsonPropertyName("schema_version")] string SchemaVersion,
[property: JsonPropertyName("overview")] ConsoleDashboardOverview Overview,
[property: JsonPropertyName("trends")] ConsoleDashboardTrends Trends,
[property: JsonPropertyName("top_issues")] IReadOnlyList<ConsoleDashboardIssue> TopIssues,
[property: JsonPropertyName("policy_compliance")] IReadOnlyList<ConsoleDashboardPolicyCompliance> PolicyCompliance,
[property: JsonPropertyName("evaluated_at")] DateTimeOffset EvaluatedAt);
/// <summary>
/// Dashboard overview for Console.
/// </summary>
internal sealed record ConsoleDashboardOverview(
[property: JsonPropertyName("total_artifacts")] int TotalArtifacts,
[property: JsonPropertyName("total_attestations")] int TotalAttestations,
[property: JsonPropertyName("pass_rate")] double PassRate,
[property: JsonPropertyName("coverage_rate")] double CoverageRate,
[property: JsonPropertyName("average_freshness_hours")] double AverageFreshnessHours);
/// <summary>
/// Dashboard trends for Console.
/// </summary>
internal sealed record ConsoleDashboardTrends(
[property: JsonPropertyName("pass_rate_change")] double PassRateChange,
[property: JsonPropertyName("coverage_rate_change")] double CoverageRateChange,
[property: JsonPropertyName("attestation_count_change")] int AttestationCountChange,
[property: JsonPropertyName("trend_direction")] string TrendDirection);
/// <summary>
/// Dashboard issue for Console.
/// </summary>
internal sealed record ConsoleDashboardIssue(
[property: JsonPropertyName("issue")] string Issue,
[property: JsonPropertyName("count")] int Count,
[property: JsonPropertyName("severity")] string Severity);
/// <summary>
/// Dashboard policy compliance for Console.
/// </summary>
internal sealed record ConsoleDashboardPolicyCompliance(
[property: JsonPropertyName("policy_id")] string PolicyId,
[property: JsonPropertyName("policy_version")] string PolicyVersion,
[property: JsonPropertyName("compliance_rate")] double ComplianceRate,
[property: JsonPropertyName("artifacts_evaluated")] int ArtifactsEvaluated);

View File

@@ -0,0 +1,470 @@
using System.Collections.Immutable;
using StellaOps.Policy.Engine.Attestation;
namespace StellaOps.Policy.Engine.ConsoleSurface;
/// <summary>
/// Service for Console attestation report integration per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
internal sealed class ConsoleAttestationReportService
{
private const string SchemaVersion = "1.0.0";
private readonly IAttestationReportService _reportService;
private readonly IVerificationPolicyStore _policyStore;
private readonly TimeProvider _timeProvider;
public ConsoleAttestationReportService(
IAttestationReportService reportService,
IVerificationPolicyStore policyStore,
TimeProvider timeProvider)
{
_reportService = reportService ?? throw new ArgumentNullException(nameof(reportService));
_policyStore = policyStore ?? throw new ArgumentNullException(nameof(policyStore));
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
}
public async Task<ConsoleAttestationReportResponse> QueryReportsAsync(
ConsoleAttestationReportRequest request,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
var now = _timeProvider.GetUtcNow();
// Convert Console request to internal query
var query = new AttestationReportQuery(
ArtifactDigests: request.ArtifactDigests,
ArtifactUriPattern: request.ArtifactUriPattern,
PolicyIds: request.PolicyIds,
PredicateTypes: request.PredicateTypes,
StatusFilter: ParseStatusFilter(request.StatusFilter),
FromTime: request.FromTime,
ToTime: request.ToTime,
IncludeDetails: true,
Limit: request.PageSize,
Offset: (request.Page - 1) * request.PageSize);
// Get reports
var response = await _reportService.ListReportsAsync(query, cancellationToken).ConfigureAwait(false);
// Get statistics for summary
var statistics = await _reportService.GetStatisticsAsync(query, cancellationToken).ConfigureAwait(false);
// Convert to Console format
var consoleReports = response.Reports.Select(r => ToConsoleReport(r, now)).ToList();
// Calculate groups if requested
IReadOnlyList<ConsoleReportGroup>? groups = null;
if (request.GroupBy.HasValue && request.GroupBy.Value != ConsoleReportGroupBy.None)
{
groups = CalculateGroups(response.Reports, request.GroupBy.Value);
}
// Calculate pagination
var totalPages = (int)Math.Ceiling((double)response.Total / request.PageSize);
var pagination = new ConsolePagination(
Page: request.Page,
PageSize: request.PageSize,
TotalPages: totalPages,
TotalItems: response.Total,
HasNext: request.Page < totalPages,
HasPrevious: request.Page > 1);
// Create summary
var summary = new ConsoleReportSummary(
TotalArtifacts: statistics.TotalArtifacts,
TotalAttestations: statistics.TotalAttestations,
StatusBreakdown: statistics.StatusDistribution
.ToImmutableDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value),
CoverageRate: Math.Round(statistics.CoverageRate, 2),
ComplianceRate: CalculateComplianceRate(response.Reports),
AverageAgeHours: Math.Round(statistics.AverageAgeSeconds / 3600, 2));
return new ConsoleAttestationReportResponse(
SchemaVersion: SchemaVersion,
Summary: summary,
Reports: consoleReports,
Groups: groups,
Pagination: pagination,
FiltersApplied: new ConsoleFiltersApplied(
ArtifactCount: request.ArtifactDigests?.Count ?? 0,
PolicyIds: request.PolicyIds,
PredicateTypes: request.PredicateTypes,
StatusFilter: request.StatusFilter,
TimeRange: request.FromTime.HasValue || request.ToTime.HasValue
? new ConsoleTimeRange(request.FromTime, request.ToTime)
: null));
}
public async Task<ConsoleAttestationDashboardResponse> GetDashboardAsync(
ConsoleAttestationDashboardRequest request,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
var now = _timeProvider.GetUtcNow();
var (fromTime, toTime) = ParseTimeRange(request.TimeRange, now);
var query = new AttestationReportQuery(
ArtifactDigests: null,
ArtifactUriPattern: request.ArtifactUriPattern,
PolicyIds: request.PolicyIds,
PredicateTypes: null,
StatusFilter: null,
FromTime: fromTime,
ToTime: toTime,
IncludeDetails: false,
Limit: int.MaxValue,
Offset: 0);
var statistics = await _reportService.GetStatisticsAsync(query, cancellationToken).ConfigureAwait(false);
var reports = await _reportService.ListReportsAsync(query, cancellationToken).ConfigureAwait(false);
// Calculate pass rate
var passCount = statistics.StatusDistribution.GetValueOrDefault(AttestationReportStatus.Pass, 0);
var failCount = statistics.StatusDistribution.GetValueOrDefault(AttestationReportStatus.Fail, 0);
var warnCount = statistics.StatusDistribution.GetValueOrDefault(AttestationReportStatus.Warn, 0);
var total = passCount + failCount + warnCount;
var passRate = total > 0 ? (double)passCount / total * 100 : 0;
// Calculate overview
var overview = new ConsoleDashboardOverview(
TotalArtifacts: statistics.TotalArtifacts,
TotalAttestations: statistics.TotalAttestations,
PassRate: Math.Round(passRate, 2),
CoverageRate: Math.Round(statistics.CoverageRate, 2),
AverageFreshnessHours: Math.Round(statistics.AverageAgeSeconds / 3600, 2));
// Calculate trends (simplified - would normally compare to previous period)
var trends = new ConsoleDashboardTrends(
PassRateChange: 0,
CoverageRateChange: 0,
AttestationCountChange: 0,
TrendDirection: "stable");
// Get top issues
var topIssues = reports.Reports
.SelectMany(r => r.VerificationResults)
.SelectMany(v => v.Issues)
.GroupBy(i => i)
.OrderByDescending(g => g.Count())
.Take(5)
.Select(g => new ConsoleDashboardIssue(
Issue: g.Key,
Count: g.Count(),
Severity: "error"))
.ToList();
// Get policy compliance
var policyCompliance = await CalculatePolicyComplianceAsync(reports.Reports, cancellationToken).ConfigureAwait(false);
return new ConsoleAttestationDashboardResponse(
SchemaVersion: SchemaVersion,
Overview: overview,
Trends: trends,
TopIssues: topIssues,
PolicyCompliance: policyCompliance,
EvaluatedAt: now);
}
private ConsoleArtifactReport ToConsoleReport(ArtifactAttestationReport report, DateTimeOffset now)
{
var age = now - report.EvaluatedAt;
var ageRelative = FormatRelativeTime(age);
return new ConsoleArtifactReport(
ArtifactDigest: report.ArtifactDigest,
ArtifactUri: report.ArtifactUri,
ArtifactShortDigest: report.ArtifactDigest.Length > 12
? report.ArtifactDigest[..12]
: report.ArtifactDigest,
Status: report.OverallStatus.ToString().ToLowerInvariant(),
StatusLabel: GetStatusLabel(report.OverallStatus),
StatusIcon: GetStatusIcon(report.OverallStatus),
AttestationCount: report.AttestationCount,
CoveragePercentage: report.Coverage.CoveragePercentage,
PoliciesPassed: report.PolicyCompliance.PoliciesPassed,
PoliciesFailed: report.PolicyCompliance.PoliciesFailed,
EvaluatedAt: report.EvaluatedAt,
EvaluatedAtRelative: ageRelative,
Details: ToConsoleDetails(report));
}
private static ConsoleReportDetails ToConsoleDetails(ArtifactAttestationReport report)
{
var predicateTypes = report.VerificationResults
.GroupBy(v => v.PredicateType)
.Select(g => new ConsolePredicateTypeStatus(
Type: g.Key,
TypeLabel: GetPredicateTypeLabel(g.Key),
Status: g.First().Status.ToString().ToLowerInvariant(),
StatusLabel: GetStatusLabel(g.First().Status),
Freshness: FormatFreshness(g.First().FreshnessStatus)))
.ToList();
var policies = report.PolicyCompliance.PolicyResults
.Select(p => new ConsolePolicyStatus(
PolicyId: p.PolicyId,
PolicyVersion: p.PolicyVersion,
Status: p.Status.ToString().ToLowerInvariant(),
StatusLabel: GetStatusLabel(p.Status),
Verdict: p.Verdict))
.ToList();
var signers = report.VerificationResults
.SelectMany(v => v.SignatureStatus.Signers)
.DistinctBy(s => s.KeyFingerprint)
.Select(s => new ConsoleSignerInfo(
KeyFingerprintShort: s.KeyFingerprint.Length > 8
? s.KeyFingerprint[..8]
: s.KeyFingerprint,
Issuer: s.Issuer,
Subject: s.Subject,
Algorithm: s.Algorithm,
Verified: s.Verified,
Trusted: s.Trusted))
.ToList();
var issues = report.VerificationResults
.SelectMany(v => v.Issues)
.Distinct()
.Select(i => new ConsoleIssue(
Severity: "error",
Message: i,
Field: null))
.ToList();
return new ConsoleReportDetails(
PredicateTypes: predicateTypes,
Policies: policies,
Signers: signers,
Issues: issues);
}
private static IReadOnlyList<ConsoleReportGroup> CalculateGroups(
IReadOnlyList<ArtifactAttestationReport> reports,
ConsoleReportGroupBy groupBy)
{
return groupBy switch
{
ConsoleReportGroupBy.Policy => GroupByPolicy(reports),
ConsoleReportGroupBy.PredicateType => GroupByPredicateType(reports),
ConsoleReportGroupBy.Status => GroupByStatus(reports),
ConsoleReportGroupBy.ArtifactUri => GroupByArtifactUri(reports),
_ => []
};
}
private static IReadOnlyList<ConsoleReportGroup> GroupByPolicy(IReadOnlyList<ArtifactAttestationReport> reports)
{
return reports
.SelectMany(r => r.PolicyCompliance.PolicyResults)
.GroupBy(p => p.PolicyId)
.Select(g => new ConsoleReportGroup(
Key: g.Key,
Label: g.Key,
Count: g.Count(),
StatusBreakdown: g.GroupBy(p => p.Status.ToString())
.ToImmutableDictionary(s => s.Key, s => s.Count())))
.ToList();
}
private static IReadOnlyList<ConsoleReportGroup> GroupByPredicateType(IReadOnlyList<ArtifactAttestationReport> reports)
{
return reports
.SelectMany(r => r.VerificationResults)
.GroupBy(v => v.PredicateType)
.Select(g => new ConsoleReportGroup(
Key: g.Key,
Label: GetPredicateTypeLabel(g.Key),
Count: g.Count(),
StatusBreakdown: g.GroupBy(v => v.Status.ToString())
.ToImmutableDictionary(s => s.Key, s => s.Count())))
.ToList();
}
private static IReadOnlyList<ConsoleReportGroup> GroupByStatus(IReadOnlyList<ArtifactAttestationReport> reports)
{
return reports
.GroupBy(r => r.OverallStatus)
.Select(g => new ConsoleReportGroup(
Key: g.Key.ToString(),
Label: GetStatusLabel(g.Key),
Count: g.Count(),
StatusBreakdown: ImmutableDictionary<string, int>.Empty.Add(g.Key.ToString(), g.Count())))
.ToList();
}
private static IReadOnlyList<ConsoleReportGroup> GroupByArtifactUri(IReadOnlyList<ArtifactAttestationReport> reports)
{
return reports
.Where(r => !string.IsNullOrWhiteSpace(r.ArtifactUri))
.GroupBy(r => ExtractRepository(r.ArtifactUri!))
.Select(g => new ConsoleReportGroup(
Key: g.Key,
Label: g.Key,
Count: g.Count(),
StatusBreakdown: g.GroupBy(r => r.OverallStatus.ToString())
.ToImmutableDictionary(s => s.Key, s => s.Count())))
.ToList();
}
private async Task<IReadOnlyList<ConsoleDashboardPolicyCompliance>> CalculatePolicyComplianceAsync(
IReadOnlyList<ArtifactAttestationReport> reports,
CancellationToken cancellationToken)
{
var policyResults = reports
.SelectMany(r => r.PolicyCompliance.PolicyResults)
.GroupBy(p => p.PolicyId)
.Select(g =>
{
var total = g.Count();
var passed = g.Count(p => p.Status == AttestationReportStatus.Pass);
var complianceRate = total > 0 ? (double)passed / total * 100 : 0;
return new ConsoleDashboardPolicyCompliance(
PolicyId: g.Key,
PolicyVersion: g.First().PolicyVersion,
ComplianceRate: Math.Round(complianceRate, 2),
ArtifactsEvaluated: total);
})
.OrderByDescending(p => p.ArtifactsEvaluated)
.Take(10)
.ToList();
return policyResults;
}
private static IReadOnlyList<AttestationReportStatus>? ParseStatusFilter(IReadOnlyList<string>? statusFilter)
{
if (statusFilter == null || statusFilter.Count == 0)
{
return null;
}
return statusFilter
.Select(s => Enum.TryParse<AttestationReportStatus>(s, true, out var status) ? status : (AttestationReportStatus?)null)
.Where(s => s.HasValue)
.Select(s => s!.Value)
.ToList();
}
private static (DateTimeOffset? from, DateTimeOffset? to) ParseTimeRange(string? timeRange, DateTimeOffset now)
{
return timeRange?.ToLowerInvariant() switch
{
"1h" => (now.AddHours(-1), now),
"24h" => (now.AddDays(-1), now),
"7d" => (now.AddDays(-7), now),
"30d" => (now.AddDays(-30), now),
"90d" => (now.AddDays(-90), now),
_ => (null, null)
};
}
private static double CalculateComplianceRate(IReadOnlyList<ArtifactAttestationReport> reports)
{
if (reports.Count == 0)
{
return 0;
}
var compliant = reports.Count(r =>
r.OverallStatus == AttestationReportStatus.Pass ||
r.OverallStatus == AttestationReportStatus.Warn);
return Math.Round((double)compliant / reports.Count * 100, 2);
}
private static string GetStatusLabel(AttestationReportStatus status)
{
return status switch
{
AttestationReportStatus.Pass => "Passed",
AttestationReportStatus.Fail => "Failed",
AttestationReportStatus.Warn => "Warning",
AttestationReportStatus.Skipped => "Skipped",
AttestationReportStatus.Pending => "Pending",
_ => "Unknown"
};
}
private static string GetStatusIcon(AttestationReportStatus status)
{
return status switch
{
AttestationReportStatus.Pass => "check-circle",
AttestationReportStatus.Fail => "x-circle",
AttestationReportStatus.Warn => "alert-triangle",
AttestationReportStatus.Skipped => "minus-circle",
AttestationReportStatus.Pending => "clock",
_ => "help-circle"
};
}
private static string GetPredicateTypeLabel(string predicateType)
{
return predicateType switch
{
PredicateTypes.SbomV1 => "SBOM",
PredicateTypes.VexV1 => "VEX",
PredicateTypes.VexDecisionV1 => "VEX Decision",
PredicateTypes.PolicyV1 => "Policy",
PredicateTypes.PromotionV1 => "Promotion",
PredicateTypes.EvidenceV1 => "Evidence",
PredicateTypes.GraphV1 => "Graph",
PredicateTypes.ReplayV1 => "Replay",
PredicateTypes.SlsaProvenanceV1 => "SLSA v1",
PredicateTypes.SlsaProvenanceV02 => "SLSA v0.2",
PredicateTypes.CycloneDxBom => "CycloneDX",
PredicateTypes.SpdxDocument => "SPDX",
PredicateTypes.OpenVex => "OpenVEX",
_ => predicateType
};
}
private static string FormatFreshness(FreshnessVerificationStatus freshness)
{
return freshness.IsFresh ? "Fresh" : $"{freshness.AgeSeconds / 3600}h old";
}
private static string FormatRelativeTime(TimeSpan age)
{
if (age.TotalMinutes < 1)
{
return "just now";
}
if (age.TotalHours < 1)
{
return $"{(int)age.TotalMinutes}m ago";
}
if (age.TotalDays < 1)
{
return $"{(int)age.TotalHours}h ago";
}
if (age.TotalDays < 7)
{
return $"{(int)age.TotalDays}d ago";
}
return $"{(int)(age.TotalDays / 7)}w ago";
}
private static string ExtractRepository(string artifactUri)
{
try
{
var uri = new Uri(artifactUri);
var path = uri.AbsolutePath.Split('/');
return path.Length >= 2 ? path[1] : uri.Host;
}
catch
{
return artifactUri;
}
}
}

View File

@@ -65,6 +65,13 @@ public sealed record PolicyDecisionLocator(
/// <summary>
/// Summary statistics for the decision response.
/// </summary>
/// <param name="TotalDecisions">Total number of policy decisions made.</param>
/// <param name="TotalConflicts">Number of conflicting decisions.</param>
/// <param name="SeverityCounts">Count of findings by severity level.</param>
/// <param name="TopSeveritySources">
/// DEPRECATED: Source ranking. Use trust weighting service instead.
/// Scheduled for removal in v2.0. See DESIGN-POLICY-NORMALIZED-FIELD-REMOVAL-001.
/// </param>
public sealed record PolicyDecisionSummary(
[property: JsonPropertyName("total_decisions")] int TotalDecisions,
[property: JsonPropertyName("total_conflicts")] int TotalConflicts,
@@ -72,7 +79,9 @@ public sealed record PolicyDecisionSummary(
[property: JsonPropertyName("top_severity_sources")] IReadOnlyList<PolicyDecisionSourceRank> TopSeveritySources);
/// <summary>
/// Aggregated source rank across all decisions.
/// DEPRECATED: Aggregated source rank across all decisions.
/// Scheduled for removal in v2.0. See DESIGN-POLICY-NORMALIZED-FIELD-REMOVAL-001.
/// Use trust weighting service instead.
/// </summary>
public sealed record PolicyDecisionSourceRank(
[property: JsonPropertyName("source")] string Source,

View File

@@ -0,0 +1,88 @@
using Microsoft.AspNetCore.Mvc;
using StellaOps.Policy.Engine.AirGap;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Endpoints for air-gap notification testing and management.
/// </summary>
public static class AirGapNotificationEndpoints
{
public static IEndpointRouteBuilder MapAirGapNotifications(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/system/airgap/notifications");
group.MapPost("/test", SendTestNotificationAsync)
.WithName("AirGap.TestNotification")
.WithDescription("Send a test notification")
.RequireAuthorization(policy => policy.RequireClaim("scope", "airgap:seal"));
group.MapGet("/channels", GetChannelsAsync)
.WithName("AirGap.GetNotificationChannels")
.WithDescription("Get configured notification channels")
.RequireAuthorization(policy => policy.RequireClaim("scope", "airgap:status:read"));
return routes;
}
private static async Task<IResult> SendTestNotificationAsync(
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
[FromBody] TestNotificationRequest? request,
IAirGapNotificationService notificationService,
TimeProvider timeProvider,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(tenantId))
{
tenantId = "default";
}
var notification = new AirGapNotification(
NotificationId: $"test-{Guid.NewGuid():N}"[..20],
TenantId: tenantId,
Type: request?.Type ?? AirGapNotificationType.StalenessWarning,
Severity: request?.Severity ?? NotificationSeverity.Info,
Title: request?.Title ?? "Test Notification",
Message: request?.Message ?? "This is a test notification from the air-gap notification system.",
OccurredAt: timeProvider.GetUtcNow(),
Metadata: new Dictionary<string, object?>
{
["test"] = true
});
await notificationService.SendAsync(notification, cancellationToken).ConfigureAwait(false);
return Results.Ok(new
{
sent = true,
notification_id = notification.NotificationId,
type = notification.Type.ToString(),
severity = notification.Severity.ToString()
});
}
private static Task<IResult> GetChannelsAsync(
[FromServices] IEnumerable<IAirGapNotificationChannel> channels,
CancellationToken cancellationToken)
{
var channelList = channels.Select(c => new
{
name = c.ChannelName
}).ToList();
return Task.FromResult(Results.Ok(new
{
channels = channelList,
count = channelList.Count
}));
}
}
/// <summary>
/// Request for sending a test notification.
/// </summary>
public sealed record TestNotificationRequest(
AirGapNotificationType? Type = null,
NotificationSeverity? Severity = null,
string? Title = null,
string? Message = null);

View File

@@ -0,0 +1,233 @@
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using StellaOps.Auth.Abstractions;
using StellaOps.Policy.Engine.Attestation;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Endpoints for attestation reports per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
public static class AttestationReportEndpoints
{
public static IEndpointRouteBuilder MapAttestationReports(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/api/v1/attestor/reports")
.WithTags("Attestation Reports");
group.MapGet("/{artifactDigest}", GetReportAsync)
.WithName("Attestor.GetReport")
.WithSummary("Get attestation report for an artifact")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<ArtifactAttestationReport>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
group.MapPost("/query", ListReportsAsync)
.WithName("Attestor.ListReports")
.WithSummary("Query attestation reports")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<AttestationReportListResponse>(StatusCodes.Status200OK);
group.MapPost("/verify", VerifyArtifactAsync)
.WithName("Attestor.VerifyArtifact")
.WithSummary("Generate attestation report for an artifact")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<ArtifactAttestationReport>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status400BadRequest);
group.MapGet("/statistics", GetStatisticsAsync)
.WithName("Attestor.GetStatistics")
.WithSummary("Get aggregated attestation statistics")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<AttestationStatistics>(StatusCodes.Status200OK);
group.MapPost("/store", StoreReportAsync)
.WithName("Attestor.StoreReport")
.WithSummary("Store an attestation report")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyWrite))
.Produces<StoredAttestationReport>(StatusCodes.Status201Created)
.Produces<ProblemHttpResult>(StatusCodes.Status400BadRequest);
group.MapDelete("/expired", PurgeExpiredAsync)
.WithName("Attestor.PurgeExpired")
.WithSummary("Purge expired attestation reports")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyWrite))
.Produces<PurgeExpiredResponse>(StatusCodes.Status200OK);
return routes;
}
private static async Task<IResult> GetReportAsync(
[FromRoute] string artifactDigest,
IAttestationReportService service,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(artifactDigest))
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Artifact digest is required.",
"ERR_ATTEST_010"));
}
var report = await service.GetReportAsync(artifactDigest, cancellationToken).ConfigureAwait(false);
if (report == null)
{
return Results.NotFound(CreateProblem(
"Report not found",
$"No attestation report found for artifact '{artifactDigest}'.",
"ERR_ATTEST_011"));
}
return Results.Ok(report);
}
private static async Task<IResult> ListReportsAsync(
[FromBody] AttestationReportQuery? query,
IAttestationReportService service,
CancellationToken cancellationToken)
{
var effectiveQuery = query ?? new AttestationReportQuery(
ArtifactDigests: null,
ArtifactUriPattern: null,
PolicyIds: null,
PredicateTypes: null,
StatusFilter: null,
FromTime: null,
ToTime: null,
IncludeDetails: true,
Limit: 100,
Offset: 0);
var response = await service.ListReportsAsync(effectiveQuery, cancellationToken).ConfigureAwait(false);
return Results.Ok(response);
}
private static async Task<IResult> VerifyArtifactAsync(
[FromBody] VerifyArtifactRequest? request,
IAttestationReportService service,
CancellationToken cancellationToken)
{
if (request == null)
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Request body is required.",
"ERR_ATTEST_001"));
}
if (string.IsNullOrWhiteSpace(request.ArtifactDigest))
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Artifact digest is required.",
"ERR_ATTEST_010"));
}
var report = await service.GenerateReportAsync(request, cancellationToken).ConfigureAwait(false);
return Results.Ok(report);
}
private static async Task<IResult> GetStatisticsAsync(
[FromQuery] string? policyIds,
[FromQuery] string? predicateTypes,
[FromQuery] string? status,
[FromQuery] DateTimeOffset? fromTime,
[FromQuery] DateTimeOffset? toTime,
IAttestationReportService service,
CancellationToken cancellationToken)
{
AttestationReportQuery? filter = null;
if (!string.IsNullOrWhiteSpace(policyIds) ||
!string.IsNullOrWhiteSpace(predicateTypes) ||
!string.IsNullOrWhiteSpace(status) ||
fromTime.HasValue ||
toTime.HasValue)
{
filter = new AttestationReportQuery(
ArtifactDigests: null,
ArtifactUriPattern: null,
PolicyIds: string.IsNullOrWhiteSpace(policyIds) ? null : policyIds.Split(',').ToList(),
PredicateTypes: string.IsNullOrWhiteSpace(predicateTypes) ? null : predicateTypes.Split(',').ToList(),
StatusFilter: string.IsNullOrWhiteSpace(status)
? null
: status.Split(',')
.Select(s => Enum.TryParse<AttestationReportStatus>(s, true, out var parsed) ? parsed : (AttestationReportStatus?)null)
.Where(s => s.HasValue)
.Select(s => s!.Value)
.ToList(),
FromTime: fromTime,
ToTime: toTime,
IncludeDetails: false,
Limit: int.MaxValue,
Offset: 0);
}
var statistics = await service.GetStatisticsAsync(filter, cancellationToken).ConfigureAwait(false);
return Results.Ok(statistics);
}
private static async Task<IResult> StoreReportAsync(
[FromBody] StoreReportRequest? request,
IAttestationReportService service,
CancellationToken cancellationToken)
{
if (request?.Report == null)
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Report is required.",
"ERR_ATTEST_012"));
}
TimeSpan? ttl = request.TtlSeconds.HasValue
? TimeSpan.FromSeconds(request.TtlSeconds.Value)
: null;
var stored = await service.StoreReportAsync(request.Report, ttl, cancellationToken).ConfigureAwait(false);
return Results.Created(
$"/api/v1/attestor/reports/{stored.Report.ArtifactDigest}",
stored);
}
private static async Task<IResult> PurgeExpiredAsync(
IAttestationReportService service,
CancellationToken cancellationToken)
{
var count = await service.PurgeExpiredReportsAsync(cancellationToken).ConfigureAwait(false);
return Results.Ok(new PurgeExpiredResponse(PurgedCount: count));
}
private static ProblemDetails CreateProblem(string title, string detail, string? errorCode = null)
{
var problem = new ProblemDetails
{
Title = title,
Detail = detail,
Status = StatusCodes.Status400BadRequest
};
if (!string.IsNullOrWhiteSpace(errorCode))
{
problem.Extensions["error_code"] = errorCode;
}
return problem;
}
}
/// <summary>
/// Request to store an attestation report.
/// </summary>
public sealed record StoreReportRequest(
[property: System.Text.Json.Serialization.JsonPropertyName("report")] ArtifactAttestationReport Report,
[property: System.Text.Json.Serialization.JsonPropertyName("ttl_seconds")] int? TtlSeconds);
/// <summary>
/// Response from purging expired reports.
/// </summary>
public sealed record PurgeExpiredResponse(
[property: System.Text.Json.Serialization.JsonPropertyName("purged_count")] int PurgedCount);

View File

@@ -0,0 +1,125 @@
using Microsoft.AspNetCore.Mvc;
using StellaOps.Auth.Abstractions;
using StellaOps.Policy.Engine.ConsoleSurface;
using StellaOps.Policy.Engine.Options;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Console endpoints for attestation reports per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
internal static class ConsoleAttestationReportEndpoints
{
public static IEndpointRouteBuilder MapConsoleAttestationReports(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/policy/console/attestation")
.WithTags("Console Attestation Reports")
.RequireRateLimiting(PolicyEngineRateLimitOptions.PolicyName);
group.MapPost("/reports", QueryReportsAsync)
.WithName("PolicyEngine.ConsoleAttestationReports")
.WithSummary("Query attestation reports for Console")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<ConsoleAttestationReportResponse>(StatusCodes.Status200OK)
.ProducesValidationProblem();
group.MapPost("/dashboard", GetDashboardAsync)
.WithName("PolicyEngine.ConsoleAttestationDashboard")
.WithSummary("Get attestation dashboard for Console")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<ConsoleAttestationDashboardResponse>(StatusCodes.Status200OK)
.ProducesValidationProblem();
group.MapGet("/report/{artifactDigest}", GetReportAsync)
.WithName("PolicyEngine.ConsoleGetAttestationReport")
.WithSummary("Get attestation report for a specific artifact")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<ConsoleArtifactReport>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound);
return routes;
}
private static async Task<IResult> QueryReportsAsync(
[FromBody] ConsoleAttestationReportRequest? request,
ConsoleAttestationReportService service,
CancellationToken cancellationToken)
{
if (request is null)
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["request"] = ["Request body is required."]
});
}
if (request.Page < 1)
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["page"] = ["Page must be at least 1."]
});
}
if (request.PageSize < 1 || request.PageSize > 100)
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["pageSize"] = ["Page size must be between 1 and 100."]
});
}
var response = await service.QueryReportsAsync(request, cancellationToken).ConfigureAwait(false);
return Results.Json(response);
}
private static async Task<IResult> GetDashboardAsync(
[FromBody] ConsoleAttestationDashboardRequest? request,
ConsoleAttestationReportService service,
CancellationToken cancellationToken)
{
var effectiveRequest = request ?? new ConsoleAttestationDashboardRequest(
TimeRange: "24h",
PolicyIds: null,
ArtifactUriPattern: null);
var response = await service.GetDashboardAsync(effectiveRequest, cancellationToken).ConfigureAwait(false);
return Results.Json(response);
}
private static async Task<IResult> GetReportAsync(
[FromRoute] string artifactDigest,
ConsoleAttestationReportService service,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(artifactDigest))
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["artifactDigest"] = ["Artifact digest is required."]
});
}
var request = new ConsoleAttestationReportRequest(
ArtifactDigests: [artifactDigest],
ArtifactUriPattern: null,
PolicyIds: null,
PredicateTypes: null,
StatusFilter: null,
FromTime: null,
ToTime: null,
GroupBy: null,
SortBy: null,
Page: 1,
PageSize: 1);
var response = await service.QueryReportsAsync(request, cancellationToken).ConfigureAwait(false);
if (response.Reports.Count == 0)
{
return Results.NotFound();
}
return Results.Json(response.Reports[0]);
}
}

View File

@@ -0,0 +1,396 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using StellaOps.Auth.Abstractions;
using StellaOps.Policy.Engine.Services;
using StellaOps.Policy.RiskProfile.Scope;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Endpoints for managing effective policies per CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008.
/// </summary>
internal static class EffectivePolicyEndpoints
{
public static IEndpointRouteBuilder MapEffectivePolicies(this IEndpointRouteBuilder endpoints)
{
var group = endpoints.MapGroup("/api/v1/authority/effective-policies")
.RequireAuthorization()
.WithTags("Effective Policies");
group.MapPost("/", CreateEffectivePolicy)
.WithName("CreateEffectivePolicy")
.WithSummary("Create a new effective policy with subject pattern and priority.")
.Produces<EffectivePolicyResponse>(StatusCodes.Status201Created)
.Produces<ProblemHttpResult>(StatusCodes.Status400BadRequest);
group.MapGet("/{effectivePolicyId}", GetEffectivePolicy)
.WithName("GetEffectivePolicy")
.WithSummary("Get an effective policy by ID.")
.Produces<EffectivePolicyResponse>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
group.MapPut("/{effectivePolicyId}", UpdateEffectivePolicy)
.WithName("UpdateEffectivePolicy")
.WithSummary("Update an effective policy's priority, expiration, or scopes.")
.Produces<EffectivePolicyResponse>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
group.MapDelete("/{effectivePolicyId}", DeleteEffectivePolicy)
.WithName("DeleteEffectivePolicy")
.WithSummary("Delete an effective policy.")
.Produces(StatusCodes.Status204NoContent)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
group.MapGet("/", ListEffectivePolicies)
.WithName("ListEffectivePolicies")
.WithSummary("List effective policies with optional filtering.")
.Produces<EffectivePolicyListResponse>(StatusCodes.Status200OK);
// Scope attachments
var scopeGroup = endpoints.MapGroup("/api/v1/authority/scope-attachments")
.RequireAuthorization()
.WithTags("Authority Scope Attachments");
scopeGroup.MapPost("/", AttachScope)
.WithName("AttachAuthorityScope")
.WithSummary("Attach an authorization scope to an effective policy.")
.Produces<AuthorityScopeAttachmentResponse>(StatusCodes.Status201Created)
.Produces<ProblemHttpResult>(StatusCodes.Status400BadRequest);
scopeGroup.MapDelete("/{attachmentId}", DetachScope)
.WithName("DetachAuthorityScope")
.WithSummary("Detach an authorization scope.")
.Produces(StatusCodes.Status204NoContent)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
scopeGroup.MapGet("/policy/{effectivePolicyId}", GetPolicyScopeAttachments)
.WithName("GetPolicyScopeAttachments")
.WithSummary("Get all scope attachments for an effective policy.")
.Produces<AuthorityScopeAttachmentListResponse>(StatusCodes.Status200OK);
// Resolution
var resolveGroup = endpoints.MapGroup("/api/v1/authority")
.RequireAuthorization()
.WithTags("Policy Resolution");
resolveGroup.MapGet("/resolve", ResolveEffectivePolicy)
.WithName("ResolveEffectivePolicy")
.WithSummary("Resolve the effective policy for a subject.")
.Produces<EffectivePolicyResolutionResponse>(StatusCodes.Status200OK);
return endpoints;
}
private static IResult CreateEffectivePolicy(
HttpContext context,
[FromBody] CreateEffectivePolicyRequest request,
EffectivePolicyService policyService,
IEffectivePolicyAuditor auditor)
{
var scopeResult = RequireEffectiveWriteScope(context);
if (scopeResult is not null)
{
return scopeResult;
}
if (request == null)
{
return Results.BadRequest(CreateProblem("Invalid request", "Request body is required."));
}
try
{
var actorId = ResolveActorId(context);
var policy = policyService.Create(request, actorId);
// Audit per CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008
auditor.RecordCreated(policy, actorId);
return Results.Created(
$"/api/v1/authority/effective-policies/{policy.EffectivePolicyId}",
new EffectivePolicyResponse(policy));
}
catch (ArgumentException ex)
{
return Results.BadRequest(CreateProblem("Invalid request", ex.Message, "ERR_AUTH_001"));
}
}
private static IResult GetEffectivePolicy(
HttpContext context,
[FromRoute] string effectivePolicyId,
EffectivePolicyService policyService)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyRead);
if (scopeResult is not null)
{
return scopeResult;
}
var policy = policyService.Get(effectivePolicyId);
if (policy == null)
{
return Results.NotFound(CreateProblem(
"Policy not found",
$"Effective policy '{effectivePolicyId}' was not found.",
"ERR_AUTH_002"));
}
return Results.Ok(new EffectivePolicyResponse(policy));
}
private static IResult UpdateEffectivePolicy(
HttpContext context,
[FromRoute] string effectivePolicyId,
[FromBody] UpdateEffectivePolicyRequest request,
EffectivePolicyService policyService,
IEffectivePolicyAuditor auditor)
{
var scopeResult = RequireEffectiveWriteScope(context);
if (scopeResult is not null)
{
return scopeResult;
}
if (request == null)
{
return Results.BadRequest(CreateProblem("Invalid request", "Request body is required."));
}
var actorId = ResolveActorId(context);
var policy = policyService.Update(effectivePolicyId, request, actorId);
if (policy == null)
{
return Results.NotFound(CreateProblem(
"Policy not found",
$"Effective policy '{effectivePolicyId}' was not found.",
"ERR_AUTH_002"));
}
// Audit per CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008
auditor.RecordUpdated(policy, actorId, request);
return Results.Ok(new EffectivePolicyResponse(policy));
}
private static IResult DeleteEffectivePolicy(
HttpContext context,
[FromRoute] string effectivePolicyId,
EffectivePolicyService policyService,
IEffectivePolicyAuditor auditor)
{
var scopeResult = RequireEffectiveWriteScope(context);
if (scopeResult is not null)
{
return scopeResult;
}
if (!policyService.Delete(effectivePolicyId))
{
return Results.NotFound(CreateProblem(
"Policy not found",
$"Effective policy '{effectivePolicyId}' was not found.",
"ERR_AUTH_002"));
}
// Audit per CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008
var actorId = ResolveActorId(context);
auditor.RecordDeleted(effectivePolicyId, actorId);
return Results.NoContent();
}
private static IResult ListEffectivePolicies(
HttpContext context,
[FromQuery] string? tenantId,
[FromQuery] string? policyId,
[FromQuery] bool enabledOnly,
[FromQuery] bool includeExpired,
[FromQuery] int limit,
EffectivePolicyService policyService)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyRead);
if (scopeResult is not null)
{
return scopeResult;
}
var query = new EffectivePolicyQuery(
TenantId: tenantId,
PolicyId: policyId,
EnabledOnly: enabledOnly,
IncludeExpired: includeExpired,
Limit: limit > 0 ? limit : 100);
var policies = policyService.Query(query);
return Results.Ok(new EffectivePolicyListResponse(policies, policies.Count));
}
private static IResult AttachScope(
HttpContext context,
[FromBody] AttachAuthorityScopeRequest request,
EffectivePolicyService policyService,
IEffectivePolicyAuditor auditor)
{
var scopeResult = RequireEffectiveWriteScope(context);
if (scopeResult is not null)
{
return scopeResult;
}
if (request == null)
{
return Results.BadRequest(CreateProblem("Invalid request", "Request body is required."));
}
try
{
var attachment = policyService.AttachScope(request);
// Audit per CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008
var actorId = ResolveActorId(context);
auditor.RecordScopeAttached(attachment, actorId);
return Results.Created(
$"/api/v1/authority/scope-attachments/{attachment.AttachmentId}",
new AuthorityScopeAttachmentResponse(attachment));
}
catch (ArgumentException ex)
{
var code = ex.Message.Contains("not found") ? "ERR_AUTH_002" : "ERR_AUTH_004";
return Results.BadRequest(CreateProblem("Invalid request", ex.Message, code));
}
}
private static IResult DetachScope(
HttpContext context,
[FromRoute] string attachmentId,
EffectivePolicyService policyService,
IEffectivePolicyAuditor auditor)
{
var scopeResult = RequireEffectiveWriteScope(context);
if (scopeResult is not null)
{
return scopeResult;
}
if (!policyService.DetachScope(attachmentId))
{
return Results.NotFound(CreateProblem(
"Attachment not found",
$"Scope attachment '{attachmentId}' was not found."));
}
// Audit per CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008
var actorId = ResolveActorId(context);
auditor.RecordScopeDetached(attachmentId, actorId);
return Results.NoContent();
}
private static IResult GetPolicyScopeAttachments(
HttpContext context,
[FromRoute] string effectivePolicyId,
EffectivePolicyService policyService)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyRead);
if (scopeResult is not null)
{
return scopeResult;
}
var attachments = policyService.GetScopeAttachments(effectivePolicyId);
return Results.Ok(new AuthorityScopeAttachmentListResponse(attachments));
}
private static IResult ResolveEffectivePolicy(
HttpContext context,
[FromQuery] string subject,
[FromQuery] string? tenantId,
EffectivePolicyService policyService)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyRead);
if (scopeResult is not null)
{
return scopeResult;
}
if (string.IsNullOrWhiteSpace(subject))
{
return Results.BadRequest(CreateProblem("Invalid request", "Subject is required."));
}
var result = policyService.Resolve(subject, tenantId);
return Results.Ok(new EffectivePolicyResolutionResponse(result));
}
private static IResult? RequireEffectiveWriteScope(HttpContext context)
{
// Check for effective:write scope per CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008
// Primary scope: effective:write (StellaOpsScopes.EffectiveWrite)
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.EffectiveWrite);
if (scopeResult is not null)
{
// Fall back to policy:edit for backwards compatibility during migration
// TODO: Remove fallback after migration period (track in POLICY-AOC-19-002)
return ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyEdit);
}
return null;
}
private static string? ResolveActorId(HttpContext context)
{
var user = context.User;
var actor = user?.FindFirst(ClaimTypes.NameIdentifier)?.Value
?? user?.FindFirst(ClaimTypes.Upn)?.Value
?? user?.FindFirst("sub")?.Value;
if (!string.IsNullOrWhiteSpace(actor))
{
return actor;
}
if (context.Request.Headers.TryGetValue("X-StellaOps-Actor", out var header) && !string.IsNullOrWhiteSpace(header))
{
return header.ToString();
}
return null;
}
private static ProblemDetails CreateProblem(string title, string detail, string? errorCode = null)
{
var problem = new ProblemDetails
{
Title = title,
Detail = detail,
Status = StatusCodes.Status400BadRequest
};
if (!string.IsNullOrWhiteSpace(errorCode))
{
problem.Extensions["error_code"] = errorCode;
}
return problem;
}
}
#region Response DTOs
internal sealed record EffectivePolicyResponse(EffectivePolicy EffectivePolicy);
internal sealed record EffectivePolicyListResponse(IReadOnlyList<EffectivePolicy> Items, int Total);
internal sealed record AuthorityScopeAttachmentResponse(AuthorityScopeAttachment Attachment);
internal sealed record AuthorityScopeAttachmentListResponse(IReadOnlyList<AuthorityScopeAttachment> Attachments);
internal sealed record EffectivePolicyResolutionResponse(EffectivePolicyResolutionResult Result);
#endregion

View File

@@ -0,0 +1,241 @@
using Microsoft.AspNetCore.Mvc;
using StellaOps.Policy.Engine.DeterminismGuard;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Endpoints for policy code linting and determinism analysis.
/// Implements POLICY-AOC-19-001 per docs/modules/policy/design/policy-aoc-linting-rules.md.
/// </summary>
public static class PolicyLintEndpoints
{
public static IEndpointRouteBuilder MapPolicyLint(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/api/v1/policy/lint");
group.MapPost("/analyze", AnalyzeSourceAsync)
.WithName("Policy.Lint.Analyze")
.WithDescription("Analyze source code for determinism violations")
.RequireAuthorization(policy => policy.RequireClaim("scope", "policy:read"));
group.MapPost("/analyze-batch", AnalyzeBatchAsync)
.WithName("Policy.Lint.AnalyzeBatch")
.WithDescription("Analyze multiple source files for determinism violations")
.RequireAuthorization(policy => policy.RequireClaim("scope", "policy:read"));
group.MapGet("/rules", GetLintRulesAsync)
.WithName("Policy.Lint.GetRules")
.WithDescription("Get available lint rules and their severities")
.AllowAnonymous();
return routes;
}
private static Task<IResult> AnalyzeSourceAsync(
[FromBody] LintSourceRequest request,
CancellationToken cancellationToken)
{
if (request is null || string.IsNullOrWhiteSpace(request.Source))
{
return Task.FromResult(Results.BadRequest(new
{
error = "LINT_SOURCE_REQUIRED",
message = "Source code is required"
}));
}
var analyzer = new ProhibitedPatternAnalyzer();
var options = new DeterminismGuardOptions
{
EnforcementEnabled = request.EnforceErrors ?? true,
FailOnSeverity = ParseSeverity(request.MinSeverity),
EnableStaticAnalysis = true,
EnableRuntimeMonitoring = false
};
var result = analyzer.AnalyzeSource(request.Source, request.FileName, options);
return Task.FromResult(Results.Ok(new LintResultResponse
{
Passed = result.Passed,
Violations = result.Violations.Select(MapViolation).ToList(),
CountBySeverity = result.CountBySeverity.ToDictionary(
kvp => kvp.Key.ToString().ToLowerInvariant(),
kvp => kvp.Value),
AnalysisDurationMs = result.AnalysisDurationMs,
EnforcementEnabled = result.EnforcementEnabled
}));
}
private static Task<IResult> AnalyzeBatchAsync(
[FromBody] LintBatchRequest request,
CancellationToken cancellationToken)
{
if (request?.Files is null || request.Files.Count == 0)
{
return Task.FromResult(Results.BadRequest(new
{
error = "LINT_FILES_REQUIRED",
message = "At least one file is required"
}));
}
var analyzer = new ProhibitedPatternAnalyzer();
var options = new DeterminismGuardOptions
{
EnforcementEnabled = request.EnforceErrors ?? true,
FailOnSeverity = ParseSeverity(request.MinSeverity),
EnableStaticAnalysis = true,
EnableRuntimeMonitoring = false
};
var sources = request.Files.Select(f => (f.Source, f.FileName));
var result = analyzer.AnalyzeMultiple(sources, options);
return Task.FromResult(Results.Ok(new LintResultResponse
{
Passed = result.Passed,
Violations = result.Violations.Select(MapViolation).ToList(),
CountBySeverity = result.CountBySeverity.ToDictionary(
kvp => kvp.Key.ToString().ToLowerInvariant(),
kvp => kvp.Value),
AnalysisDurationMs = result.AnalysisDurationMs,
EnforcementEnabled = result.EnforcementEnabled
}));
}
private static Task<IResult> GetLintRulesAsync(CancellationToken cancellationToken)
{
var rules = new List<LintRuleInfo>
{
// Wall-clock rules
new("DET-001", "DateTime.Now", "error", "WallClock", "Use TimeProvider.GetUtcNow()"),
new("DET-002", "DateTime.UtcNow", "error", "WallClock", "Use TimeProvider.GetUtcNow()"),
new("DET-003", "DateTimeOffset.Now", "error", "WallClock", "Use TimeProvider.GetUtcNow()"),
new("DET-004", "DateTimeOffset.UtcNow", "error", "WallClock", "Use TimeProvider.GetUtcNow()"),
// Random/GUID rules
new("DET-005", "Guid.NewGuid()", "error", "GuidGeneration", "Use StableIdGenerator or content hash"),
new("DET-006", "new Random()", "error", "RandomNumber", "Use seeded random or remove"),
new("DET-007", "RandomNumberGenerator", "error", "RandomNumber", "Remove from evaluation path"),
// Network/Filesystem rules
new("DET-008", "HttpClient in eval", "critical", "NetworkAccess", "Remove network from eval path"),
new("DET-009", "File.Read* in eval", "critical", "FileSystemAccess", "Remove filesystem from eval path"),
// Ordering rules
new("DET-010", "Dictionary iteration", "warning", "UnstableIteration", "Use OrderBy or SortedDictionary"),
new("DET-011", "HashSet iteration", "warning", "UnstableIteration", "Use OrderBy or SortedSet"),
// Environment rules
new("DET-012", "Environment.GetEnvironmentVariable", "error", "EnvironmentAccess", "Use evaluation context"),
new("DET-013", "Environment.MachineName", "warning", "EnvironmentAccess", "Remove host-specific info")
};
return Task.FromResult(Results.Ok(new
{
rules,
categories = new[]
{
"WallClock",
"RandomNumber",
"GuidGeneration",
"NetworkAccess",
"FileSystemAccess",
"EnvironmentAccess",
"UnstableIteration",
"FloatingPointHazard",
"ConcurrencyHazard"
},
severities = new[] { "info", "warning", "error", "critical" }
}));
}
private static DeterminismViolationSeverity ParseSeverity(string? severity)
{
return severity?.ToLowerInvariant() switch
{
"info" => DeterminismViolationSeverity.Info,
"warning" => DeterminismViolationSeverity.Warning,
"error" => DeterminismViolationSeverity.Error,
"critical" => DeterminismViolationSeverity.Critical,
_ => DeterminismViolationSeverity.Error
};
}
private static LintViolationResponse MapViolation(DeterminismViolation v)
{
return new LintViolationResponse
{
Category = v.Category.ToString(),
ViolationType = v.ViolationType,
Message = v.Message,
Severity = v.Severity.ToString().ToLowerInvariant(),
SourceFile = v.SourceFile,
LineNumber = v.LineNumber,
MemberName = v.MemberName,
Remediation = v.Remediation
};
}
}
/// <summary>
/// Request for single source analysis.
/// </summary>
public sealed record LintSourceRequest(
string Source,
string? FileName = null,
string? MinSeverity = null,
bool? EnforceErrors = null);
/// <summary>
/// Request for batch source analysis.
/// </summary>
public sealed record LintBatchRequest(
List<LintFileInput> Files,
string? MinSeverity = null,
bool? EnforceErrors = null);
/// <summary>
/// Single file input for batch analysis.
/// </summary>
public sealed record LintFileInput(
string Source,
string FileName);
/// <summary>
/// Response for lint analysis.
/// </summary>
public sealed record LintResultResponse
{
public required bool Passed { get; init; }
public required List<LintViolationResponse> Violations { get; init; }
public required Dictionary<string, int> CountBySeverity { get; init; }
public required long AnalysisDurationMs { get; init; }
public required bool EnforcementEnabled { get; init; }
}
/// <summary>
/// Single violation in lint response.
/// </summary>
public sealed record LintViolationResponse
{
public required string Category { get; init; }
public required string ViolationType { get; init; }
public required string Message { get; init; }
public required string Severity { get; init; }
public string? SourceFile { get; init; }
public int? LineNumber { get; init; }
public string? MemberName { get; init; }
public string? Remediation { get; init; }
}
/// <summary>
/// Lint rule information.
/// </summary>
public sealed record LintRuleInfo(
string RuleId,
string Name,
string DefaultSeverity,
string Category,
string Remediation);

View File

@@ -14,11 +14,15 @@ public static class PolicyPackBundleEndpoints
group.MapPost("", RegisterBundleAsync)
.WithName("AirGap.RegisterBundle")
.WithDescription("Register a bundle for import");
.WithDescription("Register a bundle for import")
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status403Forbidden)
.ProducesProblem(StatusCodes.Status412PreconditionFailed);
group.MapGet("{bundleId}", GetBundleStatusAsync)
.WithName("AirGap.GetBundleStatus")
.WithDescription("Get bundle import status");
.WithDescription("Get bundle import status")
.ProducesProblem(StatusCodes.Status404NotFound);
group.MapGet("", ListBundlesAsync)
.WithName("AirGap.ListBundles")
@@ -47,13 +51,24 @@ public static class PolicyPackBundleEndpoints
var response = await service.RegisterBundleAsync(tenantId, request, cancellationToken).ConfigureAwait(false);
return Results.Accepted($"/api/v1/airgap/bundles/{response.ImportId}", response);
}
catch (SealedModeException ex)
{
return SealedModeResultHelper.ToProblem(ex);
}
catch (InvalidOperationException ex) when (ex.Message.Contains("Bundle import blocked"))
{
// Sealed-mode enforcement blocked the import
return SealedModeResultHelper.ToProblem(
SealedModeErrorCodes.ImportBlocked,
ex.Message,
"Ensure time anchor is fresh before importing bundles");
}
catch (ArgumentException ex)
{
return Results.Problem(
title: "Invalid request",
detail: ex.Message,
statusCode: 400,
extensions: new Dictionary<string, object?> { ["code"] = "INVALID_REQUEST" });
return SealedModeResultHelper.ToProblem(
SealedModeErrorCodes.BundleInvalid,
ex.Message,
"Verify request parameters are valid");
}
}

View File

@@ -0,0 +1,283 @@
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using StellaOps.Auth.Abstractions;
using StellaOps.Policy.Engine.AirGap;
using StellaOps.Policy.Engine.Services;
using StellaOps.Policy.RiskProfile.Models;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Endpoints for air-gap risk profile export/import per CONTRACT-MIRROR-BUNDLE-003.
/// </summary>
public static class RiskProfileAirGapEndpoints
{
public static IEndpointRouteBuilder MapRiskProfileAirGap(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/api/v1/airgap/risk-profiles")
.RequireAuthorization()
.WithTags("Air-Gap Risk Profiles");
group.MapPost("/export", ExportProfilesAsync)
.WithName("AirGap.ExportRiskProfiles")
.WithSummary("Export risk profiles as an air-gap compatible bundle with signatures.")
.Produces<RiskProfileAirGapBundle>(StatusCodes.Status200OK)
.Produces<ProblemDetails>(StatusCodes.Status400BadRequest);
group.MapPost("/export/download", DownloadBundleAsync)
.WithName("AirGap.DownloadRiskProfileBundle")
.WithSummary("Export and download risk profiles as an air-gap compatible JSON file.")
.Produces<FileContentHttpResult>(StatusCodes.Status200OK, contentType: "application/json");
group.MapPost("/import", ImportProfilesAsync)
.WithName("AirGap.ImportRiskProfiles")
.WithSummary("Import risk profiles from an air-gap bundle with sealed-mode enforcement.")
.Produces<RiskProfileAirGapImportResult>(StatusCodes.Status200OK)
.Produces<ProblemDetails>(StatusCodes.Status400BadRequest)
.Produces<ProblemDetails>(StatusCodes.Status403Forbidden)
.Produces<ProblemDetails>(StatusCodes.Status412PreconditionFailed);
group.MapPost("/verify", VerifyBundleAsync)
.WithName("AirGap.VerifyRiskProfileBundle")
.WithSummary("Verify the integrity of an air-gap bundle without importing.")
.Produces<AirGapBundleVerification>(StatusCodes.Status200OK);
return routes;
}
private static async Task<IResult> ExportProfilesAsync(
HttpContext context,
[FromBody] AirGapProfileExportRequest request,
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
RiskProfileConfigurationService profileService,
RiskProfileAirGapExportService exportService,
CancellationToken cancellationToken)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyRead);
if (scopeResult is not null)
{
return scopeResult;
}
if (request == null || request.ProfileIds == null || request.ProfileIds.Count == 0)
{
return Results.Problem(
title: "Invalid request",
detail: "At least one profile ID is required.",
statusCode: 400);
}
var profiles = new List<RiskProfileModel>();
var notFound = new List<string>();
foreach (var profileId in request.ProfileIds)
{
var profile = profileService.GetProfile(profileId);
if (profile != null)
{
profiles.Add(profile);
}
else
{
notFound.Add(profileId);
}
}
if (notFound.Count > 0)
{
return Results.Problem(
title: "Profiles not found",
detail: $"The following profiles were not found: {string.Join(", ", notFound)}",
statusCode: 400);
}
var exportRequest = new AirGapExportRequest(
SignBundle: request.SignBundle,
KeyId: request.KeyId,
TargetRepository: request.TargetRepository,
DisplayName: request.DisplayName);
var bundle = await exportService.ExportAsync(
profiles, exportRequest, tenantId, cancellationToken).ConfigureAwait(false);
return Results.Ok(bundle);
}
private static async Task<IResult> DownloadBundleAsync(
HttpContext context,
[FromBody] AirGapProfileExportRequest request,
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
RiskProfileConfigurationService profileService,
RiskProfileAirGapExportService exportService,
CancellationToken cancellationToken)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyRead);
if (scopeResult is not null)
{
return scopeResult;
}
if (request == null || request.ProfileIds == null || request.ProfileIds.Count == 0)
{
return Results.Problem(
title: "Invalid request",
detail: "At least one profile ID is required.",
statusCode: 400);
}
var profiles = new List<RiskProfileModel>();
foreach (var profileId in request.ProfileIds)
{
var profile = profileService.GetProfile(profileId);
if (profile != null)
{
profiles.Add(profile);
}
}
var exportRequest = new AirGapExportRequest(
SignBundle: request.SignBundle,
KeyId: request.KeyId,
TargetRepository: request.TargetRepository,
DisplayName: request.DisplayName);
var bundle = await exportService.ExportAsync(
profiles, exportRequest, tenantId, cancellationToken).ConfigureAwait(false);
var json = System.Text.Json.JsonSerializer.Serialize(bundle, new System.Text.Json.JsonSerializerOptions
{
WriteIndented = false,
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
});
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
var fileName = $"risk-profiles-airgap-{DateTime.UtcNow:yyyyMMddHHmmss}.json";
return Results.File(bytes, "application/json", fileName);
}
private static async Task<IResult> ImportProfilesAsync(
HttpContext context,
[FromBody] AirGapProfileImportRequest request,
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
RiskProfileAirGapExportService exportService,
CancellationToken cancellationToken)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyEdit);
if (scopeResult is not null)
{
return scopeResult;
}
if (request == null || request.Bundle == null)
{
return Results.Problem(
title: "Invalid request",
detail: "Bundle is required.",
statusCode: 400);
}
if (string.IsNullOrWhiteSpace(tenantId))
{
return Results.Problem(
title: "Tenant ID required",
detail: "X-Tenant-Id header is required for air-gap import.",
statusCode: 400,
extensions: new Dictionary<string, object?> { ["code"] = "TENANT_REQUIRED" });
}
var importRequest = new AirGapImportRequest(
VerifySignature: request.VerifySignature,
VerifyMerkle: request.VerifyMerkle,
EnforceSealedMode: request.EnforceSealedMode,
RejectOnSignatureFailure: request.RejectOnSignatureFailure,
RejectOnMerkleFailure: request.RejectOnMerkleFailure);
try
{
var result = await exportService.ImportAsync(
request.Bundle, importRequest, tenantId, cancellationToken).ConfigureAwait(false);
if (!result.Success)
{
var extensions = new Dictionary<string, object?>
{
["errors"] = result.Errors,
["signatureVerified"] = result.SignatureVerified,
["merkleVerified"] = result.MerkleVerified
};
// Check if it's a sealed-mode enforcement failure
if (result.Errors.Any(e => e.Contains("Sealed-mode")))
{
return Results.Problem(
title: "Import blocked by sealed mode",
detail: result.Errors.FirstOrDefault() ?? "Sealed mode enforcement failed",
statusCode: 412,
extensions: extensions);
}
return Results.Problem(
title: "Import failed",
detail: $"Import completed with {result.ErrorCount} errors",
statusCode: 400,
extensions: extensions);
}
return Results.Ok(result);
}
catch (SealedModeException ex)
{
return SealedModeResultHelper.ToProblem(ex);
}
}
private static IResult VerifyBundleAsync(
HttpContext context,
[FromBody] RiskProfileAirGapBundle bundle,
RiskProfileAirGapExportService exportService)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyRead);
if (scopeResult is not null)
{
return scopeResult;
}
if (bundle == null)
{
return Results.Problem(
title: "Invalid request",
detail: "Bundle is required.",
statusCode: 400);
}
var verification = exportService.Verify(bundle);
return Results.Ok(verification);
}
}
#region Request DTOs
/// <summary>
/// Request to export profiles as an air-gap bundle.
/// </summary>
public sealed record AirGapProfileExportRequest(
IReadOnlyList<string> ProfileIds,
bool SignBundle = true,
string? KeyId = null,
string? TargetRepository = null,
string? DisplayName = null);
/// <summary>
/// Request to import profiles from an air-gap bundle.
/// </summary>
public sealed record AirGapProfileImportRequest(
RiskProfileAirGapBundle Bundle,
bool VerifySignature = true,
bool VerifyMerkle = true,
bool EnforceSealedMode = true,
bool RejectOnSignatureFailure = true,
bool RejectOnMerkleFailure = true);
#endregion

View File

@@ -7,6 +7,10 @@ using StellaOps.Policy.Engine.Simulation;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Risk simulation endpoints for Policy Engine and Policy Studio.
/// Enhanced with detailed analytics per POLICY-RISK-68-001.
/// </summary>
internal static class RiskSimulationEndpoints
{
public static IEndpointRouteBuilder MapRiskSimulation(this IEndpointRouteBuilder endpoints)
@@ -42,6 +46,28 @@ internal static class RiskSimulationEndpoints
.Produces<WhatIfSimulationResponse>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status400BadRequest);
// Policy Studio specific endpoints per POLICY-RISK-68-001
group.MapPost("/studio/analyze", RunStudioAnalysis)
.WithName("RunPolicyStudioAnalysis")
.WithSummary("Run a detailed analysis for Policy Studio with full breakdown analytics.")
.WithDescription("Provides comprehensive breakdown including signal analysis, override tracking, score distributions, and component breakdowns for policy authoring.")
.Produces<PolicyStudioAnalysisResponse>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status400BadRequest)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
group.MapPost("/studio/compare", CompareProfilesWithBreakdown)
.WithName("CompareProfilesWithBreakdown")
.WithSummary("Compare profiles with full breakdown analytics and trend analysis.")
.Produces<PolicyStudioComparisonResponse>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status400BadRequest);
group.MapPost("/studio/preview", PreviewProfileChanges)
.WithName("PreviewProfileChanges")
.WithSummary("Preview impact of profile changes before committing.")
.WithDescription("Simulates findings against both current and proposed profile to show impact.")
.Produces<ProfileChangePreviewResponse>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status400BadRequest);
return endpoints;
}
@@ -355,6 +381,344 @@ internal static class RiskSimulationEndpoints
ToHigher: worsened,
Unchanged: unchanged));
}
#region Policy Studio Endpoints (POLICY-RISK-68-001)
private static IResult RunStudioAnalysis(
HttpContext context,
[FromBody] PolicyStudioAnalysisRequest request,
RiskSimulationService simulationService)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyRead);
if (scopeResult is not null)
{
return scopeResult;
}
if (request == null || string.IsNullOrWhiteSpace(request.ProfileId))
{
return Results.BadRequest(new ProblemDetails
{
Title = "Invalid request",
Detail = "ProfileId is required.",
Status = StatusCodes.Status400BadRequest
});
}
if (request.Findings == null || request.Findings.Count == 0)
{
return Results.BadRequest(new ProblemDetails
{
Title = "Invalid request",
Detail = "At least one finding is required.",
Status = StatusCodes.Status400BadRequest
});
}
try
{
var breakdownOptions = request.BreakdownOptions ?? RiskSimulationBreakdownOptions.Default;
var result = simulationService.SimulateWithBreakdown(
new RiskSimulationRequest(
ProfileId: request.ProfileId,
ProfileVersion: request.ProfileVersion,
Findings: request.Findings,
IncludeContributions: true,
IncludeDistribution: true,
Mode: SimulationMode.Full),
breakdownOptions);
return Results.Ok(new PolicyStudioAnalysisResponse(
Result: result.Result,
Breakdown: result.Breakdown,
TotalExecutionTimeMs: result.TotalExecutionTimeMs));
}
catch (InvalidOperationException ex) when (ex.Message.Contains("not found"))
{
return Results.NotFound(new ProblemDetails
{
Title = "Profile not found",
Detail = ex.Message,
Status = StatusCodes.Status404NotFound
});
}
catch (InvalidOperationException ex) when (ex.Message.Contains("Breakdown service"))
{
return Results.Problem(
title: "Service unavailable",
detail: ex.Message,
statusCode: StatusCodes.Status503ServiceUnavailable);
}
}
private static IResult CompareProfilesWithBreakdown(
HttpContext context,
[FromBody] PolicyStudioComparisonRequest request,
RiskSimulationService simulationService)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyRead);
if (scopeResult is not null)
{
return scopeResult;
}
if (request == null ||
string.IsNullOrWhiteSpace(request.BaseProfileId) ||
string.IsNullOrWhiteSpace(request.CompareProfileId))
{
return Results.BadRequest(new ProblemDetails
{
Title = "Invalid request",
Detail = "Both BaseProfileId and CompareProfileId are required.",
Status = StatusCodes.Status400BadRequest
});
}
if (request.Findings == null || request.Findings.Count == 0)
{
return Results.BadRequest(new ProblemDetails
{
Title = "Invalid request",
Detail = "At least one finding is required.",
Status = StatusCodes.Status400BadRequest
});
}
try
{
var result = simulationService.CompareProfilesWithBreakdown(
request.BaseProfileId,
request.CompareProfileId,
request.Findings,
request.BreakdownOptions);
return Results.Ok(new PolicyStudioComparisonResponse(
BaselineResult: result.BaselineResult,
CompareResult: result.CompareResult,
Breakdown: result.Breakdown,
ExecutionTimeMs: result.ExecutionTimeMs));
}
catch (InvalidOperationException ex) when (ex.Message.Contains("not found"))
{
return Results.BadRequest(new ProblemDetails
{
Title = "Profile not found",
Detail = ex.Message,
Status = StatusCodes.Status400BadRequest
});
}
catch (InvalidOperationException ex) when (ex.Message.Contains("Breakdown service"))
{
return Results.Problem(
title: "Service unavailable",
detail: ex.Message,
statusCode: StatusCodes.Status503ServiceUnavailable);
}
}
private static IResult PreviewProfileChanges(
HttpContext context,
[FromBody] ProfileChangePreviewRequest request,
RiskSimulationService simulationService)
{
var scopeResult = ScopeAuthorization.RequireScope(context, StellaOpsScopes.PolicyRead);
if (scopeResult is not null)
{
return scopeResult;
}
if (request == null || string.IsNullOrWhiteSpace(request.CurrentProfileId))
{
return Results.BadRequest(new ProblemDetails
{
Title = "Invalid request",
Detail = "CurrentProfileId is required.",
Status = StatusCodes.Status400BadRequest
});
}
if (string.IsNullOrWhiteSpace(request.ProposedProfileId) &&
(request.ProposedWeightChanges == null || request.ProposedWeightChanges.Count == 0) &&
(request.ProposedOverrideChanges == null || request.ProposedOverrideChanges.Count == 0))
{
return Results.BadRequest(new ProblemDetails
{
Title = "Invalid request",
Detail = "Either ProposedProfileId or at least one proposed change is required.",
Status = StatusCodes.Status400BadRequest
});
}
try
{
// Run simulation against current profile
var currentRequest = new RiskSimulationRequest(
ProfileId: request.CurrentProfileId,
ProfileVersion: request.CurrentProfileVersion,
Findings: request.Findings,
IncludeContributions: true,
IncludeDistribution: true,
Mode: SimulationMode.Full);
var currentResult = simulationService.Simulate(currentRequest);
RiskSimulationResult proposedResult;
if (!string.IsNullOrWhiteSpace(request.ProposedProfileId))
{
// Compare against existing proposed profile
var proposedRequest = new RiskSimulationRequest(
ProfileId: request.ProposedProfileId,
ProfileVersion: request.ProposedProfileVersion,
Findings: request.Findings,
IncludeContributions: true,
IncludeDistribution: true,
Mode: SimulationMode.Full);
proposedResult = simulationService.Simulate(proposedRequest);
}
else
{
// Inline changes not yet supported - return preview of current only
proposedResult = currentResult;
}
var impactSummary = ComputePreviewImpact(currentResult, proposedResult);
return Results.Ok(new ProfileChangePreviewResponse(
CurrentResult: new ProfileSimulationSummary(
currentResult.ProfileId,
currentResult.ProfileVersion,
currentResult.AggregateMetrics),
ProposedResult: new ProfileSimulationSummary(
proposedResult.ProfileId,
proposedResult.ProfileVersion,
proposedResult.AggregateMetrics),
Impact: impactSummary,
HighImpactFindings: ComputeHighImpactFindings(currentResult, proposedResult)));
}
catch (InvalidOperationException ex) when (ex.Message.Contains("not found"))
{
return Results.NotFound(new ProblemDetails
{
Title = "Profile not found",
Detail = ex.Message,
Status = StatusCodes.Status404NotFound
});
}
}
private static ProfileChangeImpact ComputePreviewImpact(
RiskSimulationResult current,
RiskSimulationResult proposed)
{
var currentScores = current.FindingScores.ToDictionary(f => f.FindingId);
var proposedScores = proposed.FindingScores.ToDictionary(f => f.FindingId);
var improved = 0;
var worsened = 0;
var unchanged = 0;
var severityEscalations = 0;
var severityDeescalations = 0;
var actionChanges = 0;
foreach (var (findingId, currentScore) in currentScores)
{
if (!proposedScores.TryGetValue(findingId, out var proposedScore))
continue;
var scoreDelta = proposedScore.NormalizedScore - currentScore.NormalizedScore;
if (Math.Abs(scoreDelta) < 1.0)
unchanged++;
else if (scoreDelta < 0)
improved++;
else
worsened++;
if (proposedScore.Severity > currentScore.Severity)
severityEscalations++;
else if (proposedScore.Severity < currentScore.Severity)
severityDeescalations++;
if (proposedScore.RecommendedAction != currentScore.RecommendedAction)
actionChanges++;
}
return new ProfileChangeImpact(
FindingsImproved: improved,
FindingsWorsened: worsened,
FindingsUnchanged: unchanged,
SeverityEscalations: severityEscalations,
SeverityDeescalations: severityDeescalations,
ActionChanges: actionChanges,
MeanScoreDelta: proposed.AggregateMetrics.MeanScore - current.AggregateMetrics.MeanScore,
CriticalCountDelta: proposed.AggregateMetrics.CriticalCount - current.AggregateMetrics.CriticalCount,
HighCountDelta: proposed.AggregateMetrics.HighCount - current.AggregateMetrics.HighCount);
}
private static IReadOnlyList<HighImpactFindingPreview> ComputeHighImpactFindings(
RiskSimulationResult current,
RiskSimulationResult proposed)
{
var currentScores = current.FindingScores.ToDictionary(f => f.FindingId);
var proposedScores = proposed.FindingScores.ToDictionary(f => f.FindingId);
var highImpact = new List<HighImpactFindingPreview>();
foreach (var (findingId, currentScore) in currentScores)
{
if (!proposedScores.TryGetValue(findingId, out var proposedScore))
continue;
var scoreDelta = Math.Abs(proposedScore.NormalizedScore - currentScore.NormalizedScore);
var severityChanged = proposedScore.Severity != currentScore.Severity;
var actionChanged = proposedScore.RecommendedAction != currentScore.RecommendedAction;
if (scoreDelta > 10 || severityChanged || actionChanged)
{
highImpact.Add(new HighImpactFindingPreview(
FindingId: findingId,
CurrentScore: currentScore.NormalizedScore,
ProposedScore: proposedScore.NormalizedScore,
ScoreDelta: proposedScore.NormalizedScore - currentScore.NormalizedScore,
CurrentSeverity: currentScore.Severity.ToString(),
ProposedSeverity: proposedScore.Severity.ToString(),
CurrentAction: currentScore.RecommendedAction.ToString(),
ProposedAction: proposedScore.RecommendedAction.ToString(),
ImpactReason: DetermineImpactReason(currentScore, proposedScore)));
}
}
return highImpact
.OrderByDescending(f => Math.Abs(f.ScoreDelta))
.Take(20)
.ToList();
}
private static string DetermineImpactReason(FindingScore current, FindingScore proposed)
{
var reasons = new List<string>();
if (proposed.Severity != current.Severity)
{
reasons.Add($"Severity {(proposed.Severity > current.Severity ? "escalated" : "deescalated")} from {current.Severity} to {proposed.Severity}");
}
if (proposed.RecommendedAction != current.RecommendedAction)
{
reasons.Add($"Action changed from {current.RecommendedAction} to {proposed.RecommendedAction}");
}
var scoreDelta = proposed.NormalizedScore - current.NormalizedScore;
if (Math.Abs(scoreDelta) > 10)
{
reasons.Add($"Score {(scoreDelta > 0 ? "increased" : "decreased")} by {Math.Abs(scoreDelta):F1} points");
}
return reasons.Count > 0 ? string.Join("; ", reasons) : "Significant score change";
}
#endregion
}
#region Request/Response DTOs
@@ -433,3 +797,73 @@ internal sealed record SeverityShifts(
int Unchanged);
#endregion
#region Policy Studio DTOs (POLICY-RISK-68-001)
internal sealed record PolicyStudioAnalysisRequest(
string ProfileId,
string? ProfileVersion,
IReadOnlyList<SimulationFinding> Findings,
RiskSimulationBreakdownOptions? BreakdownOptions = null);
internal sealed record PolicyStudioAnalysisResponse(
RiskSimulationResult Result,
RiskSimulationBreakdown Breakdown,
double TotalExecutionTimeMs);
internal sealed record PolicyStudioComparisonRequest(
string BaseProfileId,
string CompareProfileId,
IReadOnlyList<SimulationFinding> Findings,
RiskSimulationBreakdownOptions? BreakdownOptions = null);
internal sealed record PolicyStudioComparisonResponse(
RiskSimulationResult BaselineResult,
RiskSimulationResult CompareResult,
RiskSimulationBreakdown Breakdown,
double ExecutionTimeMs);
internal sealed record ProfileChangePreviewRequest(
string CurrentProfileId,
string? CurrentProfileVersion,
string? ProposedProfileId,
string? ProposedProfileVersion,
IReadOnlyList<SimulationFinding> Findings,
IReadOnlyDictionary<string, double>? ProposedWeightChanges = null,
IReadOnlyList<ProposedOverrideChange>? ProposedOverrideChanges = null);
internal sealed record ProposedOverrideChange(
string OverrideType,
Dictionary<string, object> When,
object Value,
string? Reason = null);
internal sealed record ProfileChangePreviewResponse(
ProfileSimulationSummary CurrentResult,
ProfileSimulationSummary ProposedResult,
ProfileChangeImpact Impact,
IReadOnlyList<HighImpactFindingPreview> HighImpactFindings);
internal sealed record ProfileChangeImpact(
int FindingsImproved,
int FindingsWorsened,
int FindingsUnchanged,
int SeverityEscalations,
int SeverityDeescalations,
int ActionChanges,
double MeanScoreDelta,
int CriticalCountDelta,
int HighCountDelta);
internal sealed record HighImpactFindingPreview(
string FindingId,
double CurrentScore,
double ProposedScore,
double ScoreDelta,
string CurrentSeverity,
string ProposedSeverity,
string CurrentAction,
string ProposedAction,
string ImpactReason);
#endregion

View File

@@ -0,0 +1,159 @@
using Microsoft.AspNetCore.Mvc;
using StellaOps.Policy.Engine.AirGap;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Endpoints for sealed-mode operations per CONTRACT-SEALED-MODE-004.
/// </summary>
public static class SealedModeEndpoints
{
public static IEndpointRouteBuilder MapSealedMode(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/system/airgap");
group.MapPost("/seal", SealAsync)
.WithName("AirGap.Seal")
.WithDescription("Seal the environment")
.RequireAuthorization(policy => policy.RequireClaim("scope", "airgap:seal"))
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status500InternalServerError);
group.MapPost("/unseal", UnsealAsync)
.WithName("AirGap.Unseal")
.WithDescription("Unseal the environment")
.RequireAuthorization(policy => policy.RequireClaim("scope", "airgap:seal"))
.ProducesProblem(StatusCodes.Status500InternalServerError);
group.MapGet("/status", GetStatusAsync)
.WithName("AirGap.GetStatus")
.WithDescription("Get sealed-mode status")
.RequireAuthorization(policy => policy.RequireClaim("scope", "airgap:status:read"));
group.MapPost("/verify", VerifyBundleAsync)
.WithName("AirGap.VerifyBundle")
.WithDescription("Verify a bundle against trust roots")
.RequireAuthorization(policy => policy.RequireClaim("scope", "airgap:verify"))
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status422UnprocessableEntity);
return routes;
}
private static async Task<IResult> SealAsync(
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
[FromBody] SealRequest request,
ISealedModeService service,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(tenantId))
{
tenantId = "default";
}
try
{
var response = await service.SealAsync(tenantId, request, cancellationToken).ConfigureAwait(false);
return Results.Ok(response);
}
catch (SealedModeException ex)
{
return SealedModeResultHelper.ToProblem(ex);
}
catch (ArgumentException ex)
{
return SealedModeResultHelper.ToProblem(
SealedModeErrorCodes.SealFailed,
ex.Message,
"Ensure all required parameters are provided");
}
catch (Exception ex)
{
return SealedModeResultHelper.ToProblem(
SealedModeErrorCodes.SealFailed,
$"Seal operation failed: {ex.Message}");
}
}
private static async Task<IResult> UnsealAsync(
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
ISealedModeService service,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(tenantId))
{
tenantId = "default";
}
try
{
var response = await service.UnsealAsync(tenantId, cancellationToken).ConfigureAwait(false);
return Results.Ok(response);
}
catch (SealedModeException ex)
{
return SealedModeResultHelper.ToProblem(ex);
}
catch (Exception ex)
{
return SealedModeResultHelper.ToProblem(
SealedModeErrorCodes.UnsealFailed,
$"Unseal operation failed: {ex.Message}");
}
}
private static async Task<IResult> GetStatusAsync(
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
ISealedModeService service,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(tenantId))
{
tenantId = "default";
}
var status = await service.GetStatusAsync(tenantId, cancellationToken).ConfigureAwait(false);
return Results.Ok(status);
}
private static async Task<IResult> VerifyBundleAsync(
[FromBody] BundleVerifyRequest request,
ISealedModeService service,
CancellationToken cancellationToken)
{
try
{
var response = await service.VerifyBundleAsync(request, cancellationToken).ConfigureAwait(false);
// Return problem details if verification failed
if (!response.Valid && response.VerificationResult.Error is not null)
{
return SealedModeResultHelper.ToProblem(
SealedModeErrorCodes.SignatureInvalid,
response.VerificationResult.Error,
"Verify bundle integrity and trust root configuration",
422);
}
return Results.Ok(response);
}
catch (SealedModeException ex)
{
return SealedModeResultHelper.ToProblem(ex);
}
catch (ArgumentException ex)
{
return SealedModeResultHelper.ToProblem(
SealedModeErrorCodes.BundleInvalid,
ex.Message,
"Ensure bundle path is valid and accessible");
}
catch (FileNotFoundException ex)
{
return SealedModeResultHelper.ToProblem(
SealedModeErrorCodes.BundleInvalid,
$"Bundle file not found: {ex.FileName ?? ex.Message}",
"Verify the bundle path is correct");
}
}
}

View File

@@ -0,0 +1,121 @@
using Microsoft.AspNetCore.Mvc;
using StellaOps.Policy.Engine.AirGap;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Endpoints for staleness signaling and fallback status per CONTRACT-SEALED-MODE-004.
/// </summary>
public static class StalenessEndpoints
{
public static IEndpointRouteBuilder MapStalenessSignaling(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/system/airgap/staleness");
group.MapGet("/status", GetStalenessStatusAsync)
.WithName("AirGap.GetStalenessStatus")
.WithDescription("Get staleness signal status for health monitoring");
group.MapGet("/fallback", GetFallbackStatusAsync)
.WithName("AirGap.GetFallbackStatus")
.WithDescription("Get fallback mode status and configuration");
group.MapPost("/evaluate", EvaluateStalenessAsync)
.WithName("AirGap.EvaluateStaleness")
.WithDescription("Trigger staleness evaluation and signaling")
.RequireAuthorization(policy => policy.RequireClaim("scope", "airgap:status:read"));
group.MapPost("/recover", SignalRecoveryAsync)
.WithName("AirGap.SignalRecovery")
.WithDescription("Signal staleness recovery after time anchor refresh")
.RequireAuthorization(policy => policy.RequireClaim("scope", "airgap:seal"));
return routes;
}
private static async Task<IResult> GetStalenessStatusAsync(
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
IStalenessSignalingService service,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(tenantId))
{
tenantId = "default";
}
var status = await service.GetSignalStatusAsync(tenantId, cancellationToken).ConfigureAwait(false);
// Return different status codes based on health
if (status.IsBreach)
{
return Results.Json(status, statusCode: StatusCodes.Status503ServiceUnavailable);
}
if (status.HasWarning)
{
// Return 200 but with warning headers
return Results.Ok(status);
}
return Results.Ok(status);
}
private static async Task<IResult> GetFallbackStatusAsync(
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
IStalenessSignalingService service,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(tenantId))
{
tenantId = "default";
}
var config = await service.GetFallbackConfigurationAsync(tenantId, cancellationToken).ConfigureAwait(false);
var isActive = await service.IsFallbackActiveAsync(tenantId, cancellationToken).ConfigureAwait(false);
return Results.Ok(new
{
fallbackActive = isActive,
configuration = config
});
}
private static async Task<IResult> EvaluateStalenessAsync(
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
IStalenessSignalingService service,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(tenantId))
{
tenantId = "default";
}
await service.EvaluateAndSignalAsync(tenantId, cancellationToken).ConfigureAwait(false);
var status = await service.GetSignalStatusAsync(tenantId, cancellationToken).ConfigureAwait(false);
return Results.Ok(new
{
evaluated = true,
status
});
}
private static async Task<IResult> SignalRecoveryAsync(
[FromHeader(Name = "X-Tenant-Id")] string? tenantId,
IStalenessSignalingService service,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(tenantId))
{
tenantId = "default";
}
await service.SignalRecoveryAsync(tenantId, cancellationToken).ConfigureAwait(false);
return Results.Ok(new
{
recovered = true,
tenantId
});
}
}

View File

@@ -0,0 +1,414 @@
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using StellaOps.Auth.Abstractions;
using StellaOps.Policy.Engine.Attestation;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Editor endpoints for verification policy management per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
public static class VerificationPolicyEditorEndpoints
{
public static IEndpointRouteBuilder MapVerificationPolicyEditor(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/api/v1/attestor/policies/editor")
.WithTags("Verification Policy Editor");
group.MapGet("/metadata", GetEditorMetadata)
.WithName("Attestor.GetEditorMetadata")
.WithSummary("Get editor metadata for verification policy forms")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<VerificationPolicyEditorMetadata>(StatusCodes.Status200OK);
group.MapPost("/validate", ValidatePolicyAsync)
.WithName("Attestor.ValidatePolicy")
.WithSummary("Validate a verification policy without persisting")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<ValidatePolicyResponse>(StatusCodes.Status200OK);
group.MapGet("/{policyId}", GetPolicyEditorViewAsync)
.WithName("Attestor.GetPolicyEditorView")
.WithSummary("Get a verification policy with editor metadata")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<VerificationPolicyEditorView>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
group.MapPost("/clone", ClonePolicyAsync)
.WithName("Attestor.ClonePolicy")
.WithSummary("Clone a verification policy")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyWrite))
.Produces<VerificationPolicy>(StatusCodes.Status201Created)
.Produces<ProblemHttpResult>(StatusCodes.Status400BadRequest)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound)
.Produces<ProblemHttpResult>(StatusCodes.Status409Conflict);
group.MapPost("/compare", ComparePoliciesAsync)
.WithName("Attestor.ComparePolicies")
.WithSummary("Compare two verification policies")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<ComparePoliciesResponse>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
return routes;
}
private static IResult GetEditorMetadata()
{
var metadata = VerificationPolicyEditorMetadataProvider.GetMetadata();
return Results.Ok(metadata);
}
private static IResult ValidatePolicyAsync(
[FromBody] ValidatePolicyRequest request,
VerificationPolicyValidator validator)
{
if (request == null)
{
return Results.Ok(new ValidatePolicyResponse(
Valid: false,
Errors: [new VerificationPolicyValidationError("ERR_VP_000", "request", "Request body is required.")],
Warnings: [],
Suggestions: []));
}
// Convert to CreateVerificationPolicyRequest for validation
var createRequest = new CreateVerificationPolicyRequest(
PolicyId: request.PolicyId ?? string.Empty,
Version: request.Version ?? "1.0.0",
Description: request.Description,
TenantScope: request.TenantScope,
PredicateTypes: request.PredicateTypes ?? [],
SignerRequirements: request.SignerRequirements,
ValidityWindow: request.ValidityWindow,
Metadata: request.Metadata);
var validation = validator.ValidateCreate(createRequest);
var errors = validation.Errors
.Where(e => e.Severity == ValidationSeverity.Error)
.ToList();
var warnings = validation.Errors
.Where(e => e.Severity == ValidationSeverity.Warning)
.ToList();
var suggestions = VerificationPolicyEditorMetadataProvider.GenerateSuggestions(createRequest, validation);
return Results.Ok(new ValidatePolicyResponse(
Valid: errors.Count == 0,
Errors: errors,
Warnings: warnings,
Suggestions: suggestions));
}
private static async Task<IResult> GetPolicyEditorViewAsync(
[FromRoute] string policyId,
IVerificationPolicyStore store,
VerificationPolicyValidator validator,
CancellationToken cancellationToken)
{
var policy = await store.GetAsync(policyId, cancellationToken).ConfigureAwait(false);
if (policy == null)
{
return Results.NotFound(CreateProblem(
"Policy not found",
$"Policy '{policyId}' was not found.",
"ERR_ATTEST_005"));
}
// Re-validate current policy state
var updateRequest = new UpdateVerificationPolicyRequest(
Version: policy.Version,
Description: policy.Description,
PredicateTypes: policy.PredicateTypes,
SignerRequirements: policy.SignerRequirements,
ValidityWindow: policy.ValidityWindow,
Metadata: policy.Metadata);
var validation = validator.ValidateUpdate(updateRequest);
// Generate suggestions
var createRequest = new CreateVerificationPolicyRequest(
PolicyId: policy.PolicyId,
Version: policy.Version,
Description: policy.Description,
TenantScope: policy.TenantScope,
PredicateTypes: policy.PredicateTypes,
SignerRequirements: policy.SignerRequirements,
ValidityWindow: policy.ValidityWindow,
Metadata: policy.Metadata);
var suggestions = VerificationPolicyEditorMetadataProvider.GenerateSuggestions(createRequest, validation);
// TODO: Check if policy is referenced by attestations
var isReferenced = false;
var view = new VerificationPolicyEditorView(
Policy: policy,
Validation: validation,
Suggestions: suggestions,
CanDelete: !isReferenced,
IsReferenced: isReferenced);
return Results.Ok(view);
}
private static async Task<IResult> ClonePolicyAsync(
[FromBody] ClonePolicyRequest request,
IVerificationPolicyStore store,
VerificationPolicyValidator validator,
TimeProvider timeProvider,
CancellationToken cancellationToken)
{
if (request == null)
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Request body is required.",
"ERR_ATTEST_001"));
}
if (string.IsNullOrWhiteSpace(request.SourcePolicyId))
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Source policy ID is required.",
"ERR_ATTEST_006"));
}
if (string.IsNullOrWhiteSpace(request.NewPolicyId))
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"New policy ID is required.",
"ERR_ATTEST_007"));
}
var sourcePolicy = await store.GetAsync(request.SourcePolicyId, cancellationToken).ConfigureAwait(false);
if (sourcePolicy == null)
{
return Results.NotFound(CreateProblem(
"Source policy not found",
$"Policy '{request.SourcePolicyId}' was not found.",
"ERR_ATTEST_005"));
}
if (await store.ExistsAsync(request.NewPolicyId, cancellationToken).ConfigureAwait(false))
{
return Results.Conflict(CreateProblem(
"Policy exists",
$"Policy '{request.NewPolicyId}' already exists.",
"ERR_ATTEST_004"));
}
var now = timeProvider.GetUtcNow();
var clonedPolicy = new VerificationPolicy(
PolicyId: request.NewPolicyId,
Version: request.NewVersion ?? sourcePolicy.Version,
Description: sourcePolicy.Description != null
? $"Cloned from {request.SourcePolicyId}: {sourcePolicy.Description}"
: $"Cloned from {request.SourcePolicyId}",
TenantScope: sourcePolicy.TenantScope,
PredicateTypes: sourcePolicy.PredicateTypes,
SignerRequirements: sourcePolicy.SignerRequirements,
ValidityWindow: sourcePolicy.ValidityWindow,
Metadata: sourcePolicy.Metadata,
CreatedAt: now,
UpdatedAt: now);
await store.CreateAsync(clonedPolicy, cancellationToken).ConfigureAwait(false);
return Results.Created(
$"/api/v1/attestor/policies/{clonedPolicy.PolicyId}",
clonedPolicy);
}
private static async Task<IResult> ComparePoliciesAsync(
[FromBody] ComparePoliciesRequest request,
IVerificationPolicyStore store,
CancellationToken cancellationToken)
{
if (request == null)
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Request body is required.",
"ERR_ATTEST_001"));
}
if (string.IsNullOrWhiteSpace(request.PolicyIdA))
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Policy ID A is required.",
"ERR_ATTEST_008"));
}
if (string.IsNullOrWhiteSpace(request.PolicyIdB))
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Policy ID B is required.",
"ERR_ATTEST_009"));
}
var policyA = await store.GetAsync(request.PolicyIdA, cancellationToken).ConfigureAwait(false);
var policyB = await store.GetAsync(request.PolicyIdB, cancellationToken).ConfigureAwait(false);
if (policyA == null)
{
return Results.NotFound(CreateProblem(
"Policy not found",
$"Policy '{request.PolicyIdA}' was not found.",
"ERR_ATTEST_005"));
}
if (policyB == null)
{
return Results.NotFound(CreateProblem(
"Policy not found",
$"Policy '{request.PolicyIdB}' was not found.",
"ERR_ATTEST_005"));
}
var differences = ComputeDifferences(policyA, policyB);
return Results.Ok(new ComparePoliciesResponse(
PolicyA: policyA,
PolicyB: policyB,
Differences: differences));
}
private static IReadOnlyList<PolicyDifference> ComputeDifferences(VerificationPolicy a, VerificationPolicy b)
{
var differences = new List<PolicyDifference>();
if (a.Version != b.Version)
{
differences.Add(new PolicyDifference("version", a.Version, b.Version, DifferenceType.Modified));
}
if (a.Description != b.Description)
{
differences.Add(new PolicyDifference("description", a.Description, b.Description, DifferenceType.Modified));
}
if (a.TenantScope != b.TenantScope)
{
differences.Add(new PolicyDifference("tenant_scope", a.TenantScope, b.TenantScope, DifferenceType.Modified));
}
// Compare predicate types
var predicateTypesA = a.PredicateTypes.ToHashSet();
var predicateTypesB = b.PredicateTypes.ToHashSet();
foreach (var added in predicateTypesB.Except(predicateTypesA))
{
differences.Add(new PolicyDifference("predicate_types", null, added, DifferenceType.Added));
}
foreach (var removed in predicateTypesA.Except(predicateTypesB))
{
differences.Add(new PolicyDifference("predicate_types", removed, null, DifferenceType.Removed));
}
// Compare signer requirements
if (a.SignerRequirements.MinimumSignatures != b.SignerRequirements.MinimumSignatures)
{
differences.Add(new PolicyDifference(
"signer_requirements.minimum_signatures",
a.SignerRequirements.MinimumSignatures,
b.SignerRequirements.MinimumSignatures,
DifferenceType.Modified));
}
if (a.SignerRequirements.RequireRekor != b.SignerRequirements.RequireRekor)
{
differences.Add(new PolicyDifference(
"signer_requirements.require_rekor",
a.SignerRequirements.RequireRekor,
b.SignerRequirements.RequireRekor,
DifferenceType.Modified));
}
// Compare fingerprints
var fingerprintsA = a.SignerRequirements.TrustedKeyFingerprints.ToHashSet(StringComparer.OrdinalIgnoreCase);
var fingerprintsB = b.SignerRequirements.TrustedKeyFingerprints.ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var added in fingerprintsB.Except(fingerprintsA))
{
differences.Add(new PolicyDifference("signer_requirements.trusted_key_fingerprints", null, added, DifferenceType.Added));
}
foreach (var removed in fingerprintsA.Except(fingerprintsB))
{
differences.Add(new PolicyDifference("signer_requirements.trusted_key_fingerprints", removed, null, DifferenceType.Removed));
}
// Compare algorithms
var algorithmsA = (a.SignerRequirements.Algorithms ?? []).ToHashSet(StringComparer.OrdinalIgnoreCase);
var algorithmsB = (b.SignerRequirements.Algorithms ?? []).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var added in algorithmsB.Except(algorithmsA))
{
differences.Add(new PolicyDifference("signer_requirements.algorithms", null, added, DifferenceType.Added));
}
foreach (var removed in algorithmsA.Except(algorithmsB))
{
differences.Add(new PolicyDifference("signer_requirements.algorithms", removed, null, DifferenceType.Removed));
}
// Compare validity window
var validityA = a.ValidityWindow;
var validityB = b.ValidityWindow;
if (validityA == null && validityB != null)
{
differences.Add(new PolicyDifference("validity_window", null, validityB, DifferenceType.Added));
}
else if (validityA != null && validityB == null)
{
differences.Add(new PolicyDifference("validity_window", validityA, null, DifferenceType.Removed));
}
else if (validityA != null && validityB != null)
{
if (validityA.NotBefore != validityB.NotBefore)
{
differences.Add(new PolicyDifference("validity_window.not_before", validityA.NotBefore, validityB.NotBefore, DifferenceType.Modified));
}
if (validityA.NotAfter != validityB.NotAfter)
{
differences.Add(new PolicyDifference("validity_window.not_after", validityA.NotAfter, validityB.NotAfter, DifferenceType.Modified));
}
if (validityA.MaxAttestationAge != validityB.MaxAttestationAge)
{
differences.Add(new PolicyDifference("validity_window.max_attestation_age", validityA.MaxAttestationAge, validityB.MaxAttestationAge, DifferenceType.Modified));
}
}
return differences;
}
private static ProblemDetails CreateProblem(string title, string detail, string? errorCode = null)
{
var problem = new ProblemDetails
{
Title = title,
Detail = detail,
Status = StatusCodes.Status400BadRequest
};
if (!string.IsNullOrWhiteSpace(errorCode))
{
problem.Extensions["error_code"] = errorCode;
}
return problem;
}
}

View File

@@ -0,0 +1,227 @@
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using StellaOps.Auth.Abstractions;
using StellaOps.Policy.Engine.Attestation;
namespace StellaOps.Policy.Engine.Endpoints;
/// <summary>
/// Endpoints for verification policy management per CONTRACT-VERIFICATION-POLICY-006.
/// </summary>
public static class VerificationPolicyEndpoints
{
public static IEndpointRouteBuilder MapVerificationPolicies(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/api/v1/attestor/policies")
.WithTags("Verification Policies");
group.MapPost("/", CreatePolicyAsync)
.WithName("Attestor.CreatePolicy")
.WithSummary("Create a new verification policy")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyWrite))
.Produces<VerificationPolicy>(StatusCodes.Status201Created)
.Produces<ProblemHttpResult>(StatusCodes.Status400BadRequest)
.Produces<ProblemHttpResult>(StatusCodes.Status409Conflict);
group.MapGet("/{policyId}", GetPolicyAsync)
.WithName("Attestor.GetPolicy")
.WithSummary("Get a verification policy by ID")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<VerificationPolicy>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
group.MapGet("/", ListPoliciesAsync)
.WithName("Attestor.ListPolicies")
.WithSummary("List verification policies")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyRead))
.Produces<VerificationPolicyListResponse>(StatusCodes.Status200OK);
group.MapPut("/{policyId}", UpdatePolicyAsync)
.WithName("Attestor.UpdatePolicy")
.WithSummary("Update a verification policy")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyWrite))
.Produces<VerificationPolicy>(StatusCodes.Status200OK)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
group.MapDelete("/{policyId}", DeletePolicyAsync)
.WithName("Attestor.DeletePolicy")
.WithSummary("Delete a verification policy")
.RequireAuthorization(policy => policy.RequireClaim("scope", StellaOpsScopes.PolicyWrite))
.Produces(StatusCodes.Status204NoContent)
.Produces<ProblemHttpResult>(StatusCodes.Status404NotFound);
return routes;
}
private static async Task<IResult> CreatePolicyAsync(
[FromBody] CreateVerificationPolicyRequest request,
IVerificationPolicyStore store,
TimeProvider timeProvider,
CancellationToken cancellationToken)
{
if (request == null)
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Request body is required.",
"ERR_ATTEST_001"));
}
if (string.IsNullOrWhiteSpace(request.PolicyId))
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Policy ID is required.",
"ERR_ATTEST_002"));
}
if (request.PredicateTypes == null || request.PredicateTypes.Count == 0)
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"At least one predicate type is required.",
"ERR_ATTEST_003"));
}
if (await store.ExistsAsync(request.PolicyId, cancellationToken).ConfigureAwait(false))
{
return Results.Conflict(CreateProblem(
"Policy exists",
$"Policy '{request.PolicyId}' already exists.",
"ERR_ATTEST_004"));
}
var now = timeProvider.GetUtcNow();
var policy = new VerificationPolicy(
PolicyId: request.PolicyId,
Version: request.Version ?? "1.0.0",
Description: request.Description,
TenantScope: request.TenantScope ?? "*",
PredicateTypes: request.PredicateTypes,
SignerRequirements: request.SignerRequirements ?? SignerRequirements.Default,
ValidityWindow: request.ValidityWindow,
Metadata: request.Metadata,
CreatedAt: now,
UpdatedAt: now);
await store.CreateAsync(policy, cancellationToken).ConfigureAwait(false);
return Results.Created(
$"/api/v1/attestor/policies/{policy.PolicyId}",
policy);
}
private static async Task<IResult> GetPolicyAsync(
[FromRoute] string policyId,
IVerificationPolicyStore store,
CancellationToken cancellationToken)
{
var policy = await store.GetAsync(policyId, cancellationToken).ConfigureAwait(false);
if (policy == null)
{
return Results.NotFound(CreateProblem(
"Policy not found",
$"Policy '{policyId}' was not found.",
"ERR_ATTEST_005"));
}
return Results.Ok(policy);
}
private static async Task<IResult> ListPoliciesAsync(
[FromQuery] string? tenantScope,
IVerificationPolicyStore store,
CancellationToken cancellationToken)
{
var policies = await store.ListAsync(tenantScope, cancellationToken).ConfigureAwait(false);
return Results.Ok(new VerificationPolicyListResponse(
Policies: policies,
Total: policies.Count));
}
private static async Task<IResult> UpdatePolicyAsync(
[FromRoute] string policyId,
[FromBody] UpdateVerificationPolicyRequest request,
IVerificationPolicyStore store,
TimeProvider timeProvider,
CancellationToken cancellationToken)
{
if (request == null)
{
return Results.BadRequest(CreateProblem(
"Invalid request",
"Request body is required.",
"ERR_ATTEST_001"));
}
var now = timeProvider.GetUtcNow();
var updated = await store.UpdateAsync(
policyId,
existing => existing with
{
Version = request.Version ?? existing.Version,
Description = request.Description ?? existing.Description,
PredicateTypes = request.PredicateTypes ?? existing.PredicateTypes,
SignerRequirements = request.SignerRequirements ?? existing.SignerRequirements,
ValidityWindow = request.ValidityWindow ?? existing.ValidityWindow,
Metadata = request.Metadata ?? existing.Metadata,
UpdatedAt = now
},
cancellationToken).ConfigureAwait(false);
if (updated == null)
{
return Results.NotFound(CreateProblem(
"Policy not found",
$"Policy '{policyId}' was not found.",
"ERR_ATTEST_005"));
}
return Results.Ok(updated);
}
private static async Task<IResult> DeletePolicyAsync(
[FromRoute] string policyId,
IVerificationPolicyStore store,
CancellationToken cancellationToken)
{
var deleted = await store.DeleteAsync(policyId, cancellationToken).ConfigureAwait(false);
if (!deleted)
{
return Results.NotFound(CreateProblem(
"Policy not found",
$"Policy '{policyId}' was not found.",
"ERR_ATTEST_005"));
}
return Results.NoContent();
}
private static ProblemDetails CreateProblem(string title, string detail, string? errorCode = null)
{
var problem = new ProblemDetails
{
Title = title,
Detail = detail,
Status = StatusCodes.Status400BadRequest
};
if (!string.IsNullOrWhiteSpace(errorCode))
{
problem.Extensions["error_code"] = errorCode;
}
return problem;
}
}
/// <summary>
/// Response for listing verification policies.
/// </summary>
public sealed record VerificationPolicyListResponse(
[property: System.Text.Json.Serialization.JsonPropertyName("policies")] IReadOnlyList<VerificationPolicy> Policies,
[property: System.Text.Json.Serialization.JsonPropertyName("total")] int Total);

View File

@@ -126,6 +126,13 @@ builder.Services.AddSingleton<IncidentModeService>();
builder.Services.AddSingleton<RiskProfileConfigurationService>();
builder.Services.AddSingleton<StellaOps.Policy.RiskProfile.Lifecycle.RiskProfileLifecycleService>();
builder.Services.AddSingleton<StellaOps.Policy.RiskProfile.Scope.ScopeAttachmentService>();
builder.Services.AddSingleton<StellaOps.Policy.RiskProfile.Scope.EffectivePolicyService>();
builder.Services.AddSingleton<IEffectivePolicyAuditor, EffectivePolicyAuditor>(); // CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008
builder.Services.AddSingleton<StellaOps.Policy.Engine.Attestation.IVerificationPolicyStore, StellaOps.Policy.Engine.Attestation.InMemoryVerificationPolicyStore>(); // CONTRACT-VERIFICATION-POLICY-006
builder.Services.AddSingleton<StellaOps.Policy.Engine.Attestation.VerificationPolicyValidator>(); // CONTRACT-VERIFICATION-POLICY-006 validation
builder.Services.AddSingleton<StellaOps.Policy.Engine.Attestation.IAttestationReportStore, StellaOps.Policy.Engine.Attestation.InMemoryAttestationReportStore>(); // CONTRACT-VERIFICATION-POLICY-006 reports
builder.Services.AddSingleton<StellaOps.Policy.Engine.Attestation.IAttestationReportService, StellaOps.Policy.Engine.Attestation.AttestationReportService>(); // CONTRACT-VERIFICATION-POLICY-006 reports
builder.Services.AddSingleton<StellaOps.Policy.Engine.ConsoleSurface.ConsoleAttestationReportService>(); // CONTRACT-VERIFICATION-POLICY-006 Console integration
builder.Services.AddSingleton<StellaOps.Policy.RiskProfile.Overrides.OverrideService>();
builder.Services.AddSingleton<StellaOps.Policy.Engine.Scoring.IRiskScoringJobStore, StellaOps.Policy.Engine.Scoring.InMemoryRiskScoringJobStore>();
builder.Services.AddSingleton<StellaOps.Policy.Engine.Scoring.RiskScoringTriggerService>();
@@ -177,6 +184,24 @@ builder.Services.AddSingleton<StellaOps.Policy.Engine.ConsoleExport.ConsoleExpor
builder.Services.AddSingleton<StellaOps.Policy.Engine.AirGap.IPolicyPackBundleStore, StellaOps.Policy.Engine.AirGap.InMemoryPolicyPackBundleStore>();
builder.Services.AddSingleton<StellaOps.Policy.Engine.AirGap.PolicyPackBundleImportService>();
// Sealed-mode services per CONTRACT-SEALED-MODE-004
builder.Services.AddSingleton<StellaOps.Policy.Engine.AirGap.ISealedModeStateStore, StellaOps.Policy.Engine.AirGap.InMemorySealedModeStateStore>();
builder.Services.AddSingleton<StellaOps.Policy.Engine.AirGap.ISealedModeService, StellaOps.Policy.Engine.AirGap.SealedModeService>();
// Staleness signaling services per CONTRACT-SEALED-MODE-004
builder.Services.AddSingleton<StellaOps.Policy.Engine.AirGap.IStalenessEventSink, StellaOps.Policy.Engine.AirGap.LoggingStalenessEventSink>();
builder.Services.AddSingleton<StellaOps.Policy.Engine.AirGap.IStalenessSignalingService, StellaOps.Policy.Engine.AirGap.StalenessSignalingService>();
// Air-gap notification services
builder.Services.AddSingleton<StellaOps.Policy.Engine.AirGap.IAirGapNotificationChannel, StellaOps.Policy.Engine.AirGap.LoggingNotificationChannel>();
builder.Services.AddSingleton<StellaOps.Policy.Engine.AirGap.IAirGapNotificationService, StellaOps.Policy.Engine.AirGap.AirGapNotificationService>();
// Air-gap risk profile export/import per CONTRACT-MIRROR-BUNDLE-003
builder.Services.AddSingleton<StellaOps.Policy.Engine.AirGap.RiskProfileAirGapExportService>();
// Also register as IStalenessEventSink to auto-notify on staleness events
builder.Services.AddSingleton<StellaOps.Policy.Engine.AirGap.IStalenessEventSink>(sp =>
(StellaOps.Policy.Engine.AirGap.AirGapNotificationService)sp.GetRequiredService<StellaOps.Policy.Engine.AirGap.IAirGapNotificationService>());
builder.Services.AddSingleton<StellaOps.Policy.Engine.Snapshots.ISnapshotStore, StellaOps.Policy.Engine.Snapshots.InMemorySnapshotStore>();
builder.Services.AddSingleton<StellaOps.Policy.Engine.Snapshots.SnapshotService>();
builder.Services.AddSingleton<StellaOps.Policy.Engine.Violations.IViolationEventStore, StellaOps.Policy.Engine.Violations.InMemoryViolationEventStore>();
@@ -290,17 +315,27 @@ app.MapBatchContext();
app.MapOrchestratorJobs();
app.MapPolicyWorker();
app.MapLedgerExport();
app.MapConsoleExportJobs(); // CONTRACT-EXPORT-BUNDLE-009
app.MapPolicyPackBundles(); // CONTRACT-MIRROR-BUNDLE-003
app.MapConsoleExportJobs(); // CONTRACT-EXPORT-BUNDLE-009
app.MapPolicyPackBundles(); // CONTRACT-MIRROR-BUNDLE-003
app.MapSealedMode(); // CONTRACT-SEALED-MODE-004
app.MapStalenessSignaling(); // CONTRACT-SEALED-MODE-004 staleness
app.MapAirGapNotifications(); // Air-gap notifications
app.MapPolicyLint(); // POLICY-AOC-19-001 determinism linting
app.MapVerificationPolicies(); // CONTRACT-VERIFICATION-POLICY-006 attestation policies
app.MapVerificationPolicyEditor(); // CONTRACT-VERIFICATION-POLICY-006 editor DTOs/validation
app.MapAttestationReports(); // CONTRACT-VERIFICATION-POLICY-006 attestation reports
app.MapConsoleAttestationReports(); // CONTRACT-VERIFICATION-POLICY-006 Console integration
app.MapSnapshots();
app.MapViolations();
app.MapPolicyDecisions();
app.MapRiskProfiles();
app.MapRiskProfileSchema();
app.MapScopeAttachments();
app.MapEffectivePolicies(); // CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008
app.MapRiskSimulation();
app.MapOverrides();
app.MapProfileExport();
app.MapRiskProfileAirGap(); // CONTRACT-MIRROR-BUNDLE-003 risk profile air-gap
app.MapProfileEvents();
// Phase 5: Multi-tenant PostgreSQL-backed API endpoints

View File

@@ -117,6 +117,20 @@ public enum RiskScoringJobStatus
/// <summary>
/// Result of scoring a single finding.
/// </summary>
/// <param name="FindingId">Unique identifier for the finding.</param>
/// <param name="ProfileId">Risk profile used for scoring.</param>
/// <param name="ProfileVersion">Version of the risk profile.</param>
/// <param name="RawScore">Raw computed score before normalization.</param>
/// <param name="NormalizedScore">
/// DEPRECATED: Legacy normalized score (0-1 range). Use <see cref="Severity"/> instead.
/// Scheduled for removal in v2.0. See DESIGN-POLICY-NORMALIZED-FIELD-REMOVAL-001.
/// </param>
/// <param name="Severity">Canonical severity (critical/high/medium/low/info).</param>
/// <param name="SignalValues">Input signal values used in scoring.</param>
/// <param name="SignalContributions">Contribution of each signal to final score.</param>
/// <param name="OverrideApplied">Override rule that was applied, if any.</param>
/// <param name="OverrideReason">Reason for the override, if any.</param>
/// <param name="ScoredAt">Timestamp when scoring was performed.</param>
public sealed record RiskScoringResult(
[property: JsonPropertyName("finding_id")] string FindingId,
[property: JsonPropertyName("profile_id")] string ProfileId,

View File

@@ -0,0 +1,168 @@
using Microsoft.Extensions.Logging;
using StellaOps.Policy.RiskProfile.Scope;
namespace StellaOps.Policy.Engine.Services;
/// <summary>
/// Audit log interface for effective:write operations per CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008.
/// </summary>
internal interface IEffectivePolicyAuditor
{
/// <summary>
/// Records an effective policy creation event.
/// </summary>
void RecordCreated(EffectivePolicy policy, string? actorId);
/// <summary>
/// Records an effective policy update event.
/// </summary>
void RecordUpdated(EffectivePolicy policy, string? actorId, object? changes);
/// <summary>
/// Records an effective policy deletion event.
/// </summary>
void RecordDeleted(string effectivePolicyId, string? actorId);
/// <summary>
/// Records a scope attachment event.
/// </summary>
void RecordScopeAttached(AuthorityScopeAttachment attachment, string? actorId);
/// <summary>
/// Records a scope detachment event.
/// </summary>
void RecordScopeDetached(string attachmentId, string? actorId);
}
/// <summary>
/// Default implementation of effective policy auditor.
/// Emits structured logs for all effective:write operations per CONTRACT-AUTHORITY-EFFECTIVE-WRITE-008.
/// </summary>
internal sealed class EffectivePolicyAuditor : IEffectivePolicyAuditor
{
private readonly ILogger<EffectivePolicyAuditor> _logger;
private readonly TimeProvider _timeProvider;
public EffectivePolicyAuditor(
ILogger<EffectivePolicyAuditor> logger,
TimeProvider timeProvider)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
}
public void RecordCreated(EffectivePolicy policy, string? actorId)
{
ArgumentNullException.ThrowIfNull(policy);
var scope = CreateBaseScope("effective_policy.created", actorId);
scope["effective_policy_id"] = policy.EffectivePolicyId;
scope["tenant_id"] = policy.TenantId;
scope["policy_id"] = policy.PolicyId;
scope["subject_pattern"] = policy.SubjectPattern;
scope["priority"] = policy.Priority;
if (policy.Scopes is { Count: > 0 })
{
scope["scopes"] = policy.Scopes;
}
using (_logger.BeginScope(scope))
{
_logger.LogInformation(
"Effective policy created: {EffectivePolicyId} for pattern {SubjectPattern}",
policy.EffectivePolicyId,
policy.SubjectPattern);
}
}
public void RecordUpdated(EffectivePolicy policy, string? actorId, object? changes)
{
ArgumentNullException.ThrowIfNull(policy);
var scope = CreateBaseScope("effective_policy.updated", actorId);
scope["effective_policy_id"] = policy.EffectivePolicyId;
scope["tenant_id"] = policy.TenantId;
if (changes is not null)
{
scope["changes"] = changes;
}
using (_logger.BeginScope(scope))
{
_logger.LogInformation(
"Effective policy updated: {EffectivePolicyId}",
policy.EffectivePolicyId);
}
}
public void RecordDeleted(string effectivePolicyId, string? actorId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(effectivePolicyId);
var scope = CreateBaseScope("effective_policy.deleted", actorId);
scope["effective_policy_id"] = effectivePolicyId;
using (_logger.BeginScope(scope))
{
_logger.LogInformation(
"Effective policy deleted: {EffectivePolicyId}",
effectivePolicyId);
}
}
public void RecordScopeAttached(AuthorityScopeAttachment attachment, string? actorId)
{
ArgumentNullException.ThrowIfNull(attachment);
var scope = CreateBaseScope("scope_attachment.created", actorId);
scope["attachment_id"] = attachment.AttachmentId;
scope["effective_policy_id"] = attachment.EffectivePolicyId;
scope["scope"] = attachment.Scope;
if (attachment.Conditions is { Count: > 0 })
{
scope["conditions"] = attachment.Conditions;
}
using (_logger.BeginScope(scope))
{
_logger.LogInformation(
"Scope attached: {Scope} to policy {EffectivePolicyId}",
attachment.Scope,
attachment.EffectivePolicyId);
}
}
public void RecordScopeDetached(string attachmentId, string? actorId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(attachmentId);
var scope = CreateBaseScope("scope_attachment.deleted", actorId);
scope["attachment_id"] = attachmentId;
using (_logger.BeginScope(scope))
{
_logger.LogInformation(
"Scope detached: {AttachmentId}",
attachmentId);
}
}
private Dictionary<string, object?> CreateBaseScope(string eventType, string? actorId)
{
var scope = new Dictionary<string, object?>
{
["event"] = eventType,
["timestamp"] = _timeProvider.GetUtcNow().ToString("O")
};
if (!string.IsNullOrWhiteSpace(actorId))
{
scope["actor"] = actorId;
}
return scope;
}
}

View File

@@ -0,0 +1,295 @@
using System.Collections.Immutable;
using System.Text.Json.Serialization;
using StellaOps.Policy.RiskProfile.Models;
namespace StellaOps.Policy.Engine.Simulation;
/// <summary>
/// Detailed breakdown of a risk simulation result.
/// Per POLICY-RISK-67-003.
/// </summary>
public sealed record RiskSimulationBreakdown(
[property: JsonPropertyName("simulation_id")] string SimulationId,
[property: JsonPropertyName("profile_ref")] ProfileReference ProfileRef,
[property: JsonPropertyName("signal_analysis")] SignalAnalysis SignalAnalysis,
[property: JsonPropertyName("override_analysis")] OverrideAnalysis OverrideAnalysis,
[property: JsonPropertyName("score_distribution")] ScoreDistributionAnalysis ScoreDistribution,
[property: JsonPropertyName("severity_breakdown")] SeverityBreakdownAnalysis SeverityBreakdown,
[property: JsonPropertyName("action_breakdown")] ActionBreakdownAnalysis ActionBreakdown,
[property: JsonPropertyName("component_breakdown")] ComponentBreakdownAnalysis? ComponentBreakdown,
[property: JsonPropertyName("risk_trends")] RiskTrendAnalysis? RiskTrends,
[property: JsonPropertyName("determinism_hash")] string DeterminismHash);
/// <summary>
/// Reference to the risk profile used in simulation.
/// </summary>
public sealed record ProfileReference(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("version")] string Version,
[property: JsonPropertyName("hash")] string Hash,
[property: JsonPropertyName("description")] string? Description,
[property: JsonPropertyName("extends")] string? Extends);
/// <summary>
/// Analysis of signal contributions to risk scores.
/// </summary>
public sealed record SignalAnalysis(
[property: JsonPropertyName("total_signals")] int TotalSignals,
[property: JsonPropertyName("signals_used")] int SignalsUsed,
[property: JsonPropertyName("signals_missing")] int SignalsMissing,
[property: JsonPropertyName("signal_coverage")] double SignalCoverage,
[property: JsonPropertyName("signal_stats")] ImmutableArray<SignalStatistics> SignalStats,
[property: JsonPropertyName("top_contributors")] ImmutableArray<SignalContributor> TopContributors,
[property: JsonPropertyName("missing_signal_impact")] MissingSignalImpact MissingSignalImpact);
/// <summary>
/// Statistics for a single signal across all findings.
/// </summary>
public sealed record SignalStatistics(
[property: JsonPropertyName("signal_name")] string SignalName,
[property: JsonPropertyName("signal_type")] string SignalType,
[property: JsonPropertyName("weight")] double Weight,
[property: JsonPropertyName("findings_with_signal")] int FindingsWithSignal,
[property: JsonPropertyName("findings_missing_signal")] int FindingsMissingSignal,
[property: JsonPropertyName("coverage_percentage")] double CoveragePercentage,
[property: JsonPropertyName("value_distribution")] ValueDistribution? ValueDistribution,
[property: JsonPropertyName("total_contribution")] double TotalContribution,
[property: JsonPropertyName("avg_contribution")] double AvgContribution);
/// <summary>
/// Distribution of values for a signal.
/// </summary>
public sealed record ValueDistribution(
[property: JsonPropertyName("min")] double? Min,
[property: JsonPropertyName("max")] double? Max,
[property: JsonPropertyName("mean")] double? Mean,
[property: JsonPropertyName("median")] double? Median,
[property: JsonPropertyName("std_dev")] double? StdDev,
[property: JsonPropertyName("histogram")] ImmutableArray<HistogramBucket>? Histogram);
/// <summary>
/// Histogram bucket for value distribution.
/// </summary>
public sealed record HistogramBucket(
[property: JsonPropertyName("range_min")] double RangeMin,
[property: JsonPropertyName("range_max")] double RangeMax,
[property: JsonPropertyName("count")] int Count,
[property: JsonPropertyName("percentage")] double Percentage);
/// <summary>
/// A signal that significantly contributed to risk scores.
/// </summary>
public sealed record SignalContributor(
[property: JsonPropertyName("signal_name")] string SignalName,
[property: JsonPropertyName("total_contribution")] double TotalContribution,
[property: JsonPropertyName("contribution_percentage")] double ContributionPercentage,
[property: JsonPropertyName("avg_value")] double AvgValue,
[property: JsonPropertyName("weight")] double Weight,
[property: JsonPropertyName("impact_direction")] string ImpactDirection);
/// <summary>
/// Impact of missing signals on scoring.
/// </summary>
public sealed record MissingSignalImpact(
[property: JsonPropertyName("findings_with_missing_signals")] int FindingsWithMissingSignals,
[property: JsonPropertyName("avg_missing_signals_per_finding")] double AvgMissingSignalsPerFinding,
[property: JsonPropertyName("estimated_score_impact")] double EstimatedScoreImpact,
[property: JsonPropertyName("most_impactful_missing")] ImmutableArray<string> MostImpactfulMissing);
/// <summary>
/// Analysis of override applications.
/// </summary>
public sealed record OverrideAnalysis(
[property: JsonPropertyName("total_overrides_evaluated")] int TotalOverridesEvaluated,
[property: JsonPropertyName("severity_overrides_applied")] int SeverityOverridesApplied,
[property: JsonPropertyName("decision_overrides_applied")] int DecisionOverridesApplied,
[property: JsonPropertyName("override_application_rate")] double OverrideApplicationRate,
[property: JsonPropertyName("severity_override_details")] ImmutableArray<SeverityOverrideDetail> SeverityOverrideDetails,
[property: JsonPropertyName("decision_override_details")] ImmutableArray<DecisionOverrideDetail> DecisionOverrideDetails,
[property: JsonPropertyName("override_conflicts")] ImmutableArray<OverrideConflict> OverrideConflicts);
/// <summary>
/// Details of severity override applications.
/// </summary>
public sealed record SeverityOverrideDetail(
[property: JsonPropertyName("predicate_hash")] string PredicateHash,
[property: JsonPropertyName("predicate_summary")] string PredicateSummary,
[property: JsonPropertyName("target_severity")] string TargetSeverity,
[property: JsonPropertyName("applications_count")] int ApplicationsCount,
[property: JsonPropertyName("original_severities")] ImmutableDictionary<string, int> OriginalSeverities);
/// <summary>
/// Details of decision override applications.
/// </summary>
public sealed record DecisionOverrideDetail(
[property: JsonPropertyName("predicate_hash")] string PredicateHash,
[property: JsonPropertyName("predicate_summary")] string PredicateSummary,
[property: JsonPropertyName("target_action")] string TargetAction,
[property: JsonPropertyName("reason")] string? Reason,
[property: JsonPropertyName("applications_count")] int ApplicationsCount,
[property: JsonPropertyName("original_actions")] ImmutableDictionary<string, int> OriginalActions);
/// <summary>
/// Override conflict detected during evaluation.
/// </summary>
public sealed record OverrideConflict(
[property: JsonPropertyName("finding_id")] string FindingId,
[property: JsonPropertyName("conflict_type")] string ConflictType,
[property: JsonPropertyName("override_1")] string Override1,
[property: JsonPropertyName("override_2")] string Override2,
[property: JsonPropertyName("resolution")] string Resolution);
/// <summary>
/// Analysis of score distribution.
/// </summary>
public sealed record ScoreDistributionAnalysis(
[property: JsonPropertyName("raw_score_stats")] ScoreStatistics RawScoreStats,
[property: JsonPropertyName("normalized_score_stats")] ScoreStatistics NormalizedScoreStats,
[property: JsonPropertyName("score_buckets")] ImmutableArray<ScoreBucket> ScoreBuckets,
[property: JsonPropertyName("percentiles")] ImmutableDictionary<string, double> Percentiles,
[property: JsonPropertyName("outliers")] OutlierAnalysis Outliers);
/// <summary>
/// Statistical summary of scores.
/// </summary>
public sealed record ScoreStatistics(
[property: JsonPropertyName("count")] int Count,
[property: JsonPropertyName("min")] double Min,
[property: JsonPropertyName("max")] double Max,
[property: JsonPropertyName("mean")] double Mean,
[property: JsonPropertyName("median")] double Median,
[property: JsonPropertyName("std_dev")] double StdDev,
[property: JsonPropertyName("variance")] double Variance,
[property: JsonPropertyName("skewness")] double Skewness,
[property: JsonPropertyName("kurtosis")] double Kurtosis);
/// <summary>
/// Score bucket for distribution.
/// </summary>
public sealed record ScoreBucket(
[property: JsonPropertyName("range_min")] double RangeMin,
[property: JsonPropertyName("range_max")] double RangeMax,
[property: JsonPropertyName("label")] string Label,
[property: JsonPropertyName("count")] int Count,
[property: JsonPropertyName("percentage")] double Percentage);
/// <summary>
/// Outlier analysis for scores.
/// </summary>
public sealed record OutlierAnalysis(
[property: JsonPropertyName("outlier_count")] int OutlierCount,
[property: JsonPropertyName("outlier_threshold")] double OutlierThreshold,
[property: JsonPropertyName("outlier_finding_ids")] ImmutableArray<string> OutlierFindingIds);
/// <summary>
/// Breakdown by severity level.
/// </summary>
public sealed record SeverityBreakdownAnalysis(
[property: JsonPropertyName("by_severity")] ImmutableDictionary<string, SeverityBucket> BySeverity,
[property: JsonPropertyName("severity_flow")] ImmutableArray<SeverityFlow> SeverityFlow,
[property: JsonPropertyName("severity_concentration")] double SeverityConcentration);
/// <summary>
/// Details for a severity bucket.
/// </summary>
public sealed record SeverityBucket(
[property: JsonPropertyName("severity")] string Severity,
[property: JsonPropertyName("count")] int Count,
[property: JsonPropertyName("percentage")] double Percentage,
[property: JsonPropertyName("avg_score")] double AvgScore,
[property: JsonPropertyName("score_range")] ScoreRange ScoreRange,
[property: JsonPropertyName("top_contributors")] ImmutableArray<string> TopContributors);
/// <summary>
/// Score range for a bucket.
/// </summary>
public sealed record ScoreRange(
[property: JsonPropertyName("min")] double Min,
[property: JsonPropertyName("max")] double Max);
/// <summary>
/// Flow from original to final severity after overrides.
/// </summary>
public sealed record SeverityFlow(
[property: JsonPropertyName("from_severity")] string FromSeverity,
[property: JsonPropertyName("to_severity")] string ToSeverity,
[property: JsonPropertyName("count")] int Count,
[property: JsonPropertyName("is_escalation")] bool IsEscalation);
/// <summary>
/// Breakdown by recommended action.
/// </summary>
public sealed record ActionBreakdownAnalysis(
[property: JsonPropertyName("by_action")] ImmutableDictionary<string, ActionBucket> ByAction,
[property: JsonPropertyName("action_flow")] ImmutableArray<ActionFlow> ActionFlow,
[property: JsonPropertyName("decision_stability")] double DecisionStability);
/// <summary>
/// Details for an action bucket.
/// </summary>
public sealed record ActionBucket(
[property: JsonPropertyName("action")] string Action,
[property: JsonPropertyName("count")] int Count,
[property: JsonPropertyName("percentage")] double Percentage,
[property: JsonPropertyName("avg_score")] double AvgScore,
[property: JsonPropertyName("severity_breakdown")] ImmutableDictionary<string, int> SeverityBreakdown);
/// <summary>
/// Flow from original to final action after overrides.
/// </summary>
public sealed record ActionFlow(
[property: JsonPropertyName("from_action")] string FromAction,
[property: JsonPropertyName("to_action")] string ToAction,
[property: JsonPropertyName("count")] int Count);
/// <summary>
/// Breakdown by component/package.
/// </summary>
public sealed record ComponentBreakdownAnalysis(
[property: JsonPropertyName("total_components")] int TotalComponents,
[property: JsonPropertyName("components_with_findings")] int ComponentsWithFindings,
[property: JsonPropertyName("top_risk_components")] ImmutableArray<ComponentRiskSummary> TopRiskComponents,
[property: JsonPropertyName("ecosystem_breakdown")] ImmutableDictionary<string, EcosystemSummary> EcosystemBreakdown);
/// <summary>
/// Risk summary for a component.
/// </summary>
public sealed record ComponentRiskSummary(
[property: JsonPropertyName("component_purl")] string ComponentPurl,
[property: JsonPropertyName("finding_count")] int FindingCount,
[property: JsonPropertyName("max_score")] double MaxScore,
[property: JsonPropertyName("avg_score")] double AvgScore,
[property: JsonPropertyName("highest_severity")] string HighestSeverity,
[property: JsonPropertyName("recommended_action")] string RecommendedAction);
/// <summary>
/// Summary for a package ecosystem.
/// </summary>
public sealed record EcosystemSummary(
[property: JsonPropertyName("ecosystem")] string Ecosystem,
[property: JsonPropertyName("component_count")] int ComponentCount,
[property: JsonPropertyName("finding_count")] int FindingCount,
[property: JsonPropertyName("avg_score")] double AvgScore,
[property: JsonPropertyName("critical_count")] int CriticalCount,
[property: JsonPropertyName("high_count")] int HighCount);
/// <summary>
/// Risk trend analysis (for comparison simulations).
/// </summary>
public sealed record RiskTrendAnalysis(
[property: JsonPropertyName("comparison_type")] string ComparisonType,
[property: JsonPropertyName("score_trend")] TrendMetric ScoreTrend,
[property: JsonPropertyName("severity_trend")] TrendMetric SeverityTrend,
[property: JsonPropertyName("action_trend")] TrendMetric ActionTrend,
[property: JsonPropertyName("findings_improved")] int FindingsImproved,
[property: JsonPropertyName("findings_worsened")] int FindingsWorsened,
[property: JsonPropertyName("findings_unchanged")] int FindingsUnchanged);
/// <summary>
/// Trend metric for comparison.
/// </summary>
public sealed record TrendMetric(
[property: JsonPropertyName("direction")] string Direction,
[property: JsonPropertyName("magnitude")] double Magnitude,
[property: JsonPropertyName("percentage_change")] double PercentageChange,
[property: JsonPropertyName("is_significant")] bool IsSignificant);

View File

@@ -0,0 +1,897 @@
using System.Collections.Immutable;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using StellaOps.Policy.RiskProfile.Models;
namespace StellaOps.Policy.Engine.Simulation;
/// <summary>
/// Service for generating detailed breakdowns of risk simulation results.
/// Per POLICY-RISK-67-003.
/// </summary>
public sealed class RiskSimulationBreakdownService
{
private readonly ILogger<RiskSimulationBreakdownService> _logger;
private static readonly ImmutableArray<string> SeverityOrder = ImmutableArray.Create(
"informational", "low", "medium", "high", "critical");
private static readonly ImmutableArray<string> ActionOrder = ImmutableArray.Create(
"allow", "review", "deny");
public RiskSimulationBreakdownService(ILogger<RiskSimulationBreakdownService> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <summary>
/// Generates a detailed breakdown of a risk simulation result.
/// </summary>
public RiskSimulationBreakdown GenerateBreakdown(
RiskSimulationResult result,
RiskProfileModel profile,
IReadOnlyList<SimulationFinding> findings,
RiskSimulationBreakdownOptions? options = null)
{
ArgumentNullException.ThrowIfNull(result);
ArgumentNullException.ThrowIfNull(profile);
ArgumentNullException.ThrowIfNull(findings);
options ??= RiskSimulationBreakdownOptions.Default;
_logger.LogDebug(
"Generating breakdown for simulation {SimulationId} with {FindingCount} findings",
result.SimulationId, findings.Count);
var profileRef = new ProfileReference(
profile.Id,
profile.Version,
result.ProfileHash,
profile.Description,
profile.Extends);
var signalAnalysis = ComputeSignalAnalysis(result, profile, findings, options);
var overrideAnalysis = ComputeOverrideAnalysis(result, profile);
var scoreDistribution = ComputeScoreDistributionAnalysis(result, options);
var severityBreakdown = ComputeSeverityBreakdownAnalysis(result);
var actionBreakdown = ComputeActionBreakdownAnalysis(result);
var componentBreakdown = options.IncludeComponentBreakdown
? ComputeComponentBreakdownAnalysis(result, findings, options)
: null;
var determinismHash = ComputeDeterminismHash(result, profile);
return new RiskSimulationBreakdown(
result.SimulationId,
profileRef,
signalAnalysis,
overrideAnalysis,
scoreDistribution,
severityBreakdown,
actionBreakdown,
componentBreakdown,
RiskTrends: null, // Set by comparison operations
determinismHash);
}
/// <summary>
/// Generates a breakdown with trend analysis comparing two simulations.
/// </summary>
public RiskSimulationBreakdown GenerateComparisonBreakdown(
RiskSimulationResult baselineResult,
RiskSimulationResult compareResult,
RiskProfileModel baselineProfile,
RiskProfileModel compareProfile,
IReadOnlyList<SimulationFinding> findings,
RiskSimulationBreakdownOptions? options = null)
{
var breakdown = GenerateBreakdown(compareResult, compareProfile, findings, options);
var trends = ComputeRiskTrends(baselineResult, compareResult);
return breakdown with { RiskTrends = trends };
}
private SignalAnalysis ComputeSignalAnalysis(
RiskSimulationResult result,
RiskProfileModel profile,
IReadOnlyList<SimulationFinding> findings,
RiskSimulationBreakdownOptions options)
{
var signalStats = new List<SignalStatistics>();
var totalContribution = 0.0;
var signalsUsed = 0;
var findingsWithMissingSignals = 0;
var missingSignalCounts = new Dictionary<string, int>();
foreach (var signal in profile.Signals)
{
var weight = profile.Weights.GetValueOrDefault(signal.Name, 0.0);
var contributions = new List<double>();
var values = new List<double>();
var findingsWithSignal = 0;
var findingsMissing = 0;
foreach (var findingScore in result.FindingScores)
{
var contribution = findingScore.Contributions?
.FirstOrDefault(c => c.SignalName == signal.Name);
if (contribution != null)
{
findingsWithSignal++;
contributions.Add(contribution.Contribution);
if (contribution.SignalValue is double dv)
values.Add(dv);
else if (contribution.SignalValue is JsonElement je && je.TryGetDouble(out var jd))
values.Add(jd);
}
else
{
findingsMissing++;
missingSignalCounts.TryGetValue(signal.Name, out var count);
missingSignalCounts[signal.Name] = count + 1;
}
}
if (findingsWithSignal > 0)
{
signalsUsed++;
}
var signalTotalContribution = contributions.Sum();
totalContribution += signalTotalContribution;
var valueDistribution = values.Count > 0 && options.IncludeHistograms
? ComputeValueDistribution(values, options.HistogramBuckets)
: null;
signalStats.Add(new SignalStatistics(
signal.Name,
signal.Type.ToString().ToLowerInvariant(),
weight,
findingsWithSignal,
findingsMissing,
result.FindingScores.Count > 0
? (double)findingsWithSignal / result.FindingScores.Count * 100
: 0,
valueDistribution,
signalTotalContribution,
findingsWithSignal > 0 ? signalTotalContribution / findingsWithSignal : 0));
}
// Compute top contributors
var topContributors = signalStats
.Where(s => s.TotalContribution > 0)
.OrderByDescending(s => s.TotalContribution)
.Take(options.TopContributorsCount)
.Select(s => new SignalContributor(
s.SignalName,
s.TotalContribution,
totalContribution > 0 ? s.TotalContribution / totalContribution * 100 : 0,
s.ValueDistribution?.Mean ?? 0,
s.Weight,
s.Weight >= 0 ? "increase" : "decrease"))
.ToImmutableArray();
// Missing signal impact analysis
var avgMissingPerFinding = result.FindingScores.Count > 0
? missingSignalCounts.Values.Sum() / (double)result.FindingScores.Count
: 0;
var mostImpactfulMissing = missingSignalCounts
.OrderByDescending(kvp => kvp.Value * profile.Weights.GetValueOrDefault(kvp.Key, 0))
.Take(5)
.Select(kvp => kvp.Key)
.ToImmutableArray();
var missingImpact = new MissingSignalImpact(
findingsWithMissingSignals,
avgMissingPerFinding,
EstimateMissingSignalImpact(missingSignalCounts, profile),
mostImpactfulMissing);
return new SignalAnalysis(
profile.Signals.Count,
signalsUsed,
profile.Signals.Count - signalsUsed,
profile.Signals.Count > 0 ? (double)signalsUsed / profile.Signals.Count * 100 : 0,
signalStats.ToImmutableArray(),
topContributors,
missingImpact);
}
private OverrideAnalysis ComputeOverrideAnalysis(
RiskSimulationResult result,
RiskProfileModel profile)
{
var severityOverrideDetails = new Dictionary<string, SeverityOverrideTracker>();
var decisionOverrideDetails = new Dictionary<string, DecisionOverrideTracker>();
var severityOverrideCount = 0;
var decisionOverrideCount = 0;
var conflicts = new List<OverrideConflict>();
foreach (var score in result.FindingScores)
{
if (score.OverridesApplied == null)
continue;
foreach (var applied in score.OverridesApplied)
{
var predicateHash = ComputePredicateHash(applied.Predicate);
if (applied.OverrideType == "severity")
{
severityOverrideCount++;
if (!severityOverrideDetails.TryGetValue(predicateHash, out var tracker))
{
tracker = new SeverityOverrideTracker(
predicateHash,
SummarizePredicate(applied.Predicate),
applied.AppliedValue?.ToString() ?? "unknown");
severityOverrideDetails[predicateHash] = tracker;
}
tracker.Count++;
var origSev = applied.OriginalValue?.ToString() ?? "unknown";
tracker.OriginalSeverities.TryGetValue(origSev, out var count);
tracker.OriginalSeverities[origSev] = count + 1;
}
else if (applied.OverrideType == "decision")
{
decisionOverrideCount++;
if (!decisionOverrideDetails.TryGetValue(predicateHash, out var tracker))
{
tracker = new DecisionOverrideTracker(
predicateHash,
SummarizePredicate(applied.Predicate),
applied.AppliedValue?.ToString() ?? "unknown",
applied.Reason);
decisionOverrideDetails[predicateHash] = tracker;
}
tracker.Count++;
var origAction = applied.OriginalValue?.ToString() ?? "unknown";
tracker.OriginalActions.TryGetValue(origAction, out var count);
tracker.OriginalActions[origAction] = count + 1;
}
}
// Check for conflicts (multiple overrides of same type)
var severityOverrides = score.OverridesApplied.Where(o => o.OverrideType == "severity").ToList();
if (severityOverrides.Count > 1)
{
conflicts.Add(new OverrideConflict(
score.FindingId,
"severity_conflict",
SummarizePredicate(severityOverrides[0].Predicate),
SummarizePredicate(severityOverrides[1].Predicate),
"first_match"));
}
}
var totalOverridesEvaluated = profile.Overrides.Severity.Count + profile.Overrides.Decisions.Count;
var overrideApplicationRate = result.FindingScores.Count > 0
? (double)(severityOverrideCount + decisionOverrideCount) / result.FindingScores.Count * 100
: 0;
return new OverrideAnalysis(
totalOverridesEvaluated * result.FindingScores.Count,
severityOverrideCount,
decisionOverrideCount,
overrideApplicationRate,
severityOverrideDetails.Values
.Select(t => new SeverityOverrideDetail(
t.Hash, t.Summary, t.TargetSeverity, t.Count,
t.OriginalSeverities.ToImmutableDictionary()))
.ToImmutableArray(),
decisionOverrideDetails.Values
.Select(t => new DecisionOverrideDetail(
t.Hash, t.Summary, t.TargetAction, t.Reason, t.Count,
t.OriginalActions.ToImmutableDictionary()))
.ToImmutableArray(),
conflicts.ToImmutableArray());
}
private ScoreDistributionAnalysis ComputeScoreDistributionAnalysis(
RiskSimulationResult result,
RiskSimulationBreakdownOptions options)
{
var rawScores = result.FindingScores.Select(s => s.RawScore).ToList();
var normalizedScores = result.FindingScores.Select(s => s.NormalizedScore).ToList();
var rawStats = ComputeScoreStatistics(rawScores);
var normalizedStats = ComputeScoreStatistics(normalizedScores);
var buckets = ComputeScoreBuckets(normalizedScores, options.ScoreBucketCount);
var percentiles = ComputePercentiles(normalizedScores);
var outliers = ComputeOutliers(result.FindingScores, normalizedStats);
return new ScoreDistributionAnalysis(
rawStats,
normalizedStats,
buckets,
percentiles.ToImmutableDictionary(),
outliers);
}
private SeverityBreakdownAnalysis ComputeSeverityBreakdownAnalysis(RiskSimulationResult result)
{
var bySeverity = new Dictionary<string, SeverityBucketBuilder>();
var severityFlows = new Dictionary<(string from, string to), int>();
foreach (var score in result.FindingScores)
{
var severity = score.Severity.ToString().ToLowerInvariant();
if (!bySeverity.TryGetValue(severity, out var bucket))
{
bucket = new SeverityBucketBuilder(severity);
bySeverity[severity] = bucket;
}
bucket.Count++;
bucket.Scores.Add(score.NormalizedScore);
// Track top contributors
var topContributor = score.Contributions?
.OrderByDescending(c => c.ContributionPercentage)
.FirstOrDefault();
if (topContributor != null)
{
bucket.TopContributors.TryGetValue(topContributor.SignalName, out var count);
bucket.TopContributors[topContributor.SignalName] = count + 1;
}
// Track severity flows (from score-based to override-based)
var originalSeverity = DetermineSeverityFromScore(score.NormalizedScore).ToString().ToLowerInvariant();
if (originalSeverity != severity)
{
var flowKey = (originalSeverity, severity);
severityFlows.TryGetValue(flowKey, out var flowCount);
severityFlows[flowKey] = flowCount + 1;
}
}
var total = result.FindingScores.Count;
var severityBuckets = bySeverity.Values
.Select(b => new SeverityBucket(
b.Severity,
b.Count,
total > 0 ? (double)b.Count / total * 100 : 0,
b.Scores.Count > 0 ? b.Scores.Average() : 0,
new ScoreRange(
b.Scores.Count > 0 ? b.Scores.Min() : 0,
b.Scores.Count > 0 ? b.Scores.Max() : 0),
b.TopContributors
.OrderByDescending(kvp => kvp.Value)
.Take(3)
.Select(kvp => kvp.Key)
.ToImmutableArray()))
.ToImmutableDictionary(b => b.Severity);
var flows = severityFlows
.Select(kvp => new SeverityFlow(
kvp.Key.from,
kvp.Key.to,
kvp.Value,
SeverityOrder.IndexOf(kvp.Key.to) > SeverityOrder.IndexOf(kvp.Key.from)))
.ToImmutableArray();
// Severity concentration (HHI - higher = more concentrated)
var concentration = bySeverity.Values.Sum(b =>
Math.Pow((double)b.Count / (total > 0 ? total : 1), 2));
return new SeverityBreakdownAnalysis(severityBuckets, flows, concentration);
}
private ActionBreakdownAnalysis ComputeActionBreakdownAnalysis(RiskSimulationResult result)
{
var byAction = new Dictionary<string, ActionBucketBuilder>();
var actionFlows = new Dictionary<(string from, string to), int>();
foreach (var score in result.FindingScores)
{
var action = score.RecommendedAction.ToString().ToLowerInvariant();
var severity = score.Severity.ToString().ToLowerInvariant();
if (!byAction.TryGetValue(action, out var bucket))
{
bucket = new ActionBucketBuilder(action);
byAction[action] = bucket;
}
bucket.Count++;
bucket.Scores.Add(score.NormalizedScore);
bucket.SeverityCounts.TryGetValue(severity, out var sevCount);
bucket.SeverityCounts[severity] = sevCount + 1;
// Track action flows
var originalAction = DetermineActionFromSeverity(score.Severity).ToString().ToLowerInvariant();
if (originalAction != action)
{
var flowKey = (originalAction, action);
actionFlows.TryGetValue(flowKey, out var flowCount);
actionFlows[flowKey] = flowCount + 1;
}
}
var total = result.FindingScores.Count;
var actionBuckets = byAction.Values
.Select(b => new ActionBucket(
b.Action,
b.Count,
total > 0 ? (double)b.Count / total * 100 : 0,
b.Scores.Count > 0 ? b.Scores.Average() : 0,
b.SeverityCounts.ToImmutableDictionary()))
.ToImmutableDictionary(b => b.Action);
var flows = actionFlows
.Select(kvp => new ActionFlow(kvp.Key.from, kvp.Key.to, kvp.Value))
.ToImmutableArray();
// Decision stability (1 - flow rate)
var totalFlows = flows.Sum(f => f.Count);
var stability = total > 0 ? 1.0 - (double)totalFlows / total : 1.0;
return new ActionBreakdownAnalysis(actionBuckets, flows, stability);
}
private ComponentBreakdownAnalysis ComputeComponentBreakdownAnalysis(
RiskSimulationResult result,
IReadOnlyList<SimulationFinding> findings,
RiskSimulationBreakdownOptions options)
{
var componentScores = new Dictionary<string, ComponentScoreTracker>();
var ecosystemStats = new Dictionary<string, EcosystemTracker>();
foreach (var score in result.FindingScores)
{
var finding = findings.FirstOrDefault(f => f.FindingId == score.FindingId);
var purl = finding?.ComponentPurl ?? "unknown";
var ecosystem = ExtractEcosystem(purl);
// Component tracking
if (!componentScores.TryGetValue(purl, out var tracker))
{
tracker = new ComponentScoreTracker(purl);
componentScores[purl] = tracker;
}
tracker.Scores.Add(score.NormalizedScore);
tracker.Severities.Add(score.Severity);
tracker.Actions.Add(score.RecommendedAction);
// Ecosystem tracking
if (!ecosystemStats.TryGetValue(ecosystem, out var ecoTracker))
{
ecoTracker = new EcosystemTracker(ecosystem);
ecosystemStats[ecosystem] = ecoTracker;
}
ecoTracker.Components.Add(purl);
ecoTracker.FindingCount++;
ecoTracker.Scores.Add(score.NormalizedScore);
if (score.Severity == RiskSeverity.Critical) ecoTracker.CriticalCount++;
if (score.Severity == RiskSeverity.High) ecoTracker.HighCount++;
}
var topComponents = componentScores.Values
.OrderByDescending(c => c.Scores.Max())
.ThenByDescending(c => c.Scores.Count)
.Take(options.TopComponentsCount)
.Select(c => new ComponentRiskSummary(
c.Purl,
c.Scores.Count,
c.Scores.Max(),
c.Scores.Average(),
GetHighestSeverity(c.Severities),
GetMostRestrictiveAction(c.Actions)))
.ToImmutableArray();
var ecosystemBreakdown = ecosystemStats.Values
.Select(e => new EcosystemSummary(
e.Ecosystem,
e.Components.Count,
e.FindingCount,
e.Scores.Count > 0 ? e.Scores.Average() : 0,
e.CriticalCount,
e.HighCount))
.ToImmutableDictionary(e => e.Ecosystem);
return new ComponentBreakdownAnalysis(
componentScores.Count,
componentScores.Values.Count(c => c.Scores.Count > 0),
topComponents,
ecosystemBreakdown);
}
private RiskTrendAnalysis ComputeRiskTrends(
RiskSimulationResult baseline,
RiskSimulationResult compare)
{
var baselineScores = baseline.FindingScores.ToDictionary(s => s.FindingId);
var compareScores = compare.FindingScores.ToDictionary(s => s.FindingId);
var improved = 0;
var worsened = 0;
var unchanged = 0;
var scoreDeltaSum = 0.0;
var severityEscalations = 0;
var severityDeescalations = 0;
var actionChanges = 0;
foreach (var (findingId, baseScore) in baselineScores)
{
if (!compareScores.TryGetValue(findingId, out var compScore))
continue;
var scoreDelta = compScore.NormalizedScore - baseScore.NormalizedScore;
scoreDeltaSum += scoreDelta;
if (Math.Abs(scoreDelta) < 1.0)
unchanged++;
else if (scoreDelta < 0)
improved++;
else
worsened++;
var baseSevIdx = SeverityOrder.IndexOf(baseScore.Severity.ToString().ToLowerInvariant());
var compSevIdx = SeverityOrder.IndexOf(compScore.Severity.ToString().ToLowerInvariant());
if (compSevIdx > baseSevIdx) severityEscalations++;
else if (compSevIdx < baseSevIdx) severityDeescalations++;
if (baseScore.RecommendedAction != compScore.RecommendedAction)
actionChanges++;
}
var baselineAvg = baseline.AggregateMetrics.MeanScore;
var compareAvg = compare.AggregateMetrics.MeanScore;
var scorePercentChange = baselineAvg > 0
? (compareAvg - baselineAvg) / baselineAvg * 100
: 0;
var scoreTrend = new TrendMetric(
scorePercentChange < -1 ? "improving" : scorePercentChange > 1 ? "worsening" : "stable",
Math.Abs(compareAvg - baselineAvg),
scorePercentChange,
Math.Abs(scorePercentChange) > 5);
var severityTrend = new TrendMetric(
severityDeescalations > severityEscalations ? "improving" :
severityEscalations > severityDeescalations ? "worsening" : "stable",
Math.Abs(severityEscalations - severityDeescalations),
baselineScores.Count > 0
? (double)(severityEscalations - severityDeescalations) / baselineScores.Count * 100
: 0,
Math.Abs(severityEscalations - severityDeescalations) > baselineScores.Count * 0.05);
var actionTrend = new TrendMetric(
"changed",
actionChanges,
baselineScores.Count > 0 ? (double)actionChanges / baselineScores.Count * 100 : 0,
actionChanges > baselineScores.Count * 0.1);
return new RiskTrendAnalysis(
"profile_comparison",
scoreTrend,
severityTrend,
actionTrend,
improved,
worsened,
unchanged);
}
private static ValueDistribution ComputeValueDistribution(List<double> values, int bucketCount)
{
if (values.Count == 0)
return new ValueDistribution(null, null, null, null, null, null);
var sorted = values.OrderBy(v => v).ToList();
var min = sorted.First();
var max = sorted.Last();
var mean = values.Average();
var median = sorted.Count % 2 == 0
? (sorted[sorted.Count / 2 - 1] + sorted[sorted.Count / 2]) / 2
: sorted[sorted.Count / 2];
var variance = values.Average(v => Math.Pow(v - mean, 2));
var stdDev = Math.Sqrt(variance);
var histogram = new List<HistogramBucket>();
if (max > min)
{
var bucketSize = (max - min) / bucketCount;
for (var i = 0; i < bucketCount; i++)
{
var rangeMin = min + i * bucketSize;
var rangeMax = min + (i + 1) * bucketSize;
var count = values.Count(v => v >= rangeMin && (i == bucketCount - 1 ? v <= rangeMax : v < rangeMax));
histogram.Add(new HistogramBucket(rangeMin, rangeMax, count, (double)count / values.Count * 100));
}
}
return new ValueDistribution(min, max, mean, median, stdDev, histogram.ToImmutableArray());
}
private static ScoreStatistics ComputeScoreStatistics(List<double> scores)
{
if (scores.Count == 0)
return new ScoreStatistics(0, 0, 0, 0, 0, 0, 0, 0, 0);
var sorted = scores.OrderBy(s => s).ToList();
var mean = scores.Average();
var median = sorted.Count % 2 == 0
? (sorted[sorted.Count / 2 - 1] + sorted[sorted.Count / 2]) / 2
: sorted[sorted.Count / 2];
var variance = scores.Average(s => Math.Pow(s - mean, 2));
var stdDev = Math.Sqrt(variance);
// Skewness and kurtosis
var skewness = stdDev > 0
? scores.Average(s => Math.Pow((s - mean) / stdDev, 3))
: 0;
var kurtosis = stdDev > 0
? scores.Average(s => Math.Pow((s - mean) / stdDev, 4)) - 3
: 0;
return new ScoreStatistics(
scores.Count,
sorted.First(),
sorted.Last(),
Math.Round(mean, 2),
Math.Round(median, 2),
Math.Round(stdDev, 2),
Math.Round(variance, 2),
Math.Round(skewness, 3),
Math.Round(kurtosis, 3));
}
private static ImmutableArray<ScoreBucket> ComputeScoreBuckets(List<double> scores, int bucketCount)
{
var buckets = new List<ScoreBucket>();
var bucketSize = 100.0 / bucketCount;
for (var i = 0; i < bucketCount; i++)
{
var rangeMin = i * bucketSize;
var rangeMax = (i + 1) * bucketSize;
var count = scores.Count(s => s >= rangeMin && s < rangeMax);
var label = i switch
{
0 => "Very Low",
1 => "Low",
2 => "Low-Medium",
3 => "Medium",
4 => "Medium",
5 => "Medium-High",
6 => "High",
7 => "High",
8 => "Very High",
9 => "Critical",
_ => $"Bucket {i + 1}"
};
buckets.Add(new ScoreBucket(
rangeMin, rangeMax, label, count,
scores.Count > 0 ? (double)count / scores.Count * 100 : 0));
}
return buckets.ToImmutableArray();
}
private static Dictionary<string, double> ComputePercentiles(List<double> scores)
{
var percentiles = new Dictionary<string, double>();
if (scores.Count == 0)
return percentiles;
var sorted = scores.OrderBy(s => s).ToList();
var levels = new[] { 0.25, 0.50, 0.75, 0.90, 0.95, 0.99 };
foreach (var level in levels)
{
var index = (int)(level * (sorted.Count - 1));
percentiles[$"p{(int)(level * 100)}"] = sorted[index];
}
return percentiles;
}
private static OutlierAnalysis ComputeOutliers(
IReadOnlyList<FindingScore> scores,
ScoreStatistics stats)
{
if (scores.Count == 0)
return new OutlierAnalysis(0, 0, ImmutableArray<string>.Empty);
// Use IQR method for outlier detection
var sorted = scores.OrderBy(s => s.NormalizedScore).ToList();
var q1Idx = sorted.Count / 4;
var q3Idx = sorted.Count * 3 / 4;
var q1 = sorted[q1Idx].NormalizedScore;
var q3 = sorted[q3Idx].NormalizedScore;
var iqr = q3 - q1;
var threshold = q3 + 1.5 * iqr;
var outliers = scores
.Where(s => s.NormalizedScore > threshold)
.Select(s => s.FindingId)
.ToImmutableArray();
return new OutlierAnalysis(outliers.Length, threshold, outliers);
}
private static double EstimateMissingSignalImpact(
Dictionary<string, int> missingCounts,
RiskProfileModel profile)
{
var impact = 0.0;
foreach (var (signal, count) in missingCounts)
{
var weight = profile.Weights.GetValueOrDefault(signal, 0.0);
// Estimate impact as weight * average value (0.5) * missing count
impact += Math.Abs(weight) * 0.5 * count;
}
return impact;
}
private static RiskSeverity DetermineSeverityFromScore(double score)
{
return score switch
{
>= 90 => RiskSeverity.Critical,
>= 70 => RiskSeverity.High,
>= 40 => RiskSeverity.Medium,
>= 10 => RiskSeverity.Low,
_ => RiskSeverity.Informational
};
}
private static RiskAction DetermineActionFromSeverity(RiskSeverity severity)
{
return severity switch
{
RiskSeverity.Critical => RiskAction.Deny,
RiskSeverity.High => RiskAction.Deny,
RiskSeverity.Medium => RiskAction.Review,
_ => RiskAction.Allow
};
}
private static string ExtractEcosystem(string purl)
{
if (string.IsNullOrWhiteSpace(purl) || !purl.StartsWith("pkg:"))
return "unknown";
var colonIdx = purl.IndexOf(':', 4);
if (colonIdx < 0)
colonIdx = purl.IndexOf('/');
if (colonIdx < 0)
return "unknown";
return purl[4..colonIdx];
}
private static string GetHighestSeverity(List<RiskSeverity> severities)
{
if (severities.Count == 0) return "unknown";
return severities.Max().ToString().ToLowerInvariant();
}
private static string GetMostRestrictiveAction(List<RiskAction> actions)
{
if (actions.Count == 0) return "unknown";
return actions.Max().ToString().ToLowerInvariant();
}
private static string ComputePredicateHash(Dictionary<string, object> predicate)
{
var json = JsonSerializer.Serialize(predicate, new JsonSerializerOptions
{
WriteIndented = false,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(json));
return Convert.ToHexString(bytes)[..8].ToLowerInvariant();
}
private static string SummarizePredicate(Dictionary<string, object> predicate)
{
var parts = predicate.Select(kvp => $"{kvp.Key}={kvp.Value}");
return string.Join(", ", parts);
}
private static string ComputeDeterminismHash(RiskSimulationResult result, RiskProfileModel profile)
{
var input = $"{result.SimulationId}:{result.ProfileHash}:{result.FindingScores.Count}";
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(input));
return $"sha256:{Convert.ToHexString(bytes)[..16].ToLowerInvariant()}";
}
// Helper classes for tracking state during computation
private sealed class SeverityOverrideTracker(string hash, string summary, string targetSeverity)
{
public string Hash { get; } = hash;
public string Summary { get; } = summary;
public string TargetSeverity { get; } = targetSeverity;
public int Count { get; set; }
public Dictionary<string, int> OriginalSeverities { get; } = new();
}
private sealed class DecisionOverrideTracker(string hash, string summary, string targetAction, string? reason)
{
public string Hash { get; } = hash;
public string Summary { get; } = summary;
public string TargetAction { get; } = targetAction;
public string? Reason { get; } = reason;
public int Count { get; set; }
public Dictionary<string, int> OriginalActions { get; } = new();
}
private sealed class SeverityBucketBuilder(string severity)
{
public string Severity { get; } = severity;
public int Count { get; set; }
public List<double> Scores { get; } = new();
public Dictionary<string, int> TopContributors { get; } = new();
}
private sealed class ActionBucketBuilder(string action)
{
public string Action { get; } = action;
public int Count { get; set; }
public List<double> Scores { get; } = new();
public Dictionary<string, int> SeverityCounts { get; } = new();
}
private sealed class ComponentScoreTracker(string purl)
{
public string Purl { get; } = purl;
public List<double> Scores { get; } = new();
public List<RiskSeverity> Severities { get; } = new();
public List<RiskAction> Actions { get; } = new();
}
private sealed class EcosystemTracker(string ecosystem)
{
public string Ecosystem { get; } = ecosystem;
public HashSet<string> Components { get; } = new();
public int FindingCount { get; set; }
public List<double> Scores { get; } = new();
public int CriticalCount { get; set; }
public int HighCount { get; set; }
}
}
/// <summary>
/// Options for risk simulation breakdown generation.
/// </summary>
public sealed record RiskSimulationBreakdownOptions
{
/// <summary>Whether to include component breakdown analysis.</summary>
public bool IncludeComponentBreakdown { get; init; } = true;
/// <summary>Whether to include value histograms for signals.</summary>
public bool IncludeHistograms { get; init; } = true;
/// <summary>Number of histogram buckets.</summary>
public int HistogramBuckets { get; init; } = 10;
/// <summary>Number of score buckets for distribution.</summary>
public int ScoreBucketCount { get; init; } = 10;
/// <summary>Number of top signal contributors to include.</summary>
public int TopContributorsCount { get; init; } = 10;
/// <summary>Number of top components to include.</summary>
public int TopComponentsCount { get; init; } = 20;
/// <summary>Default options.</summary>
public static RiskSimulationBreakdownOptions Default { get; } = new();
/// <summary>Minimal options for quick analysis.</summary>
public static RiskSimulationBreakdownOptions Quick { get; } = new()
{
IncludeComponentBreakdown = false,
IncludeHistograms = false,
TopContributorsCount = 5,
TopComponentsCount = 10
};
}

View File

@@ -12,6 +12,7 @@ namespace StellaOps.Policy.Engine.Simulation;
/// <summary>
/// Service for running risk simulations with score distributions and contribution breakdowns.
/// Enhanced with detailed breakdown analytics per POLICY-RISK-67-003.
/// </summary>
public sealed class RiskSimulationService
{
@@ -20,6 +21,7 @@ public sealed class RiskSimulationService
private readonly RiskProfileConfigurationService _profileService;
private readonly RiskProfileHasher _hasher;
private readonly ICryptoHash _cryptoHash;
private readonly RiskSimulationBreakdownService? _breakdownService;
private static readonly double[] PercentileLevels = { 0.25, 0.50, 0.75, 0.90, 0.95, 0.99 };
private const int TopMoverCount = 10;
@@ -29,13 +31,15 @@ public sealed class RiskSimulationService
ILogger<RiskSimulationService> logger,
TimeProvider timeProvider,
RiskProfileConfigurationService profileService,
ICryptoHash cryptoHash)
ICryptoHash cryptoHash,
RiskSimulationBreakdownService? breakdownService = null)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
_profileService = profileService ?? throw new ArgumentNullException(nameof(profileService));
_cryptoHash = cryptoHash ?? throw new ArgumentNullException(nameof(cryptoHash));
_hasher = new RiskProfileHasher(cryptoHash);
_breakdownService = breakdownService;
}
/// <summary>
@@ -461,4 +465,183 @@ public sealed class RiskSimulationService
var hash = _cryptoHash.ComputeHashHexForPurpose(Encoding.UTF8.GetBytes(seed), HashPurpose.Content);
return $"rsim-{hash[..16]}";
}
/// <summary>
/// Runs a risk simulation with detailed breakdown analytics.
/// Per POLICY-RISK-67-003.
/// </summary>
public RiskSimulationWithBreakdown SimulateWithBreakdown(
RiskSimulationRequest request,
RiskSimulationBreakdownOptions? breakdownOptions = null)
{
ArgumentNullException.ThrowIfNull(request);
if (_breakdownService == null)
{
throw new InvalidOperationException(
"Breakdown service not available. Register RiskSimulationBreakdownService in DI.");
}
using var activity = PolicyEngineTelemetry.ActivitySource.StartActivity("risk_simulation.run_with_breakdown");
activity?.SetTag("profile.id", request.ProfileId);
activity?.SetTag("finding.count", request.Findings.Count);
var sw = Stopwatch.StartNew();
// Run simulation with contributions enabled for breakdown
var simulationRequest = request with { IncludeContributions = true };
var result = Simulate(simulationRequest);
var profile = _profileService.GetProfile(request.ProfileId);
if (profile == null)
{
throw new InvalidOperationException($"Risk profile '{request.ProfileId}' not found.");
}
// Generate breakdown
var breakdown = _breakdownService.GenerateBreakdown(
result,
profile,
request.Findings,
breakdownOptions);
sw.Stop();
_logger.LogInformation(
"Risk simulation with breakdown {SimulationId} completed in {ElapsedMs}ms",
result.SimulationId, sw.Elapsed.TotalMilliseconds);
PolicyEngineTelemetry.RiskSimulationsRun.Add(1);
return new RiskSimulationWithBreakdown(result, breakdown, sw.Elapsed.TotalMilliseconds);
}
/// <summary>
/// Runs a comparison simulation between two profiles with trend analysis.
/// Per POLICY-RISK-67-003.
/// </summary>
public RiskProfileComparisonResult CompareProfilesWithBreakdown(
string baseProfileId,
string compareProfileId,
IReadOnlyList<SimulationFinding> findings,
RiskSimulationBreakdownOptions? breakdownOptions = null)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(baseProfileId);
ArgumentNullException.ThrowIfNullOrWhiteSpace(compareProfileId);
ArgumentNullException.ThrowIfNull(findings);
if (_breakdownService == null)
{
throw new InvalidOperationException(
"Breakdown service not available. Register RiskSimulationBreakdownService in DI.");
}
using var activity = PolicyEngineTelemetry.ActivitySource.StartActivity("risk_simulation.compare_profiles");
activity?.SetTag("profile.base", baseProfileId);
activity?.SetTag("profile.compare", compareProfileId);
activity?.SetTag("finding.count", findings.Count);
var sw = Stopwatch.StartNew();
// Run baseline simulation
var baselineRequest = new RiskSimulationRequest(
ProfileId: baseProfileId,
ProfileVersion: null,
Findings: findings,
IncludeContributions: true,
IncludeDistribution: true,
Mode: SimulationMode.Full);
var baselineResult = Simulate(baselineRequest);
// Run comparison simulation
var compareRequest = new RiskSimulationRequest(
ProfileId: compareProfileId,
ProfileVersion: null,
Findings: findings,
IncludeContributions: true,
IncludeDistribution: true,
Mode: SimulationMode.Full);
var compareResult = Simulate(compareRequest);
// Get profiles
var baseProfile = _profileService.GetProfile(baseProfileId)
?? throw new InvalidOperationException($"Profile '{baseProfileId}' not found.");
var compareProfile = _profileService.GetProfile(compareProfileId)
?? throw new InvalidOperationException($"Profile '{compareProfileId}' not found.");
// Generate breakdown with trends
var breakdown = _breakdownService.GenerateComparisonBreakdown(
baselineResult,
compareResult,
baseProfile,
compareProfile,
findings,
breakdownOptions);
sw.Stop();
_logger.LogInformation(
"Profile comparison completed between {BaseProfile} and {CompareProfile} in {ElapsedMs}ms",
baseProfileId, compareProfileId, sw.Elapsed.TotalMilliseconds);
return new RiskProfileComparisonResult(
BaselineResult: baselineResult,
CompareResult: compareResult,
Breakdown: breakdown,
ExecutionTimeMs: sw.Elapsed.TotalMilliseconds);
}
/// <summary>
/// Generates a standalone breakdown for an existing simulation result.
/// </summary>
public RiskSimulationBreakdown GenerateBreakdown(
RiskSimulationResult result,
IReadOnlyList<SimulationFinding> findings,
RiskSimulationBreakdownOptions? options = null)
{
ArgumentNullException.ThrowIfNull(result);
ArgumentNullException.ThrowIfNull(findings);
if (_breakdownService == null)
{
throw new InvalidOperationException(
"Breakdown service not available. Register RiskSimulationBreakdownService in DI.");
}
var profile = _profileService.GetProfile(result.ProfileId)
?? throw new InvalidOperationException($"Profile '{result.ProfileId}' not found.");
return _breakdownService.GenerateBreakdown(result, profile, findings, options);
}
}
/// <summary>
/// Risk simulation result with detailed breakdown.
/// Per POLICY-RISK-67-003.
/// </summary>
public sealed record RiskSimulationWithBreakdown(
/// <summary>The simulation result.</summary>
RiskSimulationResult Result,
/// <summary>Detailed breakdown analytics.</summary>
RiskSimulationBreakdown Breakdown,
/// <summary>Total execution time including breakdown generation.</summary>
double TotalExecutionTimeMs);
/// <summary>
/// Result of comparing two risk profiles.
/// Per POLICY-RISK-67-003.
/// </summary>
public sealed record RiskProfileComparisonResult(
/// <summary>Baseline simulation result.</summary>
RiskSimulationResult BaselineResult,
/// <summary>Comparison simulation result.</summary>
RiskSimulationResult CompareResult,
/// <summary>Breakdown with trend analysis.</summary>
RiskSimulationBreakdown Breakdown,
/// <summary>Total execution time.</summary>
double ExecutionTimeMs);

View File

@@ -585,6 +585,72 @@ public static class PolicyEngineTelemetry
#endregion
#region AirGap/Staleness Metrics
// Counter: policy_airgap_staleness_events_total{tenant,event_type}
private static readonly Counter<long> StalenessEventsCounter =
Meter.CreateCounter<long>(
"policy_airgap_staleness_events_total",
unit: "events",
description: "Total staleness events by type (warning, breach, recovered, anchor_missing).");
// Gauge: policy_airgap_sealed
private static readonly ObservableGauge<int> AirGapSealedGauge =
Meter.CreateObservableGauge<int>(
"policy_airgap_sealed",
observeValues: () => AirGapSealedObservations ?? Enumerable.Empty<Measurement<int>>(),
unit: "boolean",
description: "1 if sealed, 0 if unsealed.");
// Gauge: policy_airgap_anchor_age_seconds
private static readonly ObservableGauge<int> AnchorAgeGauge =
Meter.CreateObservableGauge<int>(
"policy_airgap_anchor_age_seconds",
observeValues: () => AnchorAgeObservations ?? Enumerable.Empty<Measurement<int>>(),
unit: "s",
description: "Current age of the time anchor in seconds.");
private static IEnumerable<Measurement<int>> AirGapSealedObservations = Enumerable.Empty<Measurement<int>>();
private static IEnumerable<Measurement<int>> AnchorAgeObservations = Enumerable.Empty<Measurement<int>>();
/// <summary>
/// Records a staleness event.
/// </summary>
/// <param name="tenant">Tenant identifier.</param>
/// <param name="eventType">Event type (warning, breach, recovered, anchor_missing).</param>
public static void RecordStalenessEvent(string tenant, string eventType)
{
var tags = new TagList
{
{ "tenant", NormalizeTenant(tenant) },
{ "event_type", NormalizeTag(eventType) },
};
StalenessEventsCounter.Add(1, tags);
}
/// <summary>
/// Registers a callback to observe air-gap sealed state.
/// </summary>
/// <param name="observeFunc">Function that returns current sealed state measurements.</param>
public static void RegisterAirGapSealedObservation(Func<IEnumerable<Measurement<int>>> observeFunc)
{
ArgumentNullException.ThrowIfNull(observeFunc);
AirGapSealedObservations = observeFunc();
}
/// <summary>
/// Registers a callback to observe time anchor age.
/// </summary>
/// <param name="observeFunc">Function that returns current anchor age measurements.</param>
public static void RegisterAnchorAgeObservation(Func<IEnumerable<Measurement<int>>> observeFunc)
{
ArgumentNullException.ThrowIfNull(observeFunc);
AnchorAgeObservations = observeFunc();
}
#endregion
// Storage for observable gauge observations
private static IEnumerable<Measurement<int>> QueueDepthObservations = Enumerable.Empty<Measurement<int>>();
private static IEnumerable<Measurement<int>> ConcurrentEvaluationsObservations = Enumerable.Empty<Measurement<int>>();