up
Some checks failed
Docs CI / lint-and-preview (push) Has been cancelled
AOC Guard CI / aoc-guard (push) Has been cancelled
AOC Guard CI / aoc-verify (push) Has been cancelled
Concelier Attestation Tests / attestation-tests (push) Has been cancelled
Export Center CI / export-ci (push) Has been cancelled
Notify Smoke Test / Notify Unit Tests (push) Has been cancelled
Notify Smoke Test / Notifier Service Tests (push) Has been cancelled
Notify Smoke Test / Notification Smoke Test (push) Has been cancelled
Policy Lint & Smoke / policy-lint (push) Has been cancelled
Scanner Analyzers / Discover Analyzers (push) Has been cancelled
Scanner Analyzers / Build Analyzers (push) Has been cancelled
Scanner Analyzers / Test Language Analyzers (push) Has been cancelled
Scanner Analyzers / Validate Test Fixtures (push) Has been cancelled
Scanner Analyzers / Verify Deterministic Output (push) Has been cancelled
Signals CI & Image / signals-ci (push) Has been cancelled
Signals Reachability Scoring & Events / reachability-smoke (push) Has been cancelled
Signals Reachability Scoring & Events / sign-and-upload (push) Has been cancelled

This commit is contained in:
StellaOps Bot
2025-12-13 00:20:26 +02:00
parent e1f1bef4c1
commit 564df71bfb
2376 changed files with 334389 additions and 328032 deletions

View File

@@ -1,140 +1,140 @@
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StellaOps.Scheduler.Models;
using StellaOps.Scheduler.WebService.GraphJobs;
using StellaOps.Scheduler.WebService.Options;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class CartographerWebhookClientTests
{
[Fact]
public async Task NotifyAsync_PostsPayload_WhenEnabled()
{
var handler = new RecordingHandler();
var httpClient = new HttpClient(handler);
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerCartographerOptions
{
Webhook =
{
Enabled = true,
Endpoint = "https://cartographer.local/hooks/graph-completed",
ApiKeyHeader = "X-Api-Key",
ApiKey = "secret"
}
});
using var loggerFactory = LoggerFactory.Create(builder => builder.AddDebug());
var client = new CartographerWebhookClient(httpClient, new OptionsMonitorStub<SchedulerCartographerOptions>(options), loggerFactory.CreateLogger<CartographerWebhookClient>());
var job = new GraphBuildJob(
id: "gbj_test",
tenantId: "tenant-alpha",
sbomId: "sbom",
sbomVersionId: "sbom_v1",
sbomDigest: "sha256:" + new string('a', 64),
status: GraphJobStatus.Completed,
trigger: GraphBuildJobTrigger.Backfill,
createdAt: DateTimeOffset.UtcNow,
graphSnapshotId: "snap",
attempts: 1,
cartographerJobId: "carto-123",
correlationId: "corr-1",
startedAt: null,
completedAt: DateTimeOffset.UtcNow,
error: null,
metadata: Array.Empty<KeyValuePair<string, string>>());
var notification = new GraphJobCompletionNotification(
job.TenantId,
GraphJobQueryType.Build,
GraphJobStatus.Completed,
DateTimeOffset.UtcNow,
GraphJobResponse.From(job),
"oras://snap/result",
"corr-1",
null);
await client.NotifyAsync(notification, CancellationToken.None);
Assert.NotNull(handler.LastRequest);
Assert.Equal("https://cartographer.local/hooks/graph-completed", handler.LastRequest.RequestUri!.ToString());
Assert.True(handler.LastRequest.Headers.TryGetValues("X-Api-Key", out var values) && values!.Single() == "secret");
var json = JsonSerializer.Deserialize<JsonElement>(handler.LastPayload!);
Assert.Equal("gbj_test", json.GetProperty("jobId").GetString());
Assert.Equal("tenant-alpha", json.GetProperty("tenantId").GetString());
}
[Fact]
public async Task NotifyAsync_Skips_WhenDisabled()
{
var handler = new RecordingHandler();
var httpClient = new HttpClient(handler);
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerCartographerOptions());
using var loggerFactory = LoggerFactory.Create(builder => builder.AddDebug());
var client = new CartographerWebhookClient(httpClient, new OptionsMonitorStub<SchedulerCartographerOptions>(options), loggerFactory.CreateLogger<CartographerWebhookClient>());
var job = new GraphOverlayJob(
id: "goj-test",
tenantId: "tenant-alpha",
graphSnapshotId: "snap",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@1",
status: GraphJobStatus.Completed,
trigger: GraphOverlayJobTrigger.Manual,
createdAt: DateTimeOffset.UtcNow,
subjects: Array.Empty<string>(),
attempts: 1,
correlationId: null,
startedAt: null,
completedAt: DateTimeOffset.UtcNow,
error: null,
metadata: Array.Empty<KeyValuePair<string, string>>());
var notification = new GraphJobCompletionNotification(
job.TenantId,
GraphJobQueryType.Overlay,
GraphJobStatus.Completed,
DateTimeOffset.UtcNow,
GraphJobResponse.From(job),
null,
null,
null);
await client.NotifyAsync(notification, CancellationToken.None);
Assert.Null(handler.LastRequest);
}
private sealed class RecordingHandler : HttpMessageHandler
{
public HttpRequestMessage? LastRequest { get; private set; }
public string? LastPayload { get; private set; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
LastRequest = request;
LastPayload = request.Content is null ? null : request.Content.ReadAsStringAsync(cancellationToken).Result;
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
}
}
private sealed class OptionsMonitorStub<T> : IOptionsMonitor<T> where T : class
{
private readonly IOptions<T> _options;
public OptionsMonitorStub(IOptions<T> options)
{
_options = options;
}
public T CurrentValue => _options.Value;
public T Get(string? name) => _options.Value;
public IDisposable? OnChange(Action<T, string?> listener) => null;
}
}
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StellaOps.Scheduler.Models;
using StellaOps.Scheduler.WebService.GraphJobs;
using StellaOps.Scheduler.WebService.Options;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class CartographerWebhookClientTests
{
[Fact]
public async Task NotifyAsync_PostsPayload_WhenEnabled()
{
var handler = new RecordingHandler();
var httpClient = new HttpClient(handler);
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerCartographerOptions
{
Webhook =
{
Enabled = true,
Endpoint = "https://cartographer.local/hooks/graph-completed",
ApiKeyHeader = "X-Api-Key",
ApiKey = "secret"
}
});
using var loggerFactory = LoggerFactory.Create(builder => builder.AddDebug());
var client = new CartographerWebhookClient(httpClient, new OptionsMonitorStub<SchedulerCartographerOptions>(options), loggerFactory.CreateLogger<CartographerWebhookClient>());
var job = new GraphBuildJob(
id: "gbj_test",
tenantId: "tenant-alpha",
sbomId: "sbom",
sbomVersionId: "sbom_v1",
sbomDigest: "sha256:" + new string('a', 64),
status: GraphJobStatus.Completed,
trigger: GraphBuildJobTrigger.Backfill,
createdAt: DateTimeOffset.UtcNow,
graphSnapshotId: "snap",
attempts: 1,
cartographerJobId: "carto-123",
correlationId: "corr-1",
startedAt: null,
completedAt: DateTimeOffset.UtcNow,
error: null,
metadata: Array.Empty<KeyValuePair<string, string>>());
var notification = new GraphJobCompletionNotification(
job.TenantId,
GraphJobQueryType.Build,
GraphJobStatus.Completed,
DateTimeOffset.UtcNow,
GraphJobResponse.From(job),
"oras://snap/result",
"corr-1",
null);
await client.NotifyAsync(notification, CancellationToken.None);
Assert.NotNull(handler.LastRequest);
Assert.Equal("https://cartographer.local/hooks/graph-completed", handler.LastRequest.RequestUri!.ToString());
Assert.True(handler.LastRequest.Headers.TryGetValues("X-Api-Key", out var values) && values!.Single() == "secret");
var json = JsonSerializer.Deserialize<JsonElement>(handler.LastPayload!);
Assert.Equal("gbj_test", json.GetProperty("jobId").GetString());
Assert.Equal("tenant-alpha", json.GetProperty("tenantId").GetString());
}
[Fact]
public async Task NotifyAsync_Skips_WhenDisabled()
{
var handler = new RecordingHandler();
var httpClient = new HttpClient(handler);
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerCartographerOptions());
using var loggerFactory = LoggerFactory.Create(builder => builder.AddDebug());
var client = new CartographerWebhookClient(httpClient, new OptionsMonitorStub<SchedulerCartographerOptions>(options), loggerFactory.CreateLogger<CartographerWebhookClient>());
var job = new GraphOverlayJob(
id: "goj-test",
tenantId: "tenant-alpha",
graphSnapshotId: "snap",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@1",
status: GraphJobStatus.Completed,
trigger: GraphOverlayJobTrigger.Manual,
createdAt: DateTimeOffset.UtcNow,
subjects: Array.Empty<string>(),
attempts: 1,
correlationId: null,
startedAt: null,
completedAt: DateTimeOffset.UtcNow,
error: null,
metadata: Array.Empty<KeyValuePair<string, string>>());
var notification = new GraphJobCompletionNotification(
job.TenantId,
GraphJobQueryType.Overlay,
GraphJobStatus.Completed,
DateTimeOffset.UtcNow,
GraphJobResponse.From(job),
null,
null,
null);
await client.NotifyAsync(notification, CancellationToken.None);
Assert.Null(handler.LastRequest);
}
private sealed class RecordingHandler : HttpMessageHandler
{
public HttpRequestMessage? LastRequest { get; private set; }
public string? LastPayload { get; private set; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
LastRequest = request;
LastPayload = request.Content is null ? null : request.Content.ReadAsStringAsync(cancellationToken).Result;
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
}
}
private sealed class OptionsMonitorStub<T> : IOptionsMonitor<T> where T : class
{
private readonly IOptions<T> _options;
public OptionsMonitorStub(IOptions<T> options)
{
_options = options;
}
public T CurrentValue => _options.Value;
public T Get(string? name) => _options.Value;
public IDisposable? OnChange(Action<T, string?> listener) => null;
}
}

