audit work, fixed StellaOps.sln warnings/errors, fixed tests, sprints work, new advisories
This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
// <copyright file="FacetAdmissionValidator.cs" company="StellaOps">
|
||||
// Copyright (c) StellaOps. Licensed under AGPL-3.0-or-later.
|
||||
// </copyright>
|
||||
// Sprint: SPRINT_20260105_002_004_CLI (ADM-001 through ADM-007)
|
||||
|
||||
using System.Collections.Immutable;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using StellaOps.Facet;
|
||||
using StellaOps.Zastava.Core.Contracts;
|
||||
|
||||
namespace StellaOps.Zastava.Webhook.Admission;
|
||||
|
||||
/// <summary>
|
||||
/// Validates facet seals during admission.
|
||||
/// </summary>
|
||||
public interface IFacetAdmissionValidator
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates facet seal for an image admission request.
|
||||
/// </summary>
|
||||
Task<FacetAdmissionResult> ValidateAsync(
|
||||
FacetAdmissionRequest request,
|
||||
CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates facet seals and drift quotas during Kubernetes admission.
|
||||
/// </summary>
|
||||
public sealed class FacetAdmissionValidator : IFacetAdmissionValidator
|
||||
{
|
||||
private readonly IFacetSealStore _sealStore;
|
||||
private readonly IFacetDriftDetector _driftDetector;
|
||||
private readonly ILogger<FacetAdmissionValidator> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// The namespace annotation key that enables facet validation.
|
||||
/// </summary>
|
||||
public const string FacetSealRequiredAnnotation = "stellaops.io/facet-seal-required";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of <see cref="FacetAdmissionValidator"/>.
|
||||
/// </summary>
|
||||
public FacetAdmissionValidator(
|
||||
IFacetSealStore sealStore,
|
||||
IFacetDriftDetector driftDetector,
|
||||
ILogger<FacetAdmissionValidator>? logger = null)
|
||||
{
|
||||
_sealStore = sealStore ?? throw new ArgumentNullException(nameof(sealStore));
|
||||
_driftDetector = driftDetector ?? throw new ArgumentNullException(nameof(driftDetector));
|
||||
_logger = logger ?? NullLogger<FacetAdmissionValidator>.Instance;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<FacetAdmissionResult> ValidateAsync(
|
||||
FacetAdmissionRequest request,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
|
||||
// Check if facet validation is required for this namespace
|
||||
if (!IsFacetValidationRequired(request.NamespaceAnnotations))
|
||||
{
|
||||
return FacetAdmissionResult.Allow("Facet validation not required for namespace");
|
||||
}
|
||||
|
||||
// Load seal for image
|
||||
var seal = await _sealStore.GetLatestSealAsync(request.ImageDigest, ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (seal is null)
|
||||
{
|
||||
if (request.RequireSeal)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"No facet seal found for image {Image}, seal required by policy",
|
||||
request.ImageDigest);
|
||||
|
||||
return FacetAdmissionResult.Deny(
|
||||
"facet.seal.missing",
|
||||
$"No facet seal found for image {request.ImageDigest}");
|
||||
}
|
||||
|
||||
return FacetAdmissionResult.Allow("No seal found, seal not required");
|
||||
}
|
||||
|
||||
_logger.LogDebug(
|
||||
"Found facet seal {SealRoot} for image {Image}",
|
||||
TruncateHash(seal.CombinedMerkleRoot),
|
||||
request.ImageDigest);
|
||||
|
||||
// Compare against current state if we have a baseline
|
||||
if (request.CurrentSealRoot is null)
|
||||
{
|
||||
// No current state to compare - accept the baseline
|
||||
return FacetAdmissionResult.Allow(
|
||||
$"Facet seal verified: {TruncateHash(seal.CombinedMerkleRoot)}");
|
||||
}
|
||||
|
||||
// Get the current seal to compute drift
|
||||
var currentSeal = await _sealStore.GetByCombinedRootAsync(request.CurrentSealRoot, ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (currentSeal is null)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Current seal {SealRoot} not found for image {Image}",
|
||||
request.CurrentSealRoot,
|
||||
request.ImageDigest);
|
||||
|
||||
return FacetAdmissionResult.AllowWithWarning(
|
||||
"facet.seal.current_not_found",
|
||||
$"Current seal not found, using baseline: {TruncateHash(seal.CombinedMerkleRoot)}");
|
||||
}
|
||||
|
||||
// Compute drift between baseline and current
|
||||
_logger.LogDebug(
|
||||
"Computing drift between baseline {Baseline} and current {Current}",
|
||||
TruncateHash(seal.CombinedMerkleRoot),
|
||||
TruncateHash(currentSeal.CombinedMerkleRoot));
|
||||
|
||||
var driftReport = await _driftDetector.DetectDriftAsync(seal, currentSeal, ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Facet drift for {Image}: verdict={Verdict}, changes={Changes}",
|
||||
request.ImageDigest,
|
||||
driftReport.OverallVerdict,
|
||||
driftReport.TotalChangedFiles);
|
||||
|
||||
// Evaluate verdict
|
||||
return driftReport.OverallVerdict switch
|
||||
{
|
||||
QuotaVerdict.Ok => FacetAdmissionResult.Allow(
|
||||
$"Facet quotas OK: {driftReport.TotalChangedFiles} changes within limits"),
|
||||
|
||||
QuotaVerdict.Warning => FacetAdmissionResult.AllowWithWarning(
|
||||
"facet.quota.warning",
|
||||
$"Facet drift warning: {FormatBreaches(driftReport)}"),
|
||||
|
||||
QuotaVerdict.Blocked => FacetAdmissionResult.Deny(
|
||||
"facet.quota.exceeded",
|
||||
$"Facet quota exceeded: {FormatBreaches(driftReport)}"),
|
||||
|
||||
QuotaVerdict.RequiresVex => FacetAdmissionResult.Deny(
|
||||
"facet.vex.required",
|
||||
$"Facet drift requires VEX authorization: {FormatBreaches(driftReport)}"),
|
||||
|
||||
_ => FacetAdmissionResult.Allow("Unknown verdict - allowing")
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if facet validation is required based on namespace annotations.
|
||||
/// </summary>
|
||||
public static bool IsFacetValidationRequired(IReadOnlyDictionary<string, string>? annotations)
|
||||
{
|
||||
if (annotations is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return annotations.TryGetValue(FacetSealRequiredAnnotation, out var value) &&
|
||||
string.Equals(value, "true", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string FormatBreaches(FacetDriftReport report)
|
||||
{
|
||||
var breaches = report.FacetDrifts
|
||||
.Where(d => d.QuotaVerdict != QuotaVerdict.Ok)
|
||||
.Select(d => $"{d.FacetId}({d.ChurnPercent:F1}%)")
|
||||
.ToArray();
|
||||
|
||||
return string.Join(", ", breaches);
|
||||
}
|
||||
|
||||
private static string TruncateHash(string? hash)
|
||||
{
|
||||
if (string.IsNullOrEmpty(hash)) return "(none)";
|
||||
return hash.Length > 16 ? $"{hash[..8]}...{hash[^8..]}" : hash;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request for facet admission validation.
|
||||
/// </summary>
|
||||
public sealed record FacetAdmissionRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// The image digest being admitted.
|
||||
/// </summary>
|
||||
public required string ImageDigest { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Namespace annotations for policy evaluation.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, string>? NamespaceAnnotations { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether a seal is required by namespace policy.
|
||||
/// </summary>
|
||||
public bool RequireSeal { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The current seal root to compare against (if drift detection is needed).
|
||||
/// </summary>
|
||||
public string? CurrentSealRoot { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of facet admission validation.
|
||||
/// </summary>
|
||||
public sealed record FacetAdmissionResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether admission is allowed.
|
||||
/// </summary>
|
||||
public required bool Allowed { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether this is a warning (allowed but with caution).
|
||||
/// </summary>
|
||||
public bool IsWarning { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Error or warning code for denied/warning results.
|
||||
/// </summary>
|
||||
public string? Code { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Human-readable message describing the result.
|
||||
/// </summary>
|
||||
public required string Message { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates an allow result.
|
||||
/// </summary>
|
||||
public static FacetAdmissionResult Allow(string message)
|
||||
=> new() { Allowed = true, Message = message };
|
||||
|
||||
/// <summary>
|
||||
/// Creates an allow result with a warning.
|
||||
/// </summary>
|
||||
public static FacetAdmissionResult AllowWithWarning(string code, string message)
|
||||
=> new() { Allowed = true, IsWarning = true, Code = code, Message = message };
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deny result.
|
||||
/// </summary>
|
||||
public static FacetAdmissionResult Deny(string code, string message)
|
||||
=> new() { Allowed = false, Code = code, Message = message };
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -38,7 +39,7 @@ public sealed class AuthorityTokenHealthCheck : IHealthCheck
|
||||
"Authority token acquired.",
|
||||
data: new Dictionary<string, object>
|
||||
{
|
||||
["expiresAtUtc"] = token.ExpiresAtUtc?.ToString("O") ?? "static",
|
||||
["expiresAtUtc"] = token.ExpiresAtUtc?.ToString("O", CultureInfo.InvariantCulture) ?? "static",
|
||||
["tokenType"] = token.TokenType
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
|
||||
namespace StellaOps.Zastava.Webhook.Certificates;
|
||||
@@ -31,7 +32,7 @@ public sealed class WebhookCertificateHealthCheck : IHealthCheck
|
||||
{
|
||||
return Task.FromResult(HealthCheckResult.Unhealthy("Webhook certificate expired.", data: new Dictionary<string, object>
|
||||
{
|
||||
["expiresAtUtc"] = expires.ToString("O")
|
||||
["expiresAtUtc"] = expires.ToString("O", CultureInfo.InvariantCulture)
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -39,14 +40,14 @@ public sealed class WebhookCertificateHealthCheck : IHealthCheck
|
||||
{
|
||||
return Task.FromResult(HealthCheckResult.Degraded("Webhook certificate nearing expiry.", data: new Dictionary<string, object>
|
||||
{
|
||||
["expiresAtUtc"] = expires.ToString("O"),
|
||||
["expiresAtUtc"] = expires.ToString("O", CultureInfo.InvariantCulture),
|
||||
["daysRemaining"] = remaining.TotalDays
|
||||
}));
|
||||
}
|
||||
|
||||
return Task.FromResult(HealthCheckResult.Healthy("Webhook certificate valid.", data: new Dictionary<string, object>
|
||||
{
|
||||
["expiresAtUtc"] = expires.ToString("O"),
|
||||
["expiresAtUtc"] = expires.ToString("O", CultureInfo.InvariantCulture),
|
||||
["daysRemaining"] = remaining.TotalDays
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -21,5 +21,7 @@
|
||||
<ProjectReference Include="../../Scanner/__Libraries/StellaOps.Scanner.Surface.Secrets/StellaOps.Scanner.Surface.Secrets.csproj" />
|
||||
<ProjectReference Include="../../Scanner/__Libraries/StellaOps.Scanner.Surface.Validation/StellaOps.Scanner.Surface.Validation.csproj" />
|
||||
<ProjectReference Include="../../__Libraries/StellaOps.Cryptography.DependencyInjection/StellaOps.Cryptography.DependencyInjection.csproj" />
|
||||
<!-- Facet seal admission (SPRINT_20260105_002_004_CLI) -->
|
||||
<ProjectReference Include="../../__Libraries/StellaOps.Facet/StellaOps.Facet.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -9,10 +9,6 @@
|
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xunit.runner.visualstudio" >
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Moq" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
@@ -10,10 +10,6 @@
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" >
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Moq" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// FacetAdmissionValidatorTests.cs
|
||||
// Sprint: SPRINT_20260105_002_004_CLI (ADM-006)
|
||||
// Description: Unit tests for facet seal admission validator.
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
using System.Collections.Immutable;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
using StellaOps.Facet;
|
||||
using StellaOps.Zastava.Webhook.Admission;
|
||||
|
||||
namespace StellaOps.Zastava.Webhook.Tests.Admission;
|
||||
|
||||
/// <summary>
|
||||
/// Unit tests for the FacetAdmissionValidator.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class FacetAdmissionValidatorTests
|
||||
{
|
||||
private readonly Mock<IFacetSealStore> _mockSealStore;
|
||||
private readonly Mock<IFacetDriftDetector> _mockDriftDetector;
|
||||
private readonly FacetAdmissionValidator _validator;
|
||||
|
||||
public FacetAdmissionValidatorTests()
|
||||
{
|
||||
_mockSealStore = new Mock<IFacetSealStore>();
|
||||
_mockDriftDetector = new Mock<IFacetDriftDetector>();
|
||||
_validator = new FacetAdmissionValidator(
|
||||
_mockSealStore.Object,
|
||||
_mockDriftDetector.Object);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_WithoutAnnotation_ReturnsAllow()
|
||||
{
|
||||
// Arrange
|
||||
var request = new FacetAdmissionRequest
|
||||
{
|
||||
ImageDigest = "sha256:abc123",
|
||||
NamespaceAnnotations = new Dictionary<string, string>()
|
||||
};
|
||||
|
||||
// Act
|
||||
var result = await _validator.ValidateAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.Allowed);
|
||||
Assert.Contains("not required", result.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_WithAnnotationFalse_ReturnsAllow()
|
||||
{
|
||||
// Arrange
|
||||
var request = new FacetAdmissionRequest
|
||||
{
|
||||
ImageDigest = "sha256:abc123",
|
||||
NamespaceAnnotations = new Dictionary<string, string>
|
||||
{
|
||||
[FacetAdmissionValidator.FacetSealRequiredAnnotation] = "false"
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
var result = await _validator.ValidateAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.Allowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_WithAnnotationTrue_NoSeal_RequireSeal_ReturnsDeny()
|
||||
{
|
||||
// Arrange
|
||||
var request = new FacetAdmissionRequest
|
||||
{
|
||||
ImageDigest = "sha256:abc123",
|
||||
NamespaceAnnotations = new Dictionary<string, string>
|
||||
{
|
||||
[FacetAdmissionValidator.FacetSealRequiredAnnotation] = "true"
|
||||
},
|
||||
RequireSeal = true
|
||||
};
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetLatestSealAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync((FacetSeal?)null);
|
||||
|
||||
// Act
|
||||
var result = await _validator.ValidateAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.Allowed);
|
||||
Assert.Equal("facet.seal.missing", result.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_WithAnnotationTrue_NoSeal_NotRequired_ReturnsAllow()
|
||||
{
|
||||
// Arrange
|
||||
var request = new FacetAdmissionRequest
|
||||
{
|
||||
ImageDigest = "sha256:abc123",
|
||||
NamespaceAnnotations = new Dictionary<string, string>
|
||||
{
|
||||
[FacetAdmissionValidator.FacetSealRequiredAnnotation] = "true"
|
||||
},
|
||||
RequireSeal = false
|
||||
};
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetLatestSealAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync((FacetSeal?)null);
|
||||
|
||||
// Act
|
||||
var result = await _validator.ValidateAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.Allowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_WithSeal_NoCurrentRoot_ReturnsAllow()
|
||||
{
|
||||
// Arrange
|
||||
var seal = CreateTestSeal("sha256:abc123");
|
||||
var request = new FacetAdmissionRequest
|
||||
{
|
||||
ImageDigest = "sha256:abc123",
|
||||
NamespaceAnnotations = new Dictionary<string, string>
|
||||
{
|
||||
[FacetAdmissionValidator.FacetSealRequiredAnnotation] = "true"
|
||||
},
|
||||
CurrentSealRoot = null
|
||||
};
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetLatestSealAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(seal);
|
||||
|
||||
// Act
|
||||
var result = await _validator.ValidateAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.Allowed);
|
||||
Assert.Contains("verified", result.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_DriftOk_ReturnsAllow()
|
||||
{
|
||||
// Arrange
|
||||
var baseline = CreateTestSeal("sha256:abc123", "baseline-root");
|
||||
var current = CreateTestSeal("sha256:abc123", "current-root");
|
||||
var driftReport = CreateDriftReport(QuotaVerdict.Ok, 0);
|
||||
|
||||
var request = new FacetAdmissionRequest
|
||||
{
|
||||
ImageDigest = "sha256:abc123",
|
||||
NamespaceAnnotations = new Dictionary<string, string>
|
||||
{
|
||||
[FacetAdmissionValidator.FacetSealRequiredAnnotation] = "true"
|
||||
},
|
||||
CurrentSealRoot = "current-root"
|
||||
};
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetLatestSealAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(baseline);
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetByCombinedRootAsync("current-root", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(current);
|
||||
|
||||
_mockDriftDetector
|
||||
.Setup(x => x.DetectDriftAsync(baseline, current, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(driftReport);
|
||||
|
||||
// Act
|
||||
var result = await _validator.ValidateAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.Allowed);
|
||||
Assert.Contains("Facet quotas OK", result.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_DriftWarning_ReturnsAllowWithWarning()
|
||||
{
|
||||
// Arrange
|
||||
var baseline = CreateTestSeal("sha256:abc123", "baseline-root");
|
||||
var current = CreateTestSeal("sha256:abc123", "current-root");
|
||||
var driftReport = CreateDriftReport(QuotaVerdict.Warning, 5);
|
||||
|
||||
var request = new FacetAdmissionRequest
|
||||
{
|
||||
ImageDigest = "sha256:abc123",
|
||||
NamespaceAnnotations = new Dictionary<string, string>
|
||||
{
|
||||
[FacetAdmissionValidator.FacetSealRequiredAnnotation] = "true"
|
||||
},
|
||||
CurrentSealRoot = "current-root"
|
||||
};
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetLatestSealAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(baseline);
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetByCombinedRootAsync("current-root", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(current);
|
||||
|
||||
_mockDriftDetector
|
||||
.Setup(x => x.DetectDriftAsync(baseline, current, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(driftReport);
|
||||
|
||||
// Act
|
||||
var result = await _validator.ValidateAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.Allowed);
|
||||
Assert.True(result.IsWarning);
|
||||
Assert.Equal("facet.quota.warning", result.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_DriftBlocked_ReturnsDeny()
|
||||
{
|
||||
// Arrange
|
||||
var baseline = CreateTestSeal("sha256:abc123", "baseline-root");
|
||||
var current = CreateTestSeal("sha256:abc123", "current-root");
|
||||
var driftReport = CreateDriftReport(QuotaVerdict.Blocked, 100);
|
||||
|
||||
var request = new FacetAdmissionRequest
|
||||
{
|
||||
ImageDigest = "sha256:abc123",
|
||||
NamespaceAnnotations = new Dictionary<string, string>
|
||||
{
|
||||
[FacetAdmissionValidator.FacetSealRequiredAnnotation] = "true"
|
||||
},
|
||||
CurrentSealRoot = "current-root"
|
||||
};
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetLatestSealAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(baseline);
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetByCombinedRootAsync("current-root", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(current);
|
||||
|
||||
_mockDriftDetector
|
||||
.Setup(x => x.DetectDriftAsync(baseline, current, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(driftReport);
|
||||
|
||||
// Act
|
||||
var result = await _validator.ValidateAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.Allowed);
|
||||
Assert.Equal("facet.quota.exceeded", result.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_DriftRequiresVex_ReturnsDeny()
|
||||
{
|
||||
// Arrange
|
||||
var baseline = CreateTestSeal("sha256:abc123", "baseline-root");
|
||||
var current = CreateTestSeal("sha256:abc123", "current-root");
|
||||
var driftReport = CreateDriftReport(QuotaVerdict.RequiresVex, 50);
|
||||
|
||||
var request = new FacetAdmissionRequest
|
||||
{
|
||||
ImageDigest = "sha256:abc123",
|
||||
NamespaceAnnotations = new Dictionary<string, string>
|
||||
{
|
||||
[FacetAdmissionValidator.FacetSealRequiredAnnotation] = "true"
|
||||
},
|
||||
CurrentSealRoot = "current-root"
|
||||
};
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetLatestSealAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(baseline);
|
||||
|
||||
_mockSealStore
|
||||
.Setup(x => x.GetByCombinedRootAsync("current-root", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(current);
|
||||
|
||||
_mockDriftDetector
|
||||
.Setup(x => x.DetectDriftAsync(baseline, current, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(driftReport);
|
||||
|
||||
// Act
|
||||
var result = await _validator.ValidateAsync(request);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.Allowed);
|
||||
Assert.Equal("facet.vex.required", result.Code);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("true", true)]
|
||||
[InlineData("TRUE", true)]
|
||||
[InlineData("True", true)]
|
||||
[InlineData("false", false)]
|
||||
[InlineData("", false)]
|
||||
[InlineData("no", false)]
|
||||
public void IsFacetValidationRequired_VariousValues_ReturnsExpected(string value, bool expected)
|
||||
{
|
||||
// Arrange
|
||||
var annotations = new Dictionary<string, string>
|
||||
{
|
||||
[FacetAdmissionValidator.FacetSealRequiredAnnotation] = value
|
||||
};
|
||||
|
||||
// Act
|
||||
var result = FacetAdmissionValidator.IsFacetValidationRequired(annotations);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expected, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsFacetValidationRequired_NullAnnotations_ReturnsFalse()
|
||||
{
|
||||
// Act
|
||||
var result = FacetAdmissionValidator.IsFacetValidationRequired(null);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsFacetValidationRequired_MissingAnnotation_ReturnsFalse()
|
||||
{
|
||||
// Arrange
|
||||
var annotations = new Dictionary<string, string>
|
||||
{
|
||||
["other-annotation"] = "true"
|
||||
};
|
||||
|
||||
// Act
|
||||
var result = FacetAdmissionValidator.IsFacetValidationRequired(annotations);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
private static FacetSeal CreateTestSeal(string imageDigest, string? root = null)
|
||||
{
|
||||
return new FacetSeal
|
||||
{
|
||||
ImageDigest = imageDigest,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
CombinedMerkleRoot = root ?? "test-root-hash",
|
||||
Facets = ImmutableArray<FacetEntry>.Empty
|
||||
};
|
||||
}
|
||||
|
||||
private static FacetDriftReport CreateDriftReport(QuotaVerdict verdict, int changedFiles)
|
||||
{
|
||||
// Create a facet drift with the specified changed files count
|
||||
var addedFiles = changedFiles > 0
|
||||
? Enumerable.Range(0, changedFiles)
|
||||
.Select(i => new FacetFileEntry($"/added/{i}", $"sha256:hash{i}", 1024, null))
|
||||
.ToImmutableArray()
|
||||
: ImmutableArray<FacetFileEntry>.Empty;
|
||||
|
||||
var facetDrifts = changedFiles > 0
|
||||
? ImmutableArray.Create(new FacetDrift
|
||||
{
|
||||
FacetId = "test-facet",
|
||||
BaselineFileCount = 10,
|
||||
Added = addedFiles,
|
||||
Removed = ImmutableArray<FacetFileEntry>.Empty,
|
||||
Modified = ImmutableArray<FacetFileModification>.Empty,
|
||||
DriftScore = changedFiles * 10m,
|
||||
QuotaVerdict = verdict
|
||||
})
|
||||
: ImmutableArray<FacetDrift>.Empty;
|
||||
|
||||
return new FacetDriftReport
|
||||
{
|
||||
ImageDigest = "sha256:abc123",
|
||||
BaselineSealId = "baseline",
|
||||
AnalyzedAt = DateTimeOffset.UtcNow,
|
||||
OverallVerdict = verdict,
|
||||
FacetDrifts = facetDrifts
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,6 @@
|
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xunit.runner.visualstudio" >
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Moq" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
Reference in New Issue
Block a user