Add Policy DSL Validator, Schema Exporter, and Simulation Smoke tools

- Implemented PolicyDslValidator with command-line options for strict mode and JSON output.
- Created PolicySchemaExporter to generate JSON schemas for policy-related models.
- Developed PolicySimulationSmoke tool to validate policy simulations against expected outcomes.
- Added project files and necessary dependencies for each tool.
- Ensured proper error handling and usage instructions across tools.
This commit is contained in:
master
2025-10-27 08:00:11 +02:00
parent 2b7b88ca77
commit 799f787de2
712 changed files with 49449 additions and 6124 deletions

View File

@@ -0,0 +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;
}
}

View File

@@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class EventWebhookEndpointTests : IClassFixture<WebApplicationFactory<Program>>
{
static EventWebhookEndpointTests()
{
Environment.SetEnvironmentVariable("Scheduler__Events__Webhooks__Feedser__HmacSecret", FeedserSecret);
Environment.SetEnvironmentVariable("Scheduler__Events__Webhooks__Feedser__Enabled", "true");
Environment.SetEnvironmentVariable("Scheduler__Events__Webhooks__Vexer__HmacSecret", VexerSecret);
Environment.SetEnvironmentVariable("Scheduler__Events__Webhooks__Vexer__Enabled", "true");
}
private const string FeedserSecret = "feedser-secret";
private const string VexerSecret = "vexer-secret";
private readonly WebApplicationFactory<Program> _factory;
public EventWebhookEndpointTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task FeedserWebhook_AcceptsValidSignature()
{
using var client = _factory.CreateClient();
var payload = new
{
exportId = "feedser-exp-1",
changedProductKeys = new[] { "pkg:rpm/openssl", "pkg:deb/nginx" },
kev = new[] { "CVE-2024-0001" },
window = new { from = DateTimeOffset.UtcNow.AddHours(-1), to = DateTimeOffset.UtcNow }
};
var json = JsonSerializer.Serialize(payload, new JsonSerializerOptions(JsonSerializerDefaults.Web));
using var request = new HttpRequestMessage(HttpMethod.Post, "/events/feedser-export")
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
request.Headers.TryAddWithoutValidation("X-Scheduler-Signature", ComputeSignature(FeedserSecret, json));
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
}
[Fact]
public async Task FeedserWebhook_RejectsInvalidSignature()
{
using var client = _factory.CreateClient();
var payload = new
{
exportId = "feedser-exp-2",
changedProductKeys = new[] { "pkg:nuget/log4net" }
};
var json = JsonSerializer.Serialize(payload, new JsonSerializerOptions(JsonSerializerDefaults.Web));
using var request = new HttpRequestMessage(HttpMethod.Post, "/events/feedser-export")
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
request.Headers.TryAddWithoutValidation("X-Scheduler-Signature", "sha256=invalid");
var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task VexerWebhook_HonoursRateLimit()
{
using var restrictedFactory = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureAppConfiguration((_, configuration) =>
{
configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
["Scheduler:Events:Webhooks:Vexer:RateLimitRequests"] = "1",
["Scheduler:Events:Webhooks:Vexer:RateLimitWindowSeconds"] = "60"
});
});
});
using var client = restrictedFactory.CreateClient();
var payload = new
{
exportId = "vexer-exp-1",
changedClaims = new[]
{
new { productKey = "pkg:deb/openssl", vulnerabilityId = "CVE-2024-1234", status = "affected" }
}
};
var json = JsonSerializer.Serialize(payload, new JsonSerializerOptions(JsonSerializerDefaults.Web));
using var first = new HttpRequestMessage(HttpMethod.Post, "/events/vexer-export")
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
first.Headers.TryAddWithoutValidation("X-Scheduler-Signature", ComputeSignature(VexerSecret, json));
var firstResponse = await client.SendAsync(first);
Assert.Equal(HttpStatusCode.Accepted, firstResponse.StatusCode);
using var second = new HttpRequestMessage(HttpMethod.Post, "/events/vexer-export")
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
second.Headers.TryAddWithoutValidation("X-Scheduler-Signature", ComputeSignature(VexerSecret, json));
var secondResponse = await client.SendAsync(second);
Assert.Equal((HttpStatusCode)429, secondResponse.StatusCode);
Assert.True(secondResponse.Headers.Contains("Retry-After"));
}
private static string ComputeSignature(string secret, string payload)
{
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
return "sha256=" + Convert.ToHexString(hash).ToLowerInvariant();
}
}