View File

@@ -1,6 +1,6 @@
global using System.Net.Http.Json;
global using System.Text.Json;
global using System.Text.Json.Serialization;
global using System.Threading.Tasks;
global using Microsoft.AspNetCore.Mvc.Testing;
global using Xunit;
global using System.Net.Http.Json;
global using System.Text.Json;
global using System.Text.Json.Serialization;
global using System.Threading.Tasks;
global using Microsoft.AspNetCore.Mvc.Testing;
global using Xunit;

View File

@@ -1,110 +1,110 @@
using StellaOps.Auth.Abstractions;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class GraphJobEndpointTests : IClassFixture<SchedulerWebApplicationFactory>
{
private readonly SchedulerWebApplicationFactory _factory;
public GraphJobEndpointTests(SchedulerWebApplicationFactory factory)
{
_factory = factory;
}
[Fact]
public async Task CreateGraphBuildJob_RequiresGraphWriteScope()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-alpha");
var response = await client.PostAsJsonAsync("/graphs/build", new
{
sbomId = "sbom-test",
sbomVersionId = "sbom-ver",
sbomDigest = "sha256:" + new string('a', 64)
});
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task CreateGraphBuildJob_AndList()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-alpha");
client.DefaultRequestHeaders.Add("X-Scopes", string.Join(' ', StellaOpsScopes.GraphWrite, StellaOpsScopes.GraphRead));
var createResponse = await client.PostAsJsonAsync("/graphs/build", new
{
sbomId = "sbom-alpha",
sbomVersionId = "sbom-alpha-v1",
sbomDigest = "sha256:" + new string('b', 64),
metadata = new { source = "test" }
});
createResponse.EnsureSuccessStatusCode();
var listResponse = await client.GetAsync("/graphs/jobs");
listResponse.EnsureSuccessStatusCode();
var json = await listResponse.Content.ReadAsStringAsync();
using var document = JsonDocument.Parse(json);
var root = document.RootElement;
Assert.True(root.TryGetProperty("jobs", out var jobs));
Assert.True(jobs.GetArrayLength() >= 1);
var first = jobs[0];
Assert.Equal("build", first.GetProperty("kind").GetString());
Assert.Equal("tenant-alpha", first.GetProperty("tenantId").GetString());
Assert.Equal("pending", first.GetProperty("status").GetString());
}
[Fact]
public async Task CompleteOverlayJob_UpdatesStatusAndMetrics()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-bravo");
client.DefaultRequestHeaders.Add("X-Scopes", string.Join(' ', StellaOpsScopes.GraphWrite, StellaOpsScopes.GraphRead));
var createOverlay = await client.PostAsJsonAsync("/graphs/overlays", new
{
graphSnapshotId = "graph_snap_20251026",
overlayKind = "policy",
overlayKey = "policy@2025-10-01",
subjects = new[] { "artifact/service-api" }
});
createOverlay.EnsureSuccessStatusCode();
var createdJson = await createOverlay.Content.ReadAsStringAsync();
using var createdDoc = JsonDocument.Parse(createdJson);
var jobId = createdDoc.RootElement.GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(jobId));
var completeResponse = await client.PostAsJsonAsync("/graphs/hooks/completed", new
{
jobId = jobId,
jobType = "Overlay",
status = "Completed",
occurredAt = DateTimeOffset.UtcNow,
correlationId = "corr-123",
resultUri = "oras://cartographer/snapshots/graph_snap_20251026"
});
completeResponse.EnsureSuccessStatusCode();
var completedJson = await completeResponse.Content.ReadAsStringAsync();
using var completedDoc = JsonDocument.Parse(completedJson);
Assert.Equal("completed", completedDoc.RootElement.GetProperty("status").GetString());
var metricsResponse = await client.GetAsync("/graphs/overlays/lag");
metricsResponse.EnsureSuccessStatusCode();
var metricsJson = await metricsResponse.Content.ReadAsStringAsync();
using var metricsDoc = JsonDocument.Parse(metricsJson);
var metricsRoot = metricsDoc.RootElement;
Assert.Equal("tenant-bravo", metricsRoot.GetProperty("tenantId").GetString());
Assert.True(metricsRoot.GetProperty("completed").GetInt32() >= 1);
var recent = metricsRoot.GetProperty("recentCompleted");
Assert.True(recent.GetArrayLength() >= 1);
var entry = recent[0];
Assert.Equal(jobId, entry.GetProperty("jobId").GetString());
Assert.Equal("corr-123", entry.GetProperty("correlationId").GetString());
}
}
using StellaOps.Auth.Abstractions;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class GraphJobEndpointTests : IClassFixture<SchedulerWebApplicationFactory>
{
private readonly SchedulerWebApplicationFactory _factory;
public GraphJobEndpointTests(SchedulerWebApplicationFactory factory)
{
_factory = factory;
}
[Fact]
public async Task CreateGraphBuildJob_RequiresGraphWriteScope()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-alpha");
var response = await client.PostAsJsonAsync("/graphs/build", new
{
sbomId = "sbom-test",
sbomVersionId = "sbom-ver",
sbomDigest = "sha256:" + new string('a', 64)
});
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task CreateGraphBuildJob_AndList()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-alpha");
client.DefaultRequestHeaders.Add("X-Scopes", string.Join(' ', StellaOpsScopes.GraphWrite, StellaOpsScopes.GraphRead));
var createResponse = await client.PostAsJsonAsync("/graphs/build", new
{
sbomId = "sbom-alpha",
sbomVersionId = "sbom-alpha-v1",
sbomDigest = "sha256:" + new string('b', 64),
metadata = new { source = "test" }
});
createResponse.EnsureSuccessStatusCode();
var listResponse = await client.GetAsync("/graphs/jobs");
listResponse.EnsureSuccessStatusCode();
var json = await listResponse.Content.ReadAsStringAsync();
using var document = JsonDocument.Parse(json);
var root = document.RootElement;
Assert.True(root.TryGetProperty("jobs", out var jobs));
Assert.True(jobs.GetArrayLength() >= 1);
var first = jobs[0];
Assert.Equal("build", first.GetProperty("kind").GetString());
Assert.Equal("tenant-alpha", first.GetProperty("tenantId").GetString());
Assert.Equal("pending", first.GetProperty("status").GetString());
}
[Fact]
public async Task CompleteOverlayJob_UpdatesStatusAndMetrics()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-bravo");
client.DefaultRequestHeaders.Add("X-Scopes", string.Join(' ', StellaOpsScopes.GraphWrite, StellaOpsScopes.GraphRead));
var createOverlay = await client.PostAsJsonAsync("/graphs/overlays", new
{
graphSnapshotId = "graph_snap_20251026",
overlayKind = "policy",
overlayKey = "policy@2025-10-01",
subjects = new[] { "artifact/service-api" }
});
createOverlay.EnsureSuccessStatusCode();
var createdJson = await createOverlay.Content.ReadAsStringAsync();
using var createdDoc = JsonDocument.Parse(createdJson);
var jobId = createdDoc.RootElement.GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(jobId));
var completeResponse = await client.PostAsJsonAsync("/graphs/hooks/completed", new
{
jobId = jobId,
jobType = "Overlay",
status = "Completed",
occurredAt = DateTimeOffset.UtcNow,
correlationId = "corr-123",
resultUri = "oras://cartographer/snapshots/graph_snap_20251026"
});
completeResponse.EnsureSuccessStatusCode();
var completedJson = await completeResponse.Content.ReadAsStringAsync();
using var completedDoc = JsonDocument.Parse(completedJson);
Assert.Equal("completed", completedDoc.RootElement.GetProperty("status").GetString());
var metricsResponse = await client.GetAsync("/graphs/overlays/lag");
metricsResponse.EnsureSuccessStatusCode();
var metricsJson = await metricsResponse.Content.ReadAsStringAsync();
using var metricsDoc = JsonDocument.Parse(metricsJson);
var metricsRoot = metricsDoc.RootElement;
Assert.Equal("tenant-bravo", metricsRoot.GetProperty("tenantId").GetString());
Assert.True(metricsRoot.GetProperty("completed").GetInt32() >= 1);
var recent = metricsRoot.GetProperty("recentCompleted");
Assert.True(recent.GetArrayLength() >= 1);
var entry = recent[0];
Assert.Equal(jobId, entry.GetProperty("jobId").GetString());
Assert.Equal("corr-123", entry.GetProperty("correlationId").GetString());
}
}

View File

@@ -6,12 +6,12 @@ using StellaOps.Scheduler.WebService.GraphJobs;
using StellaOps.Scheduler.WebService.GraphJobs.Events;
using StellaOps.Scheduler.WebService.Options;
using StackExchange.Redis;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class GraphJobEventPublisherTests
{
[Fact]
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class GraphJobEventPublisherTests
{
[Fact]
public async Task PublishAsync_LogsEvent_WhenDriverUnsupported()
{
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerEventsOptions
@@ -25,99 +25,99 @@ public sealed class GraphJobEventPublisherTests
var loggerProvider = new ListLoggerProvider();
using var loggerFactory = LoggerFactory.Create(builder => builder.AddProvider(loggerProvider));
var publisher = new GraphJobEventPublisher(new OptionsMonitorStub<SchedulerEventsOptions>(options), new ThrowingRedisConnectionFactory(), loggerFactory.CreateLogger<GraphJobEventPublisher>());
var buildJob = new GraphBuildJob(
id: "gbj_test",
tenantId: "tenant-alpha",
sbomId: "sbom",
sbomVersionId: "sbom_v1",
sbomDigest: "sha256:" + new string('a', 64),
status: GraphJobStatus.Completed,
trigger: GraphBuildJobTrigger.SbomVersion,
createdAt: DateTimeOffset.UtcNow,
graphSnapshotId: "graph_snap",
attempts: 1,
cartographerJobId: "carto",
correlationId: "corr",
startedAt: DateTimeOffset.UtcNow.AddSeconds(-30),
completedAt: DateTimeOffset.UtcNow,
error: null,
metadata: Array.Empty<KeyValuePair<string, string>>());
var notification = new GraphJobCompletionNotification(
buildJob.TenantId,
GraphJobQueryType.Build,
GraphJobStatus.Completed,
DateTimeOffset.UtcNow,
GraphJobResponse.From(buildJob),
"oras://result",
"corr",
null);
await publisher.PublishAsync(notification, CancellationToken.None);
var buildJob = new GraphBuildJob(
id: "gbj_test",
tenantId: "tenant-alpha",
sbomId: "sbom",
sbomVersionId: "sbom_v1",
sbomDigest: "sha256:" + new string('a', 64),
status: GraphJobStatus.Completed,
trigger: GraphBuildJobTrigger.SbomVersion,
createdAt: DateTimeOffset.UtcNow,
graphSnapshotId: "graph_snap",
attempts: 1,
cartographerJobId: "carto",
correlationId: "corr",
startedAt: DateTimeOffset.UtcNow.AddSeconds(-30),
completedAt: DateTimeOffset.UtcNow,
error: null,
metadata: Array.Empty<KeyValuePair<string, string>>());
var notification = new GraphJobCompletionNotification(
buildJob.TenantId,
GraphJobQueryType.Build,
GraphJobStatus.Completed,
DateTimeOffset.UtcNow,
GraphJobResponse.From(buildJob),
"oras://result",
"corr",
null);
await publisher.PublishAsync(notification, CancellationToken.None);
Assert.Contains(loggerProvider.Messages, message => message.Contains("unsupported driver", StringComparison.OrdinalIgnoreCase));
var eventPayload = loggerProvider.Messages.FirstOrDefault(message => message.Contains("\"kind\":\"scheduler.graph.job.completed\"", StringComparison.Ordinal));
Assert.NotNull(eventPayload);
Assert.Contains("\"tenant\":\"tenant-alpha\"", eventPayload);
Assert.Contains("\"resultUri\":\"oras://result\"", eventPayload);
}
[Fact]
}
[Fact]
public async Task PublishAsync_Suppressed_WhenDisabled()
{
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerEventsOptions());
var loggerProvider = new ListLoggerProvider();
using var loggerFactory = LoggerFactory.Create(builder => builder.AddProvider(loggerProvider));
var publisher = new GraphJobEventPublisher(new OptionsMonitorStub<SchedulerEventsOptions>(options), new ThrowingRedisConnectionFactory(), loggerFactory.CreateLogger<GraphJobEventPublisher>());
var overlayJob = new GraphOverlayJob(
id: "goj_test",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap",
buildJobId: null,
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@1",
subjects: Array.Empty<string>(),
status: GraphJobStatus.Completed,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: DateTimeOffset.UtcNow,
attempts: 1,
correlationId: null,
startedAt: DateTimeOffset.UtcNow.AddSeconds(-10),
completedAt: DateTimeOffset.UtcNow,
error: null,
metadata: Array.Empty<KeyValuePair<string, string>>());
var notification = new GraphJobCompletionNotification(
overlayJob.TenantId,
GraphJobQueryType.Overlay,
GraphJobStatus.Completed,
DateTimeOffset.UtcNow,
GraphJobResponse.From(overlayJob),
null,
null,
null);
await publisher.PublishAsync(notification, CancellationToken.None);
var overlayJob = new GraphOverlayJob(
id: "goj_test",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap",
buildJobId: null,
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@1",
subjects: Array.Empty<string>(),
status: GraphJobStatus.Completed,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: DateTimeOffset.UtcNow,
attempts: 1,
correlationId: null,
startedAt: DateTimeOffset.UtcNow.AddSeconds(-10),
completedAt: DateTimeOffset.UtcNow,
error: null,
metadata: Array.Empty<KeyValuePair<string, string>>());
var notification = new GraphJobCompletionNotification(
overlayJob.TenantId,
GraphJobQueryType.Overlay,
GraphJobStatus.Completed,
DateTimeOffset.UtcNow,
GraphJobResponse.From(overlayJob),
null,
null,
null);
await publisher.PublishAsync(notification, CancellationToken.None);
Assert.DoesNotContain(loggerProvider.Messages, message => message.Contains(GraphJobEventKinds.GraphJobCompleted, StringComparison.Ordinal));
}
}
private sealed class OptionsMonitorStub<T> : IOptionsMonitor<T> where T : class
{
private readonly IOptions<T> _options;
public OptionsMonitorStub(IOptions<T> options)
{
_options = options;
}
public T CurrentValue => _options.Value;
public T Get(string? name) => _options.Value;
public IDisposable? OnChange(Action<T, string?> listener) => null;
public OptionsMonitorStub(IOptions<T> options)
{
_options = options;
}
public T CurrentValue => _options.Value;
public T Get(string? name) => _options.Value;
public IDisposable? OnChange(Action<T, string?> listener) => null;
}
private sealed class ThrowingRedisConnectionFactory : IRedisConnectionFactory
@@ -125,39 +125,39 @@ public sealed class GraphJobEventPublisherTests
public Task<IConnectionMultiplexer> ConnectAsync(ConfigurationOptions options, CancellationToken cancellationToken)
=> throw new InvalidOperationException("Redis connection should not be established in this test.");
}
private sealed class ListLoggerProvider : ILoggerProvider
{
private readonly ListLogger _logger = new();
public IList<string> Messages => _logger.Messages;
public ILogger CreateLogger(string categoryName) => _logger;
public void Dispose()
{
}
private sealed class ListLogger : ILogger
{
public IList<string> Messages { get; } = new List<string>();
public IDisposable BeginScope<TState>(TState state) where TState : notnull => NullDisposable.Instance;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
Messages.Add(formatter(state, exception));
}
private sealed class NullDisposable : IDisposable
{
public static readonly NullDisposable Instance = new();
public void Dispose()
{
}
}
}
}
}
private sealed class ListLoggerProvider : ILoggerProvider
{
private readonly ListLogger _logger = new();
public IList<string> Messages => _logger.Messages;
public ILogger CreateLogger(string categoryName) => _logger;
public void Dispose()
{
}
private sealed class ListLogger : ILogger
{
public IList<string> Messages { get; } = new List<string>();
public IDisposable BeginScope<TState>(TState state) where TState : notnull => NullDisposable.Instance;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
Messages.Add(formatter(state, exception));
}
private sealed class NullDisposable : IDisposable
{
public static readonly NullDisposable Instance = new();
public void Dispose()
{
}
}
}
}
}