View File

@@ -0,0 +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;

View File

@@ -0,0 +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());
}
}

View File

@@ -0,0 +1,151 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StellaOps.Auth.Abstractions;
using StellaOps.Scheduler.Models;
using StellaOps.Scheduler.WebService.GraphJobs;
using StellaOps.Scheduler.WebService.GraphJobs.Events;
using StellaOps.Scheduler.WebService.Options;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class GraphJobEventPublisherTests
{
[Fact]
public async Task PublishAsync_WritesEventJson_WhenEnabled()
{
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerEventsOptions
{
GraphJobs = { Enabled = true }
});
var loggerProvider = new ListLoggerProvider();
using var loggerFactory = LoggerFactory.Create(builder => builder.AddProvider(loggerProvider));
var publisher = new GraphJobEventPublisher(new OptionsMonitorStub<SchedulerEventsOptions>(options), 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 message = Assert.Single(loggerProvider.Messages);
Assert.Contains("\"kind\":\"scheduler.graph.job.completed\"", message);
Assert.Contains("\"tenant\":\"tenant-alpha\"", message);
Assert.Contains("\"resultUri\":\"oras://result\"", message);
}
[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), 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);
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;
}
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

@@ -0,0 +1,104 @@
using System.Linq;
using System.Text.Json;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class RunEndpointTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public RunEndpointTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task CreateListCancelRun()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-runs");
client.DefaultRequestHeaders.Add("X-Scopes", "scheduler.schedules.write scheduler.schedules.read scheduler.runs.write scheduler.runs.read scheduler.runs.preview");
var scheduleResponse = await client.PostAsJsonAsync("/api/v1/scheduler/schedules", new
{
name = "RunSchedule",
cronExpression = "0 3 * * *",
timezone = "UTC",
mode = "analysis-only",
selection = new
{
scope = "all-images"
}
});
scheduleResponse.EnsureSuccessStatusCode();
var scheduleJson = await scheduleResponse.Content.ReadFromJsonAsync<JsonElement>();
var scheduleId = scheduleJson.GetProperty("schedule").GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(scheduleId));
var createRun = await client.PostAsJsonAsync("/api/v1/scheduler/runs", new
{
scheduleId,
trigger = "manual"
});
createRun.EnsureSuccessStatusCode();
Assert.Equal(System.Net.HttpStatusCode.Created, createRun.StatusCode);
var runJson = await createRun.Content.ReadFromJsonAsync<JsonElement>();
var runId = runJson.GetProperty("run").GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(runId));
Assert.Equal("planning", runJson.GetProperty("run").GetProperty("state").GetString());
var listResponse = await client.GetAsync("/api/v1/scheduler/runs");
listResponse.EnsureSuccessStatusCode();
var listJson = await listResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.True(listJson.GetProperty("runs").EnumerateArray().Any());
var cancelResponse = await client.PostAsync($"/api/v1/scheduler/runs/{runId}/cancel", null);
cancelResponse.EnsureSuccessStatusCode();
var cancelled = await cancelResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.Equal("cancelled", cancelled.GetProperty("run").GetProperty("state").GetString());
var getResponse = await client.GetAsync($"/api/v1/scheduler/runs/{runId}");
getResponse.EnsureSuccessStatusCode();
var runDetail = await getResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.Equal("cancelled", runDetail.GetProperty("run").GetProperty("state").GetString());
}
[Fact]
public async Task PreviewImpactForSchedule()
{
using var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-preview");
client.DefaultRequestHeaders.Add("X-Scopes", "scheduler.schedules.write scheduler.schedules.read scheduler.runs.write scheduler.runs.read scheduler.runs.preview");
var scheduleResponse = await client.PostAsJsonAsync("/api/v1/scheduler/schedules", new
{
name = "PreviewSchedule",
cronExpression = "0 5 * * *",
timezone = "UTC",
mode = "analysis-only",
selection = new
{
scope = "all-images"
}
});
scheduleResponse.EnsureSuccessStatusCode();
var scheduleJson = await scheduleResponse.Content.ReadFromJsonAsync<JsonElement>();
var scheduleId = scheduleJson.GetProperty("schedule").GetProperty("id").GetString();
Assert.False(string.IsNullOrEmpty(scheduleId));
var previewResponse = await client.PostAsJsonAsync("/api/v1/scheduler/runs/preview", new
{
scheduleId,
usageOnly = true,
sampleSize = 3
});
previewResponse.EnsureSuccessStatusCode();
var preview = await previewResponse.Content.ReadFromJsonAsync<JsonElement>();
Assert.True(preview.GetProperty("total").GetInt32() >= 0);
Assert.True(preview.GetProperty("sample").GetArrayLength() <= 3);
}
}