View File

@@ -1,218 +1,218 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using StellaOps.Scheduler.Models;
using StellaOps.Scheduler.WebService.GraphJobs;
using Xunit;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class GraphJobServiceTests
{
private static readonly DateTimeOffset FixedTime = new(2025, 11, 4, 12, 0, 0, TimeSpan.Zero);
[Fact]
public async Task CompleteBuildJob_PersistsMetadataAndPublishesOnce()
{
var store = new TrackingGraphJobStore();
var initial = CreateBuildJob();
await store.AddAsync(initial, CancellationToken.None);
var clock = new FixedClock(FixedTime);
var publisher = new RecordingPublisher();
var webhook = new RecordingWebhookClient();
var service = new GraphJobService(store, clock, publisher, webhook);
var request = new GraphJobCompletionRequest
{
JobId = initial.Id,
JobType = GraphJobQueryType.Build,
Status = GraphJobStatus.Completed,
OccurredAt = FixedTime,
GraphSnapshotId = "graph_snap_final ",
ResultUri = "oras://cartographer/bundle ",
CorrelationId = "corr-123 "
};
var response = await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
Assert.Equal(GraphJobStatus.Completed, response.Status);
Assert.Equal(1, store.BuildUpdateCount);
Assert.Single(publisher.Notifications);
Assert.Single(webhook.Notifications);
var stored = await store.GetBuildJobAsync(initial.TenantId, initial.Id, CancellationToken.None);
Assert.NotNull(stored);
Assert.Equal("graph_snap_final", stored!.GraphSnapshotId);
Assert.Equal("corr-123", stored.CorrelationId);
Assert.True(stored.Metadata.TryGetValue("resultUri", out var resultUri));
Assert.Equal("oras://cartographer/bundle", resultUri);
}
[Fact]
public async Task CompleteBuildJob_IsIdempotentWhenAlreadyCompleted()
{
var store = new TrackingGraphJobStore();
var initial = CreateBuildJob();
await store.AddAsync(initial, CancellationToken.None);
var clock = new FixedClock(FixedTime);
var publisher = new RecordingPublisher();
var webhook = new RecordingWebhookClient();
var service = new GraphJobService(store, clock, publisher, webhook);
var request = new GraphJobCompletionRequest
{
JobId = initial.Id,
JobType = GraphJobQueryType.Build,
Status = GraphJobStatus.Completed,
OccurredAt = FixedTime,
GraphSnapshotId = "graph_snap_final",
ResultUri = "oras://cartographer/bundle",
CorrelationId = "corr-123"
};
await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
var updateCountAfterFirst = store.BuildUpdateCount;
var secondResponse = await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
Assert.Equal(GraphJobStatus.Completed, secondResponse.Status);
Assert.Equal(updateCountAfterFirst, store.BuildUpdateCount);
Assert.Single(publisher.Notifications);
Assert.Single(webhook.Notifications);
}
[Fact]
public async Task CompleteBuildJob_UpdatesResultUriWithoutReemittingEvent()
{
var store = new TrackingGraphJobStore();
var initial = CreateBuildJob();
await store.AddAsync(initial, CancellationToken.None);
var clock = new FixedClock(FixedTime);
var publisher = new RecordingPublisher();
var webhook = new RecordingWebhookClient();
var service = new GraphJobService(store, clock, publisher, webhook);
var firstRequest = new GraphJobCompletionRequest
{
JobId = initial.Id,
JobType = GraphJobQueryType.Build,
Status = GraphJobStatus.Completed,
OccurredAt = FixedTime,
GraphSnapshotId = "graph_snap_final",
ResultUri = null,
CorrelationId = "corr-123"
};
await service.CompleteJobAsync(initial.TenantId, firstRequest, CancellationToken.None);
Assert.Equal(1, store.BuildUpdateCount);
Assert.Single(publisher.Notifications);
Assert.Single(webhook.Notifications);
var secondRequest = firstRequest with
{
ResultUri = "oras://cartographer/bundle-v2",
OccurredAt = FixedTime.AddSeconds(30)
};
var response = await service.CompleteJobAsync(initial.TenantId, secondRequest, CancellationToken.None);
Assert.Equal(GraphJobStatus.Completed, response.Status);
Assert.Equal(2, store.BuildUpdateCount);
Assert.Single(publisher.Notifications);
Assert.Single(webhook.Notifications);
var stored = await store.GetBuildJobAsync(initial.TenantId, initial.Id, CancellationToken.None);
Assert.NotNull(stored);
Assert.True(stored!.Metadata.TryGetValue("resultUri", out var resultUri));
Assert.Equal("oras://cartographer/bundle-v2", resultUri);
}
private static GraphBuildJob CreateBuildJob()
{
var digest = "sha256:" + new string('a', 64);
return new GraphBuildJob(
id: "gbj_test",
tenantId: "tenant-alpha",
sbomId: "sbom-alpha",
sbomVersionId: "sbom-alpha-v1",
sbomDigest: digest,
status: GraphJobStatus.Pending,
trigger: GraphBuildJobTrigger.SbomVersion,
createdAt: FixedTime,
metadata: null);
}
private sealed class TrackingGraphJobStore : IGraphJobStore
{
private readonly InMemoryGraphJobStore _inner = new();
public int BuildUpdateCount { get; private set; }
public int OverlayUpdateCount { get; private set; }
public ValueTask<GraphBuildJob> AddAsync(GraphBuildJob job, CancellationToken cancellationToken)
=> _inner.AddAsync(job, cancellationToken);
public ValueTask<GraphOverlayJob> AddAsync(GraphOverlayJob job, CancellationToken cancellationToken)
=> _inner.AddAsync(job, cancellationToken);
public ValueTask<GraphJobCollection> GetJobsAsync(string tenantId, GraphJobQuery query, CancellationToken cancellationToken)
=> _inner.GetJobsAsync(tenantId, query, cancellationToken);
public ValueTask<GraphBuildJob?> GetBuildJobAsync(string tenantId, string jobId, CancellationToken cancellationToken)
=> _inner.GetBuildJobAsync(tenantId, jobId, cancellationToken);
public ValueTask<GraphOverlayJob?> GetOverlayJobAsync(string tenantId, string jobId, CancellationToken cancellationToken)
=> _inner.GetOverlayJobAsync(tenantId, jobId, cancellationToken);
public async ValueTask<GraphJobUpdateResult<GraphBuildJob>> UpdateAsync(GraphBuildJob job, GraphJobStatus expectedStatus, CancellationToken cancellationToken)
{
BuildUpdateCount++;
return await _inner.UpdateAsync(job, expectedStatus, cancellationToken);
}
public async ValueTask<GraphJobUpdateResult<GraphOverlayJob>> UpdateAsync(GraphOverlayJob job, GraphJobStatus expectedStatus, CancellationToken cancellationToken)
{
OverlayUpdateCount++;
return await _inner.UpdateAsync(job, expectedStatus, cancellationToken);
}
public ValueTask<IReadOnlyCollection<GraphOverlayJob>> GetOverlayJobsAsync(string tenantId, CancellationToken cancellationToken)
=> _inner.GetOverlayJobsAsync(tenantId, cancellationToken);
}
private sealed class RecordingPublisher : IGraphJobCompletionPublisher
{
public List<GraphJobCompletionNotification> Notifications { get; } = new();
public Task PublishAsync(GraphJobCompletionNotification notification, CancellationToken cancellationToken)
{
Notifications.Add(notification);
return Task.CompletedTask;
}
}
private sealed class RecordingWebhookClient : ICartographerWebhookClient
{
public List<GraphJobCompletionNotification> Notifications { get; } = new();
public Task NotifyAsync(GraphJobCompletionNotification notification, CancellationToken cancellationToken)
{
Notifications.Add(notification);
return Task.CompletedTask;
}
}
private sealed class FixedClock : ISystemClock
{
public FixedClock(DateTimeOffset utcNow)
{
UtcNow = utcNow;
}
public DateTimeOffset UtcNow { get; set; }
}
}
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using StellaOps.Scheduler.Models;
using StellaOps.Scheduler.WebService.GraphJobs;
using Xunit;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class GraphJobServiceTests
{
private static readonly DateTimeOffset FixedTime = new(2025, 11, 4, 12, 0, 0, TimeSpan.Zero);
[Fact]
public async Task CompleteBuildJob_PersistsMetadataAndPublishesOnce()
{
var store = new TrackingGraphJobStore();
var initial = CreateBuildJob();
await store.AddAsync(initial, CancellationToken.None);
var clock = new FixedClock(FixedTime);
var publisher = new RecordingPublisher();
var webhook = new RecordingWebhookClient();
var service = new GraphJobService(store, clock, publisher, webhook);
var request = new GraphJobCompletionRequest
{
JobId = initial.Id,
JobType = GraphJobQueryType.Build,
Status = GraphJobStatus.Completed,
OccurredAt = FixedTime,
GraphSnapshotId = "graph_snap_final ",
ResultUri = "oras://cartographer/bundle ",
CorrelationId = "corr-123 "
};
var response = await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
Assert.Equal(GraphJobStatus.Completed, response.Status);
Assert.Equal(1, store.BuildUpdateCount);
Assert.Single(publisher.Notifications);
Assert.Single(webhook.Notifications);
var stored = await store.GetBuildJobAsync(initial.TenantId, initial.Id, CancellationToken.None);
Assert.NotNull(stored);
Assert.Equal("graph_snap_final", stored!.GraphSnapshotId);
Assert.Equal("corr-123", stored.CorrelationId);
Assert.True(stored.Metadata.TryGetValue("resultUri", out var resultUri));
Assert.Equal("oras://cartographer/bundle", resultUri);
}
[Fact]
public async Task CompleteBuildJob_IsIdempotentWhenAlreadyCompleted()
{
var store = new TrackingGraphJobStore();
var initial = CreateBuildJob();
await store.AddAsync(initial, CancellationToken.None);
var clock = new FixedClock(FixedTime);
var publisher = new RecordingPublisher();
var webhook = new RecordingWebhookClient();
var service = new GraphJobService(store, clock, publisher, webhook);
var request = new GraphJobCompletionRequest
{
JobId = initial.Id,
JobType = GraphJobQueryType.Build,
Status = GraphJobStatus.Completed,
OccurredAt = FixedTime,
GraphSnapshotId = "graph_snap_final",
ResultUri = "oras://cartographer/bundle",
CorrelationId = "corr-123"
};
await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
var updateCountAfterFirst = store.BuildUpdateCount;
var secondResponse = await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
Assert.Equal(GraphJobStatus.Completed, secondResponse.Status);
Assert.Equal(updateCountAfterFirst, store.BuildUpdateCount);
Assert.Single(publisher.Notifications);
Assert.Single(webhook.Notifications);
}
[Fact]
public async Task CompleteBuildJob_UpdatesResultUriWithoutReemittingEvent()
{
var store = new TrackingGraphJobStore();
var initial = CreateBuildJob();
await store.AddAsync(initial, CancellationToken.None);
var clock = new FixedClock(FixedTime);
var publisher = new RecordingPublisher();
var webhook = new RecordingWebhookClient();
var service = new GraphJobService(store, clock, publisher, webhook);
var firstRequest = new GraphJobCompletionRequest
{
JobId = initial.Id,
JobType = GraphJobQueryType.Build,
Status = GraphJobStatus.Completed,
OccurredAt = FixedTime,
GraphSnapshotId = "graph_snap_final",
ResultUri = null,
CorrelationId = "corr-123"
};
await service.CompleteJobAsync(initial.TenantId, firstRequest, CancellationToken.None);
Assert.Equal(1, store.BuildUpdateCount);
Assert.Single(publisher.Notifications);
Assert.Single(webhook.Notifications);
var secondRequest = firstRequest with
{
ResultUri = "oras://cartographer/bundle-v2",
OccurredAt = FixedTime.AddSeconds(30)
};
var response = await service.CompleteJobAsync(initial.TenantId, secondRequest, CancellationToken.None);
Assert.Equal(GraphJobStatus.Completed, response.Status);
Assert.Equal(2, store.BuildUpdateCount);
Assert.Single(publisher.Notifications);
Assert.Single(webhook.Notifications);
var stored = await store.GetBuildJobAsync(initial.TenantId, initial.Id, CancellationToken.None);
Assert.NotNull(stored);
Assert.True(stored!.Metadata.TryGetValue("resultUri", out var resultUri));
Assert.Equal("oras://cartographer/bundle-v2", resultUri);
}
private static GraphBuildJob CreateBuildJob()
{
var digest = "sha256:" + new string('a', 64);
return new GraphBuildJob(
id: "gbj_test",
tenantId: "tenant-alpha",
sbomId: "sbom-alpha",
sbomVersionId: "sbom-alpha-v1",
sbomDigest: digest,
status: GraphJobStatus.Pending,
trigger: GraphBuildJobTrigger.SbomVersion,
createdAt: FixedTime,
metadata: null);
}
private sealed class TrackingGraphJobStore : IGraphJobStore
{
private readonly InMemoryGraphJobStore _inner = new();
public int BuildUpdateCount { get; private set; }
public int OverlayUpdateCount { get; private set; }
public ValueTask<GraphBuildJob> AddAsync(GraphBuildJob job, CancellationToken cancellationToken)
=> _inner.AddAsync(job, cancellationToken);
public ValueTask<GraphOverlayJob> AddAsync(GraphOverlayJob job, CancellationToken cancellationToken)
=> _inner.AddAsync(job, cancellationToken);
public ValueTask<GraphJobCollection> GetJobsAsync(string tenantId, GraphJobQuery query, CancellationToken cancellationToken)
=> _inner.GetJobsAsync(tenantId, query, cancellationToken);
public ValueTask<GraphBuildJob?> GetBuildJobAsync(string tenantId, string jobId, CancellationToken cancellationToken)
=> _inner.GetBuildJobAsync(tenantId, jobId, cancellationToken);
public ValueTask<GraphOverlayJob?> GetOverlayJobAsync(string tenantId, string jobId, CancellationToken cancellationToken)
=> _inner.GetOverlayJobAsync(tenantId, jobId, cancellationToken);
public async ValueTask<GraphJobUpdateResult<GraphBuildJob>> UpdateAsync(GraphBuildJob job, GraphJobStatus expectedStatus, CancellationToken cancellationToken)
{
BuildUpdateCount++;
return await _inner.UpdateAsync(job, expectedStatus, cancellationToken);
}
public async ValueTask<GraphJobUpdateResult<GraphOverlayJob>> UpdateAsync(GraphOverlayJob job, GraphJobStatus expectedStatus, CancellationToken cancellationToken)
{
OverlayUpdateCount++;
return await _inner.UpdateAsync(job, expectedStatus, cancellationToken);
}
public ValueTask<IReadOnlyCollection<GraphOverlayJob>> GetOverlayJobsAsync(string tenantId, CancellationToken cancellationToken)
=> _inner.GetOverlayJobsAsync(tenantId, cancellationToken);
}
private sealed class RecordingPublisher : IGraphJobCompletionPublisher
{
public List<GraphJobCompletionNotification> Notifications { get; } = new();
public Task PublishAsync(GraphJobCompletionNotification notification, CancellationToken cancellationToken)
{
Notifications.Add(notification);
return Task.CompletedTask;
}
}
private sealed class RecordingWebhookClient : ICartographerWebhookClient
{
public List<GraphJobCompletionNotification> Notifications { get; } = new();
public Task NotifyAsync(GraphJobCompletionNotification notification, CancellationToken cancellationToken)
{
Notifications.Add(notification);
return Task.CompletedTask;
}
}
private sealed class FixedClock : ISystemClock
{
public FixedClock(DateTimeOffset utcNow)
{
UtcNow = utcNow;
}
public DateTimeOffset UtcNow { get; set; }
}
}

View File

@@ -1,71 +1,71 @@
using System.Text.Json;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class PolicyRunEndpointTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public PolicyRunEndpointTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task CreateListGetPolicyRun()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-policy");
client.DefaultRequestHeaders.Add("X-Scopes", "policy:run");
var createResponse = await client.PostAsJsonAsync("/api/v1/scheduler/policy/runs", new
{
policyId = "P-7",
policyVersion = 4,
mode = "incremental",
priority = "normal",
metadata = new { source = "cli" },
inputs = new
{
sbomSet = new[] { "sbom:S-42", "sbom:S-99" },
advisoryCursor = "2025-10-26T13:59:00+00:00",
vexCursor = "2025-10-26T13:58:30+00:00",
environment = new { @sealed = false, exposure = "internet" },
captureExplain = true
}
});
createResponse.EnsureSuccessStatusCode();
Assert.Equal(System.Net.HttpStatusCode.Created, createResponse.StatusCode);
var created = await createResponse.Content.ReadFromJsonAsync<JsonElement>();
var runJson = created.GetProperty("run");
var runId = runJson.GetProperty("runId").GetString();
Assert.False(string.IsNullOrEmpty(runId));
Assert.Equal("queued", runJson.GetProperty("status").GetString());
Assert.Equal("P-7", runJson.GetProperty("policyId").GetString());
Assert.True(runJson.GetProperty("inputs").GetProperty("captureExplain").GetBoolean());
var listResponse = await client.GetAsync("/api/v1/scheduler/policy/runs?policyId=P-7");
listResponse.EnsureSuccessStatusCode();
var list = await listResponse.Content.ReadFromJsonAsync<JsonElement>();
var runsArray = list.GetProperty("runs");
Assert.True(runsArray.GetArrayLength() >= 1);
var getResponse = await client.GetAsync($"/api/v1/scheduler/policy/runs/{runId}");
getResponse.EnsureSuccessStatusCode();
var retrieved = await getResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.Equal(runId, retrieved.GetProperty("run").GetProperty("runId").GetString());
}
[Fact]
public async Task MissingScopeReturnsForbidden()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-policy");
var response = await client.GetAsync("/api/v1/scheduler/policy/runs");
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
}
}
using System.Text.Json;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class PolicyRunEndpointTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public PolicyRunEndpointTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task CreateListGetPolicyRun()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-policy");
client.DefaultRequestHeaders.Add("X-Scopes", "policy:run");
var createResponse = await client.PostAsJsonAsync("/api/v1/scheduler/policy/runs", new
{
policyId = "P-7",
policyVersion = 4,
mode = "incremental",
priority = "normal",
metadata = new { source = "cli" },
inputs = new
{
sbomSet = new[] { "sbom:S-42", "sbom:S-99" },
advisoryCursor = "2025-10-26T13:59:00+00:00",
vexCursor = "2025-10-26T13:58:30+00:00",
environment = new { @sealed = false, exposure = "internet" },
captureExplain = true
}
});
createResponse.EnsureSuccessStatusCode();
Assert.Equal(System.Net.HttpStatusCode.Created, createResponse.StatusCode);
var created = await createResponse.Content.ReadFromJsonAsync<JsonElement>();
var runJson = created.GetProperty("run");
var runId = runJson.GetProperty("runId").GetString();
Assert.False(string.IsNullOrEmpty(runId));
Assert.Equal("queued", runJson.GetProperty("status").GetString());
Assert.Equal("P-7", runJson.GetProperty("policyId").GetString());
Assert.True(runJson.GetProperty("inputs").GetProperty("captureExplain").GetBoolean());
var listResponse = await client.GetAsync("/api/v1/scheduler/policy/runs?policyId=P-7");
listResponse.EnsureSuccessStatusCode();
var list = await listResponse.Content.ReadFromJsonAsync<JsonElement>();
var runsArray = list.GetProperty("runs");
Assert.True(runsArray.GetArrayLength() >= 1);
var getResponse = await client.GetAsync($"/api/v1/scheduler/policy/runs/{runId}");
getResponse.EnsureSuccessStatusCode();
var retrieved = await getResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.Equal(runId, retrieved.GetProperty("run").GetProperty("runId").GetString());
}
[Fact]
public async Task MissingScopeReturnsForbidden()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-policy");
var response = await client.GetAsync("/api/v1/scheduler/policy/runs");
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
}
}