View File

@@ -0,0 +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());
}
}

View File

@@ -0,0 +1,46 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StellaOps.Scheduler.WebService.Options;
namespace StellaOps.Scheduler.WebService.Tests;
public sealed class SchedulerWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration((_, configuration) =>
{
configuration.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string?>("Scheduler:Authority:Enabled", "false"),
new KeyValuePair<string, string?>("Scheduler:Cartographer:Webhook:Enabled", "false"),
new KeyValuePair<string, string?>("Scheduler:Events:GraphJobs:Enabled", "false"),
new KeyValuePair<string, string?>("Scheduler:Events:Webhooks:Feedser:Enabled", "true"),
new KeyValuePair<string, string?>("Scheduler:Events:Webhooks:Feedser:HmacSecret", "feedser-secret"),
new KeyValuePair<string, string?>("Scheduler:Events:Webhooks:Feedser:RateLimitRequests", "20"),
new KeyValuePair<string, string?>("Scheduler:Events:Webhooks:Feedser:RateLimitWindowSeconds", "60"),
new KeyValuePair<string, string?>("Scheduler:Events:Webhooks:Vexer:Enabled", "true"),
new KeyValuePair<string, string?>("Scheduler:Events:Webhooks:Vexer:HmacSecret", "vexer-secret"),
new KeyValuePair<string, string?>("Scheduler:Events:Webhooks:Vexer:RateLimitRequests", "20"),
new KeyValuePair<string, string?>("Scheduler:Events:Webhooks:Vexer:RateLimitWindowSeconds", "60")
});
});
builder.ConfigureServices(services =>
{
services.Configure<SchedulerEventsOptions>(options =>
{
options.Webhooks ??= new SchedulerInboundWebhooksOptions();
options.Webhooks.Feedser ??= SchedulerWebhookOptions.CreateDefault("feedser");
options.Webhooks.Vexer ??= SchedulerWebhookOptions.CreateDefault("vexer");
options.Webhooks.Feedser.HmacSecret = "feedser-secret";
options.Webhooks.Feedser.Enabled = true;
options.Webhooks.Vexer.HmacSecret = "vexer-secret";
options.Webhooks.Vexer.Enabled = true;
});
});
}
}

View File

@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<UseConcelierTestInfra>false</UseConcelierTestInfra>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0-rc.2.25502.107" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="coverlet.collector" Version="6.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../StellaOps.Scheduler.WebService/StellaOps.Scheduler.WebService.csproj" />
</ItemGroup>
</Project>