View File

@@ -2,9 +2,7 @@ using System.Net;
using System.Net.Http.Headers;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Mongo2Go;
using StellaOps.Scheduler.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StellaOps.Scheduler.WebService.PolicySimulations;
using System.Collections.Generic;
@@ -273,41 +271,6 @@ public sealed class PolicySimulationEndpointTests : IClassFixture<WebApplication
Assert.True(seenHeartbeat, "Heartbeat event was not observed.");
}
[Fact]
public async Task MongoBackedCreateSimulationPersists()
{
using var runner = MongoDbRunner.Start(additionalMongodArguments: "--quiet");
await using var factory = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureAppConfiguration((_, configuration) =>
{
configuration.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string?>("Scheduler:Storage:ConnectionString", runner.ConnectionString),
new KeyValuePair<string, string?>("Scheduler:Storage:Database", $"scheduler_web_tests_{Guid.NewGuid():N}")
});
});
});
using var client = factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-sim-mongo");
client.DefaultRequestHeaders.Add("X-Scopes", "policy:simulate");
var createResponse = await client.PostAsJsonAsync("/api/v1/scheduler/policies/simulations", new
{
policyId = "policy-mongo",
policyVersion = 11
});
createResponse.EnsureSuccessStatusCode();
var runId = (await createResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("simulation").GetProperty("runId").GetString();
Assert.False(string.IsNullOrEmpty(runId));
var fetched = await client.GetAsync($"/api/v1/scheduler/policies/simulations/{runId}");
fetched.EnsureSuccessStatusCode();
var payload = await fetched.Content.ReadFromJsonAsync<JsonElement>();
Assert.Equal(runId, payload.GetProperty("simulation").GetProperty("runId").GetString());
}
private sealed class StubPolicySimulationMetricsProvider : IPolicySimulationMetricsProvider, IPolicySimulationMetricsRecorder
{
public PolicySimulationMetricsResponse Response { get; set; } = new(

View File

@@ -6,7 +6,6 @@ using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Driver;
using StellaOps.Scheduler.Models;
using StellaOps.Scheduler.Storage.Postgres.Repositories;
using StellaOps.Scheduler.WebService.PolicySimulations;
@@ -250,7 +249,6 @@ public sealed class PolicySimulationMetricsProviderTests
public Task InsertAsync(
PolicyRunJob job,
IClientSessionHandle? session = null,
CancellationToken cancellationToken = default)
{
Jobs.Add(job);
@@ -287,7 +285,6 @@ public sealed class PolicySimulationMetricsProviderTests
IReadOnlyCollection<PolicyRunJobStatus>? statuses = null,
DateTimeOffset? queuedAfter = null,
int limit = 50,
IClientSessionHandle? session = null,
CancellationToken cancellationToken = default)
{
IEnumerable<PolicyRunJob> query = Jobs;
@@ -309,14 +306,12 @@ public sealed class PolicySimulationMetricsProviderTests
public Task<PolicyRunJob?> GetAsync(
string tenantId,
string jobId,
IClientSessionHandle? session = null,
CancellationToken cancellationToken = default)
=> Task.FromResult<PolicyRunJob?>(Jobs.FirstOrDefault(job => job.Id == jobId));
public Task<PolicyRunJob?> GetByRunIdAsync(
string tenantId,
string runId,
IClientSessionHandle? session = null,
CancellationToken cancellationToken = default)
=> Task.FromResult<PolicyRunJob?>(Jobs.FirstOrDefault(job => string.Equals(job.RunId, runId, StringComparison.Ordinal)));
@@ -325,14 +320,12 @@ public sealed class PolicySimulationMetricsProviderTests
DateTimeOffset now,
TimeSpan leaseDuration,
int maxAttempts,
IClientSessionHandle? session = null,
CancellationToken cancellationToken = default)
=> Task.FromResult<PolicyRunJob?>(null);
public Task<bool> ReplaceAsync(
PolicyRunJob job,
string? expectedLeaseOwner = null,
IClientSessionHandle? session = null,
CancellationToken cancellationToken = default)
=> Task.FromResult(true);
}

View File

@@ -1,88 +1,88 @@
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class ScheduleEndpointTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public ScheduleEndpointTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task CreateListAndRetrieveSchedule()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-schedules");
client.DefaultRequestHeaders.Add("X-Scopes", "scheduler.schedules.write scheduler.schedules.read");
var createResponse = await client.PostAsJsonAsync("/api/v1/scheduler/schedules", new
{
name = "Nightly",
cronExpression = "0 2 * * *",
timezone = "UTC",
mode = "analysis-only",
selection = new
{
scope = "all-images"
},
notify = new
{
onNewFindings = true,
minSeverity = "medium",
includeKev = true
}
});
createResponse.EnsureSuccessStatusCode();
var created = await createResponse.Content.ReadFromJsonAsync<JsonElement>();
var scheduleId = created.GetProperty("schedule").GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(scheduleId));
var listResponse = await client.GetAsync("/api/v1/scheduler/schedules");
listResponse.EnsureSuccessStatusCode();
var listJson = await listResponse.Content.ReadFromJsonAsync<JsonElement>();
var schedules = listJson.GetProperty("schedules");
Assert.True(schedules.GetArrayLength() >= 1);
var getResponse = await client.GetAsync($"/api/v1/scheduler/schedules/{scheduleId}");
getResponse.EnsureSuccessStatusCode();
var scheduleJson = await getResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.Equal("Nightly", scheduleJson.GetProperty("schedule").GetProperty("name").GetString());
}
[Fact]
public async Task PauseAndResumeSchedule()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-controls");
client.DefaultRequestHeaders.Add("X-Scopes", "scheduler.schedules.write scheduler.schedules.read");
var create = await client.PostAsJsonAsync("/api/v1/scheduler/schedules", new
{
name = "PauseResume",
cronExpression = "*/5 * * * *",
timezone = "UTC",
mode = "analysis-only",
selection = new
{
scope = "all-images"
}
});
create.EnsureSuccessStatusCode();
var created = await create.Content.ReadFromJsonAsync<JsonElement>();
var scheduleId = created.GetProperty("schedule").GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(scheduleId));
var pauseResponse = await client.PostAsync($"/api/v1/scheduler/schedules/{scheduleId}/pause", null);
pauseResponse.EnsureSuccessStatusCode();
var paused = await pauseResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.False(paused.GetProperty("schedule").GetProperty("enabled").GetBoolean());
var resumeResponse = await client.PostAsync($"/api/v1/scheduler/schedules/{scheduleId}/resume", null);
resumeResponse.EnsureSuccessStatusCode();
var resumed = await resumeResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.True(resumed.GetProperty("schedule").GetProperty("enabled").GetBoolean());
}
}
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class ScheduleEndpointTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public ScheduleEndpointTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task CreateListAndRetrieveSchedule()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-schedules");
client.DefaultRequestHeaders.Add("X-Scopes", "scheduler.schedules.write scheduler.schedules.read");
var createResponse = await client.PostAsJsonAsync("/api/v1/scheduler/schedules", new
{
name = "Nightly",
cronExpression = "0 2 * * *",
timezone = "UTC",
mode = "analysis-only",
selection = new
{
scope = "all-images"
},
notify = new
{
onNewFindings = true,
minSeverity = "medium",
includeKev = true
}
});
createResponse.EnsureSuccessStatusCode();
var created = await createResponse.Content.ReadFromJsonAsync<JsonElement>();
var scheduleId = created.GetProperty("schedule").GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(scheduleId));
var listResponse = await client.GetAsync("/api/v1/scheduler/schedules");
listResponse.EnsureSuccessStatusCode();
var listJson = await listResponse.Content.ReadFromJsonAsync<JsonElement>();
var schedules = listJson.GetProperty("schedules");
Assert.True(schedules.GetArrayLength() >= 1);
var getResponse = await client.GetAsync($"/api/v1/scheduler/schedules/{scheduleId}");
getResponse.EnsureSuccessStatusCode();
var scheduleJson = await getResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.Equal("Nightly", scheduleJson.GetProperty("schedule").GetProperty("name").GetString());
}
[Fact]
public async Task PauseAndResumeSchedule()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-controls");
client.DefaultRequestHeaders.Add("X-Scopes", "scheduler.schedules.write scheduler.schedules.read");
var create = await client.PostAsJsonAsync("/api/v1/scheduler/schedules", new
{
name = "PauseResume",
cronExpression = "*/5 * * * *",
timezone = "UTC",
mode = "analysis-only",
selection = new
{
scope = "all-images"
}
});
create.EnsureSuccessStatusCode();
var created = await create.Content.ReadFromJsonAsync<JsonElement>();
var scheduleId = created.GetProperty("schedule").GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(scheduleId));
var pauseResponse = await client.PostAsync($"/api/v1/scheduler/schedules/{scheduleId}/pause", null);
pauseResponse.EnsureSuccessStatusCode();
var paused = await pauseResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.False(paused.GetProperty("schedule").GetProperty("enabled").GetBoolean());
var resumeResponse = await client.PostAsync($"/api/v1/scheduler/schedules/{scheduleId}/resume", null);
resumeResponse.EnsureSuccessStatusCode();
var resumed = await resumeResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.True(resumed.GetProperty("schedule").GetProperty("enabled").GetBoolean());
}
}

View File

@@ -1,73 +1,73 @@
using System;
using System.IO;
using StellaOps.Plugin.Hosting;
using StellaOps.Scheduler.WebService.Hosting;
using StellaOps.Scheduler.WebService.Options;
using Xunit;
namespace StellaOps.Scheduler.WebService.Tests;
public class SchedulerPluginHostFactoryTests
{
[Fact]
public void Build_usesDefaults_whenOptionsEmpty()
{
var options = new SchedulerOptions.PluginOptions();
var contentRoot = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(contentRoot);
try
{
var hostOptions = SchedulerPluginHostFactory.Build(options, contentRoot);
var expectedBase = Path.GetFullPath(Path.Combine(contentRoot, ".."));
var expectedPlugins = Path.Combine(expectedBase, "plugins", "scheduler");
Assert.Equal(expectedBase, hostOptions.BaseDirectory);
Assert.Equal(expectedPlugins, hostOptions.PluginsDirectory);
Assert.Single(hostOptions.SearchPatterns, "StellaOps.Scheduler.Plugin.*.dll");
Assert.True(hostOptions.EnsureDirectoryExists);
Assert.False(hostOptions.RecursiveSearch);
Assert.Empty(hostOptions.PluginOrder);
}
finally
{
Directory.Delete(contentRoot, recursive: true);
}
}
[Fact]
public void Build_respectsConfiguredValues()
{
var options = new SchedulerOptions.PluginOptions
{
BaseDirectory = Path.Combine(Path.GetTempPath(), "scheduler-options", Guid.NewGuid().ToString("N")),
Directory = Path.Combine("custom", "plugins"),
RecursiveSearch = true,
EnsureDirectoryExists = false
};
options.SearchPatterns.Add("Custom.Plugin.*.dll");
options.OrderedPlugins.Add("StellaOps.Scheduler.Plugin.Alpha");
Directory.CreateDirectory(options.BaseDirectory!);
try
{
var hostOptions = SchedulerPluginHostFactory.Build(options, contentRootPath: Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")));
var expectedPlugins = Path.GetFullPath(Path.Combine(options.BaseDirectory!, options.Directory!));
Assert.Equal(options.BaseDirectory, hostOptions.BaseDirectory);
Assert.Equal(expectedPlugins, hostOptions.PluginsDirectory);
Assert.Single(hostOptions.SearchPatterns, "Custom.Plugin.*.dll");
Assert.Single(hostOptions.PluginOrder, "StellaOps.Scheduler.Plugin.Alpha");
Assert.True(hostOptions.RecursiveSearch);
Assert.False(hostOptions.EnsureDirectoryExists);
}
finally
{
Directory.Delete(options.BaseDirectory!, recursive: true);
}
}
}
using System;
using System.IO;
using StellaOps.Plugin.Hosting;
using StellaOps.Scheduler.WebService.Hosting;
using StellaOps.Scheduler.WebService.Options;
using Xunit;
namespace StellaOps.Scheduler.WebService.Tests;
public class SchedulerPluginHostFactoryTests
{
[Fact]
public void Build_usesDefaults_whenOptionsEmpty()
{
var options = new SchedulerOptions.PluginOptions();
var contentRoot = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(contentRoot);
try
{
var hostOptions = SchedulerPluginHostFactory.Build(options, contentRoot);
var expectedBase = Path.GetFullPath(Path.Combine(contentRoot, ".."));
var expectedPlugins = Path.Combine(expectedBase, "plugins", "scheduler");
Assert.Equal(expectedBase, hostOptions.BaseDirectory);
Assert.Equal(expectedPlugins, hostOptions.PluginsDirectory);
Assert.Single(hostOptions.SearchPatterns, "StellaOps.Scheduler.Plugin.*.dll");
Assert.True(hostOptions.EnsureDirectoryExists);
Assert.False(hostOptions.RecursiveSearch);
Assert.Empty(hostOptions.PluginOrder);
}
finally
{
Directory.Delete(contentRoot, recursive: true);
}
}
[Fact]
public void Build_respectsConfiguredValues()
{
var options = new SchedulerOptions.PluginOptions
{
BaseDirectory = Path.Combine(Path.GetTempPath(), "scheduler-options", Guid.NewGuid().ToString("N")),
Directory = Path.Combine("custom", "plugins"),
RecursiveSearch = true,
EnsureDirectoryExists = false
};
options.SearchPatterns.Add("Custom.Plugin.*.dll");
options.OrderedPlugins.Add("StellaOps.Scheduler.Plugin.Alpha");
Directory.CreateDirectory(options.BaseDirectory!);
try
{
var hostOptions = SchedulerPluginHostFactory.Build(options, contentRootPath: Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")));
var expectedPlugins = Path.GetFullPath(Path.Combine(options.BaseDirectory!, options.Directory!));
Assert.Equal(options.BaseDirectory, hostOptions.BaseDirectory);
Assert.Equal(expectedPlugins, hostOptions.PluginsDirectory);
Assert.Single(hostOptions.SearchPatterns, "Custom.Plugin.*.dll");
Assert.Single(hostOptions.PluginOrder, "StellaOps.Scheduler.Plugin.Alpha");
Assert.True(hostOptions.RecursiveSearch);
Assert.False(hostOptions.EnsureDirectoryExists);
}
finally
{
Directory.Delete(options.BaseDirectory!, recursive: true);
}
}
}

View File

@@ -8,7 +8,6 @@
<UseConcelierTestInfra>false</UseConcelierTestInfra>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Mongo2Go" Version="4.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.0" />
<PackageReference Include="xunit" Version="2.9.2" />