Restructure solution layout by module

This commit is contained in:
master
2025-10-28 15:10:40 +02:00
parent 95daa159c4
commit d870da18ce
4103 changed files with 192899 additions and 187024 deletions

View File

@@ -0,0 +1,39 @@
namespace StellaOps.Scheduler.Models.Tests;
public sealed class AuditRecordTests
{
[Fact]
public void AuditRecordNormalizesMetadataAndIdentifiers()
{
var actor = new AuditActor(actorId: "user_admin", displayName: "Cluster Admin", kind: "user");
var metadata = new[]
{
new KeyValuePair<string, string>("details", "schedule paused"),
new KeyValuePair<string, string>("Details", "should be overridden"), // duplicate with different casing
new KeyValuePair<string, string>("reason", "maintenance"),
};
var record = new AuditRecord(
id: "audit_001",
tenantId: "tenant-alpha",
category: "scheduler",
action: "pause",
occurredAt: DateTimeOffset.Parse("2025-10-18T05:00:00Z"),
actor: actor,
scheduleId: "sch_001",
runId: null,
correlationId: "corr-123",
metadata: metadata,
message: "Paused via API");
Assert.Equal("tenant-alpha", record.TenantId);
Assert.Equal("scheduler", record.Category);
Assert.Equal(2, record.Metadata.Count);
Assert.Equal("schedule paused", record.Metadata["details"]);
Assert.Equal("maintenance", record.Metadata["reason"]);
var json = CanonicalJsonSerializer.Serialize(record);
Assert.Contains("\"category\":\"scheduler\"", json, StringComparison.Ordinal);
Assert.Contains("\"metadata\":{\"details\":\"schedule paused\",\"reason\":\"maintenance\"}", json, StringComparison.Ordinal);
}
}

View File

@@ -0,0 +1,171 @@
namespace StellaOps.Scheduler.Models.Tests;
public sealed class GraphJobStateMachineTests
{
[Theory]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Pending, true)]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Queued, true)]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Running, true)]
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Completed, false)]
[InlineData(GraphJobStatus.Queued, GraphJobStatus.Running, true)]
[InlineData(GraphJobStatus.Queued, GraphJobStatus.Completed, false)]
[InlineData(GraphJobStatus.Running, GraphJobStatus.Completed, true)]
[InlineData(GraphJobStatus.Running, GraphJobStatus.Pending, false)]
[InlineData(GraphJobStatus.Completed, GraphJobStatus.Failed, false)]
public void CanTransition_ReturnsExpectedResult(GraphJobStatus from, GraphJobStatus to, bool expected)
{
Assert.Equal(expected, GraphJobStateMachine.CanTransition(from, to));
}
[Fact]
public void EnsureTransition_UpdatesBuildJobLifecycle()
{
var createdAt = new DateTimeOffset(2025, 10, 26, 12, 0, 0, TimeSpan.Zero);
var job = new GraphBuildJob(
id: "gbj_1",
tenantId: "tenant-alpha",
sbomId: "sbom_1",
sbomVersionId: "sbom_ver_1",
sbomDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
status: GraphJobStatus.Pending,
trigger: GraphBuildJobTrigger.SbomVersion,
createdAt: createdAt);
var queuedAt = createdAt.AddSeconds(5);
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Queued, queuedAt);
Assert.Equal(GraphJobStatus.Queued, job.Status);
Assert.Null(job.StartedAt);
Assert.Null(job.CompletedAt);
var runningAt = queuedAt.AddSeconds(5);
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Running, runningAt, attempts: job.Attempts + 1);
Assert.Equal(GraphJobStatus.Running, job.Status);
Assert.Equal(runningAt, job.StartedAt);
Assert.Null(job.CompletedAt);
var completedAt = runningAt.AddSeconds(30);
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Completed, completedAt);
Assert.Equal(GraphJobStatus.Completed, job.Status);
Assert.Equal(runningAt, job.StartedAt);
Assert.Equal(completedAt, job.CompletedAt);
Assert.Null(job.Error);
}
[Fact]
public void EnsureTransition_ToFailedRequiresError()
{
var job = new GraphBuildJob(
id: "gbj_1",
tenantId: "tenant-alpha",
sbomId: "sbom_1",
sbomVersionId: "sbom_ver_1",
sbomDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
status: GraphJobStatus.Running,
trigger: GraphBuildJobTrigger.SbomVersion,
createdAt: DateTimeOffset.UtcNow,
startedAt: DateTimeOffset.UtcNow);
Assert.Throws<InvalidOperationException>(() => GraphJobStateMachine.EnsureTransition(
job,
GraphJobStatus.Failed,
DateTimeOffset.UtcNow));
}
[Fact]
public void EnsureTransition_ToFailedSetsError()
{
var job = new GraphOverlayJob(
id: "goj_1",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap_1",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@latest",
status: GraphJobStatus.Running,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: DateTimeOffset.UtcNow,
startedAt: DateTimeOffset.UtcNow);
var failed = GraphJobStateMachine.EnsureTransition(
job,
GraphJobStatus.Failed,
DateTimeOffset.UtcNow,
errorMessage: "cartographer timeout");
Assert.Equal(GraphJobStatus.Failed, failed.Status);
Assert.NotNull(failed.CompletedAt);
Assert.Equal("cartographer timeout", failed.Error);
}
[Fact]
public void Validate_RequiresCompletedAtForTerminalState()
{
var job = new GraphOverlayJob(
id: "goj_1",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap_1",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@latest",
status: GraphJobStatus.Completed,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: DateTimeOffset.UtcNow);
Assert.Throws<InvalidOperationException>(() => GraphJobStateMachine.Validate(job));
}
[Fact]
public void GraphOverlayJob_NormalizesSubjectsAndMetadata()
{
var createdAt = DateTimeOffset.UtcNow;
var job = new GraphOverlayJob(
id: "goj_norm",
tenantId: "tenant-alpha",
graphSnapshotId: "graph_snap_norm",
overlayKind: GraphOverlayKind.Policy,
overlayKey: "policy@norm",
status: GraphJobStatus.Pending,
trigger: GraphOverlayJobTrigger.Policy,
createdAt: createdAt,
subjects: new[]
{
"artifact/service-api",
"artifact/service-ui",
"artifact/service-api"
},
metadata: new[]
{
new KeyValuePair<string, string>("PolicyRunId", "run-123"),
new KeyValuePair<string, string>("policyRunId", "run-123")
});
Assert.Equal(2, job.Subjects.Length);
Assert.Collection(
job.Subjects,
subject => Assert.Equal("artifact/service-api", subject),
subject => Assert.Equal("artifact/service-ui", subject));
Assert.Single(job.Metadata);
Assert.Equal("run-123", job.Metadata["policyrunid"]);
}
[Fact]
public void GraphBuildJob_NormalizesDigestAndMetadata()
{
var job = new GraphBuildJob(
id: "gbj_norm",
tenantId: "tenant-alpha",
sbomId: "sbom_norm",
sbomVersionId: "sbom_ver_norm",
sbomDigest: "SHA256:ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890",
status: GraphJobStatus.Pending,
trigger: GraphBuildJobTrigger.Manual,
createdAt: DateTimeOffset.UtcNow,
metadata: new[]
{
new KeyValuePair<string, string>("SBoMEventId", "evt-42")
});
Assert.Equal("sha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", job.SbomDigest);
Assert.Single(job.Metadata);
Assert.Equal("evt-42", job.Metadata["sbomeventid"]);
}
}

View File

@@ -0,0 +1,55 @@
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class ImpactSetTests
{
[Fact]
public void ImpactSetSortsImagesByDigest()
{
var selector = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
var images = new[]
{
new ImpactImage(
imageDigest: "sha256:bbbb",
registry: "registry.internal",
repository: "app/api",
namespaces: new[] { "team-a" },
tags: new[] { "prod", "latest" },
usedByEntrypoint: true,
labels: new Dictionary<string, string>
{
["env"] = "prod",
}),
new ImpactImage(
imageDigest: "sha256:aaaa",
registry: "registry.internal",
repository: "app/api",
namespaces: new[] { "team-a" },
tags: new[] { "prod" },
usedByEntrypoint: false),
};
var impactSet = new ImpactSet(
selector,
images,
usageOnly: true,
generatedAt: DateTimeOffset.Parse("2025-10-18T05:04:03Z"),
total: 2,
snapshotId: "snap-001");
Assert.Equal(SchedulerSchemaVersions.ImpactSet, impactSet.SchemaVersion);
Assert.Equal(new[] { "sha256:aaaa", "sha256:bbbb" }, impactSet.Images.Select(i => i.ImageDigest));
Assert.True(impactSet.UsageOnly);
Assert.Equal(2, impactSet.Total);
var json = CanonicalJsonSerializer.Serialize(impactSet);
Assert.Contains("\"snapshotId\":\"snap-001\"", json, StringComparison.Ordinal);
}
[Fact]
public void ImpactImageRejectsInvalidDigest()
{
Assert.Throws<ArgumentException>(() => new ImpactImage("sha1:not-supported", "registry", "repo"));
}
}

View File

@@ -0,0 +1,83 @@
using System.Collections.Immutable;
using System.Text.Json;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class PolicyRunModelsTests
{
[Fact]
public void PolicyRunInputs_NormalizesEnvironmentKeys()
{
var inputs = new PolicyRunInputs(
sbomSet: new[] { "sbom:two", "sbom:one" },
env: new[]
{
new KeyValuePair<string, object?>("Sealed", true),
new KeyValuePair<string, object?>("Exposure", "internet"),
new KeyValuePair<string, object?>("region", JsonSerializer.SerializeToElement("global"))
},
captureExplain: true);
Assert.Equal(new[] { "sbom:one", "sbom:two" }, inputs.SbomSet);
Assert.True(inputs.CaptureExplain);
Assert.Equal(3, inputs.Environment.Count);
Assert.True(inputs.Environment.ContainsKey("sealed"));
Assert.Equal(JsonValueKind.True, inputs.Environment["sealed"].ValueKind);
Assert.Equal("internet", inputs.Environment["exposure"].GetString());
Assert.Equal("global", inputs.Environment["region"].GetString());
}
[Fact]
public void PolicyRunStatus_ThrowsOnNegativeAttempts()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PolicyRunStatus(
runId: "run:test",
tenantId: "tenant-alpha",
policyId: "P-1",
policyVersion: 1,
mode: PolicyRunMode.Full,
status: PolicyRunExecutionStatus.Queued,
priority: PolicyRunPriority.Normal,
queuedAt: DateTimeOffset.UtcNow,
attempts: -1));
}
[Fact]
public void PolicyDiffSummary_NormalizesSeverityKeys()
{
var summary = new PolicyDiffSummary(
added: 1,
removed: 2,
unchanged: 3,
bySeverity: new[]
{
new KeyValuePair<string, PolicyDiffSeverityDelta>("critical", new PolicyDiffSeverityDelta(1, 0)),
new KeyValuePair<string, PolicyDiffSeverityDelta>("HIGH", new PolicyDiffSeverityDelta(0, 1))
});
Assert.True(summary.BySeverity.ContainsKey("Critical"));
Assert.True(summary.BySeverity.ContainsKey("High"));
}
[Fact]
public void PolicyExplainTrace_LowercasesMetadataKeys()
{
var trace = new PolicyExplainTrace(
findingId: "finding:alpha",
policyId: "P-1",
policyVersion: 1,
tenantId: "tenant-alpha",
runId: "run:test",
verdict: new PolicyExplainVerdict(PolicyVerdictStatus.Passed, SeverityRank.Low, quiet: false, score: 0, rationale: "ok"),
evaluatedAt: DateTimeOffset.UtcNow,
metadata: ImmutableSortedDictionary.CreateRange(new[]
{
new KeyValuePair<string, string>("TraceId", "trace-1"),
new KeyValuePair<string, string>("ComponentPurl", "pkg:npm/a@1.0.0")
}));
Assert.Equal("trace-1", trace.Metadata["traceid"]);
Assert.Equal("pkg:npm/a@1.0.0", trace.Metadata["componentpurl"]);
}
}

View File

@@ -0,0 +1,59 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using StellaOps.Notify.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class RescanDeltaEventSampleTests
{
private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web);
[Fact]
public void RescanDeltaEventSampleAlignsWithContracts()
{
const string fileName = "scheduler.rescan.delta@1.sample.json";
var json = LoadSample(fileName);
var notifyEvent = JsonSerializer.Deserialize<NotifyEvent>(json, SerializerOptions);
Assert.NotNull(notifyEvent);
Assert.Equal(NotifyEventKinds.SchedulerRescanDelta, notifyEvent!.Kind);
Assert.NotEqual(Guid.Empty, notifyEvent.EventId);
Assert.NotNull(notifyEvent.Payload);
Assert.Null(notifyEvent.Scope);
var payload = Assert.IsType<JsonObject>(notifyEvent.Payload);
var scheduleId = Assert.IsAssignableFrom<JsonValue>(payload["scheduleId"]).GetValue<string>();
Assert.Equal("rescan-weekly-critical", scheduleId);
var digests = Assert.IsType<JsonArray>(payload["impactedDigests"]);
Assert.Equal(2, digests.Count);
foreach (var digestNode in digests)
{
var digest = Assert.IsAssignableFrom<JsonValue>(digestNode).GetValue<string>();
Assert.StartsWith("sha256:", digest, StringComparison.Ordinal);
}
var summary = Assert.IsType<JsonObject>(payload["summary"]);
Assert.Equal(0, summary["newCritical"]!.GetValue<int>());
Assert.Equal(1, summary["newHigh"]!.GetValue<int>());
Assert.Equal(4, summary["total"]!.GetValue<int>());
var canonicalJson = NotifyCanonicalJsonSerializer.Serialize(notifyEvent);
var canonicalNode = JsonNode.Parse(canonicalJson) ?? throw new InvalidOperationException("Canonical JSON null.");
var sampleNode = JsonNode.Parse(json) ?? throw new InvalidOperationException("Sample JSON null.");
Assert.True(JsonNode.DeepEquals(sampleNode, canonicalNode), "Rescan delta event sample must remain canonical.");
}
private static string LoadSample(string fileName)
{
var path = Path.Combine(AppContext.BaseDirectory, fileName);
if (!File.Exists(path))
{
throw new FileNotFoundException($"Unable to locate sample '{fileName}'.", path);
}
return File.ReadAllText(path);
}
}

View File

@@ -0,0 +1,108 @@
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class RunStateMachineTests
{
[Fact]
public void EnsureTransition_FromQueuedToRunningSetsStartedAt()
{
var run = new Run(
id: "run-queued",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Queued,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"));
var transitionTime = DateTimeOffset.Parse("2025-10-18T03:05:00Z");
var updated = RunStateMachine.EnsureTransition(
run,
RunState.Running,
transitionTime,
mutateStats: builder => builder.SetQueued(1));
Assert.Equal(RunState.Running, updated.State);
Assert.Equal(transitionTime.ToUniversalTime(), updated.StartedAt);
Assert.Equal(1, updated.Stats.Queued);
Assert.Null(updated.Error);
}
[Fact]
public void EnsureTransition_ToCompletedPopulatesFinishedAt()
{
var run = new Run(
id: "run-running",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Running,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
var completedAt = DateTimeOffset.Parse("2025-10-18T03:10:00Z");
var updated = RunStateMachine.EnsureTransition(
run,
RunState.Completed,
completedAt,
mutateStats: builder =>
{
builder.SetQueued(1);
builder.SetCompleted(1);
});
Assert.Equal(RunState.Completed, updated.State);
Assert.Equal(completedAt.ToUniversalTime(), updated.FinishedAt);
Assert.Equal(1, updated.Stats.Completed);
}
[Fact]
public void EnsureTransition_ErrorRequiresMessage()
{
var run = new Run(
id: "run-running",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Running,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
var timestamp = DateTimeOffset.Parse("2025-10-18T03:06:00Z");
var ex = Assert.Throws<InvalidOperationException>(
() => RunStateMachine.EnsureTransition(run, RunState.Error, timestamp));
Assert.Contains("requires a non-empty error message", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void Validate_ThrowsWhenTerminalWithoutFinishedAt()
{
var run = new Run(
id: "run-bad",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Completed,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
Assert.Throws<InvalidOperationException>(() => RunStateMachine.Validate(run));
}
[Fact]
public void RunReasonExtension_NormalizesImpactWindow()
{
var reason = new RunReason(manualReason: "delta");
var from = DateTimeOffset.Parse("2025-10-18T01:00:00+02:00");
var to = DateTimeOffset.Parse("2025-10-18T03:30:00+02:00");
var updated = reason.WithImpactWindow(from, to);
Assert.Equal(from.ToUniversalTime().ToString("O"), updated.ImpactWindowFrom);
Assert.Equal(to.ToUniversalTime().ToString("O"), updated.ImpactWindowTo);
}
}

View File

@@ -0,0 +1,78 @@
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class RunValidationTests
{
[Fact]
public void RunStatsRejectsNegativeValues()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(candidates: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(deduped: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(queued: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(completed: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(deltas: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(newCriticals: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(newHigh: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(newMedium: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(newLow: -1));
}
[Fact]
public void DeltaSummarySortsTopFindingsBySeverityThenId()
{
var summary = new DeltaSummary(
imageDigest: "sha256:0011",
newFindings: 3,
newCriticals: 1,
newHigh: 1,
newMedium: 1,
newLow: 0,
kevHits: new[] { "CVE-2025-0002", "CVE-2025-0001" },
topFindings: new[]
{
new DeltaFinding("pkg:maven/b", "CVE-2025-0002", SeverityRank.High),
new DeltaFinding("pkg:maven/a", "CVE-2024-0001", SeverityRank.Critical),
new DeltaFinding("pkg:maven/c", "CVE-2025-0008", SeverityRank.Medium),
},
reportUrl: "https://ui.example/reports/sha256:0011",
attestation: new DeltaAttestation(uuid: "rekor-1", verified: true),
detectedAt: DateTimeOffset.Parse("2025-10-18T00:01:02Z"));
Assert.Equal(new[] { "pkg:maven/a", "pkg:maven/b", "pkg:maven/c" }, summary.TopFindings.Select(f => f.Purl));
Assert.Equal(new[] { "CVE-2025-0001", "CVE-2025-0002" }, summary.KevHits);
}
[Fact]
public void RunSerializationIncludesDeterministicOrdering()
{
var stats = new RunStats(candidates: 10, deduped: 8, queued: 8, completed: 5, deltas: 3, newCriticals: 2);
var run = new Run(
id: "run_001",
tenantId: "tenant-alpha",
trigger: RunTrigger.Feedser,
state: RunState.Running,
stats: stats,
reason: new RunReason(feedserExportId: "exp-123"),
scheduleId: "sch_001",
createdAt: DateTimeOffset.Parse("2025-10-18T01:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T01:00:05Z"),
finishedAt: null,
error: null,
deltas: new[]
{
new DeltaSummary(
imageDigest: "sha256:aaa",
newFindings: 1,
newCriticals: 1,
newHigh: 0,
newMedium: 0,
newLow: 0)
});
var json = CanonicalJsonSerializer.Serialize(run);
Assert.Equal(SchedulerSchemaVersions.Run, run.SchemaVersion);
Assert.Contains("\"trigger\":\"feedser\"", json, StringComparison.Ordinal);
Assert.Contains("\"stats\":{\"candidates\":10,\"deduped\":8,\"queued\":8,\"completed\":5,\"deltas\":3,\"newCriticals\":2,\"newHigh\":0,\"newMedium\":0,\"newLow\":0}", json, StringComparison.Ordinal);
}
}

View File

@@ -0,0 +1,245 @@
using System;
using System.Collections.Immutable;
using System.Text.Json;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class SamplePayloadTests
{
private static readonly string SamplesRoot = LocateSamplesRoot();
[Fact]
public void ScheduleSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("schedule.json");
var schedule = CanonicalJsonSerializer.Deserialize<Schedule>(json);
Assert.Equal("sch_20251018a", schedule.Id);
Assert.Equal("tenant-alpha", schedule.TenantId);
var canonical = CanonicalJsonSerializer.Serialize(schedule);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void RunSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("run.json");
var run = CanonicalJsonSerializer.Deserialize<Run>(json);
Assert.Equal(RunState.Running, run.State);
Assert.Equal(42, run.Stats.Deltas);
var canonical = CanonicalJsonSerializer.Serialize(run);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void ImpactSetSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("impact-set.json");
var impact = CanonicalJsonSerializer.Deserialize<ImpactSet>(json);
Assert.True(impact.UsageOnly);
Assert.Single(impact.Images);
var canonical = CanonicalJsonSerializer.Serialize(impact);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void AuditSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("audit.json");
var audit = CanonicalJsonSerializer.Deserialize<AuditRecord>(json);
Assert.Equal("scheduler", audit.Category);
Assert.Equal("pause", audit.Action);
var canonical = CanonicalJsonSerializer.Serialize(audit);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void GraphBuildJobSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("graph-build-job.json");
var job = CanonicalJsonSerializer.Deserialize<GraphBuildJob>(json);
Assert.Equal(GraphJobStatus.Running, job.Status);
Assert.Equal(GraphBuildJobTrigger.SbomVersion, job.Trigger);
var canonical = CanonicalJsonSerializer.Serialize(job);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void GraphOverlayJobSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("graph-overlay-job.json");
var job = CanonicalJsonSerializer.Deserialize<GraphOverlayJob>(json);
Assert.Equal(GraphJobStatus.Queued, job.Status);
Assert.Equal(GraphOverlayJobTrigger.Policy, job.Trigger);
Assert.Equal(GraphOverlayKind.Policy, job.OverlayKind);
var canonical = CanonicalJsonSerializer.Serialize(job);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void PolicyRunRequestSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("policy-run-request.json");
var request = CanonicalJsonSerializer.Deserialize<PolicyRunRequest>(json);
Assert.Equal("default", request.TenantId);
Assert.Equal(PolicyRunMode.Incremental, request.Mode);
Assert.Equal("run:P-7:2025-10-26:auto", request.RunId);
Assert.True(request.Inputs.CaptureExplain);
Assert.Equal(2, request.Inputs.SbomSet.Length);
var canonical = CanonicalJsonSerializer.Serialize(request);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void PolicyRunStatusSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("policy-run-status.json");
var status = CanonicalJsonSerializer.Deserialize<PolicyRunStatus>(json);
Assert.Equal(PolicyRunExecutionStatus.Succeeded, status.Status);
Assert.Equal(1742, status.Stats.Components);
Assert.Equal("scheduler", status.Metadata["orchestrator"]);
var canonical = CanonicalJsonSerializer.Serialize(status);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void PolicyDiffSummarySample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("policy-diff-summary.json");
var summary = CanonicalJsonSerializer.Deserialize<PolicyDiffSummary>(json);
Assert.Equal(12, summary.Added);
Assert.Contains(summary.BySeverity.Keys, key => string.Equals(key, "critical", StringComparison.OrdinalIgnoreCase));
Assert.Equal(2, summary.RuleHits.Length);
var canonical = CanonicalJsonSerializer.Serialize(summary);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void PolicyExplainTraceSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("policy-explain-trace.json");
var trace = CanonicalJsonSerializer.Deserialize<PolicyExplainTrace>(json);
Assert.Equal("finding:sbom:S-42/pkg:npm/lodash@4.17.21", trace.FindingId);
Assert.Equal(PolicyVerdictStatus.Blocked, trace.Verdict.Status);
Assert.Equal(2, trace.RuleChain.Length);
Assert.Equal(2, trace.Evidence.Length);
var canonical = CanonicalJsonSerializer.Serialize(trace);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void PolicyRunJob_RoundtripsThroughCanonicalSerializer()
{
var metadata = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
metadata["source"] = "cli";
metadata["trigger"] = "manual";
var job = new PolicyRunJob(
SchemaVersion: SchedulerSchemaVersions.PolicyRunJob,
Id: "job_20251026T140500Z",
TenantId: "tenant-alpha",
PolicyId: "P-7",
PolicyVersion: 4,
Mode: PolicyRunMode.Incremental,
Priority: PolicyRunPriority.High,
PriorityRank: -1,
RunId: "run:P-7:2025-10-26:auto",
RequestedBy: "user:cli",
CorrelationId: "req-20251026T140500Z",
Metadata: metadata.ToImmutable(),
Inputs: new PolicyRunInputs(
sbomSet: new[] { "sbom:S-42", "sbom:S-318" },
advisoryCursor: DateTimeOffset.Parse("2025-10-26T13:59:00Z"),
captureExplain: true),
QueuedAt: DateTimeOffset.Parse("2025-10-26T14:05:00Z"),
Status: PolicyRunJobStatus.Pending,
AttemptCount: 1,
LastAttemptAt: DateTimeOffset.Parse("2025-10-26T14:05:30Z"),
LastError: "transient network error",
CreatedAt: DateTimeOffset.Parse("2025-10-26T14:04:50Z"),
UpdatedAt: DateTimeOffset.Parse("2025-10-26T14:05:10Z"),
AvailableAt: DateTimeOffset.Parse("2025-10-26T14:05:20Z"),
SubmittedAt: null,
CompletedAt: null,
LeaseOwner: "worker-01",
LeaseExpiresAt: DateTimeOffset.Parse("2025-10-26T14:06:30Z"),
CancellationRequested: false,
CancellationRequestedAt: null,
CancellationReason: null,
CancelledAt: null);
var canonical = CanonicalJsonSerializer.Serialize(job);
var roundtrip = CanonicalJsonSerializer.Deserialize<PolicyRunJob>(canonical);
Assert.Equal(job.TenantId, roundtrip.TenantId);
Assert.Equal(job.PolicyId, roundtrip.PolicyId);
Assert.Equal(job.Priority, roundtrip.Priority);
Assert.Equal(job.Status, roundtrip.Status);
Assert.Equal(job.RunId, roundtrip.RunId);
Assert.Equal("cli", roundtrip.Metadata!["source"]);
}
private static string ReadSample(string fileName)
{
var path = Path.Combine(SamplesRoot, fileName);
return File.ReadAllText(path);
}
private static string LocateSamplesRoot()
{
var current = AppContext.BaseDirectory;
while (!string.IsNullOrEmpty(current))
{
var candidate = Path.Combine(current, "samples", "api", "scheduler");
if (Directory.Exists(candidate))
{
return candidate;
}
var parent = Path.GetDirectoryName(current.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
if (string.Equals(parent, current, StringComparison.Ordinal))
{
break;
}
current = parent;
}
throw new DirectoryNotFoundException("Unable to locate samples/api/scheduler in repository tree.");
}
private static void AssertJsonEquivalent(string expected, string actual)
{
var normalizedExpected = NormalizeJson(expected);
var normalizedActual = NormalizeJson(actual);
Assert.Equal(normalizedExpected, normalizedActual);
}
private static string NormalizeJson(string json)
{
using var document = JsonDocument.Parse(json);
return JsonSerializer.Serialize(document.RootElement, new JsonSerializerOptions
{
WriteIndented = false
});
}
}

View File

@@ -0,0 +1,113 @@
using System.Text.Json;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class ScheduleSerializationTests
{
[Fact]
public void ScheduleSerialization_IsDeterministicRegardlessOfInputOrdering()
{
var selectionA = new Selector(
SelectorScope.ByNamespace,
tenantId: "tenant-alpha",
namespaces: new[] { "team-b", "team-a" },
repositories: new[] { "app/service-api", "app/service-web" },
digests: new[] { "sha256:bb", "sha256:aa" },
includeTags: new[] { "prod", "canary" },
labels: new[]
{
new LabelSelector("env", new[] { "prod", "staging" }),
new LabelSelector("app", new[] { "web", "api" }),
},
resolvesTags: true);
var selectionB = new Selector(
scope: SelectorScope.ByNamespace,
tenantId: "tenant-alpha",
namespaces: new[] { "team-a", "team-b" },
repositories: new[] { "app/service-web", "app/service-api" },
digests: new[] { "sha256:aa", "sha256:bb" },
includeTags: new[] { "canary", "prod" },
labels: new[]
{
new LabelSelector("app", new[] { "api", "web" }),
new LabelSelector("env", new[] { "staging", "prod" }),
},
resolvesTags: true);
var scheduleA = new Schedule(
id: "sch_001",
tenantId: "tenant-alpha",
name: "Nightly Prod",
enabled: true,
cronExpression: "0 2 * * *",
timezone: "UTC",
mode: ScheduleMode.AnalysisOnly,
selection: selectionA,
onlyIf: new ScheduleOnlyIf(lastReportOlderThanDays: 7, policyRevision: "policy@42"),
notify: new ScheduleNotify(onNewFindings: true, SeverityRank.High, includeKev: true),
limits: new ScheduleLimits(maxJobs: 1000, ratePerSecond: 25, parallelism: 4),
createdAt: DateTimeOffset.Parse("2025-10-18T23:00:00Z"),
createdBy: "svc_scheduler",
updatedAt: DateTimeOffset.Parse("2025-10-18T23:00:00Z"),
updatedBy: "svc_scheduler");
var scheduleB = new Schedule(
id: scheduleA.Id,
tenantId: scheduleA.TenantId,
name: scheduleA.Name,
enabled: scheduleA.Enabled,
cronExpression: scheduleA.CronExpression,
timezone: scheduleA.Timezone,
mode: scheduleA.Mode,
selection: selectionB,
onlyIf: scheduleA.OnlyIf,
notify: scheduleA.Notify,
limits: scheduleA.Limits,
createdAt: scheduleA.CreatedAt,
createdBy: scheduleA.CreatedBy,
updatedAt: scheduleA.UpdatedAt,
updatedBy: scheduleA.UpdatedBy,
subscribers: scheduleA.Subscribers);
var jsonA = CanonicalJsonSerializer.Serialize(scheduleA);
var jsonB = CanonicalJsonSerializer.Serialize(scheduleB);
Assert.Equal(jsonA, jsonB);
using var doc = JsonDocument.Parse(jsonA);
var root = doc.RootElement;
Assert.Equal(SchedulerSchemaVersions.Schedule, root.GetProperty("schemaVersion").GetString());
Assert.Equal("analysis-only", root.GetProperty("mode").GetString());
Assert.Equal("tenant-alpha", root.GetProperty("tenantId").GetString());
var namespaces = root.GetProperty("selection").GetProperty("namespaces").EnumerateArray().Select(e => e.GetString()).ToArray();
Assert.Equal(new[] { "team-a", "team-b" }, namespaces);
}
[Theory]
[InlineData("")]
[InlineData("not-a-timezone")]
public void Schedule_ThrowsWhenTimezoneInvalid(string timezone)
{
var selection = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
Assert.ThrowsAny<Exception>(() => new Schedule(
id: "sch_002",
tenantId: "tenant-alpha",
name: "Invalid timezone",
enabled: true,
cronExpression: "0 3 * * *",
timezone: timezone,
mode: ScheduleMode.AnalysisOnly,
selection: selection,
onlyIf: null,
notify: null,
limits: null,
createdAt: DateTimeOffset.UtcNow,
createdBy: "svc",
updatedAt: DateTimeOffset.UtcNow,
updatedBy: "svc"));
}
}

View File

@@ -0,0 +1,171 @@
using System.Text.Json.Nodes;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class SchedulerSchemaMigrationTests
{
[Fact]
public void UpgradeSchedule_DefaultsSchemaVersionWhenMissing()
{
var schedule = new Schedule(
id: "sch-01",
tenantId: "tenant-alpha",
name: "Nightly",
enabled: true,
cronExpression: "0 2 * * *",
timezone: "UTC",
mode: ScheduleMode.AnalysisOnly,
selection: new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha"),
onlyIf: null,
notify: null,
limits: null,
createdAt: DateTimeOffset.Parse("2025-10-18T00:00:00Z"),
createdBy: "svc-scheduler",
updatedAt: DateTimeOffset.Parse("2025-10-18T00:00:00Z"),
updatedBy: "svc-scheduler");
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(schedule))!.AsObject();
json.Remove("schemaVersion");
var result = SchedulerSchemaMigration.UpgradeSchedule(json);
Assert.Equal(SchedulerSchemaVersions.Schedule, result.Value.SchemaVersion);
Assert.Equal(SchedulerSchemaVersions.Schedule, result.ToVersion);
Assert.Empty(result.Warnings);
}
[Fact]
public void UpgradeRun_StrictModeRemovesUnknownProperties()
{
var run = new Run(
id: "run-01",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Queued,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T01:10:00Z"));
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(run))!.AsObject();
json["extraField"] = "to-be-removed";
var result = SchedulerSchemaMigration.UpgradeRun(json, strict: true);
Assert.Contains(result.Warnings, warning => warning.Contains("extraField", StringComparison.Ordinal));
}
[Fact]
public void UpgradeImpactSet_ThrowsForUnsupportedVersion()
{
var impactSet = new ImpactSet(
selector: new Selector(SelectorScope.AllImages, "tenant-alpha"),
images: Array.Empty<ImpactImage>(),
usageOnly: false,
generatedAt: DateTimeOffset.Parse("2025-10-18T02:00:00Z"));
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(impactSet))!.AsObject();
json["schemaVersion"] = "scheduler.impact-set@99";
var ex = Assert.Throws<NotSupportedException>(() => SchedulerSchemaMigration.UpgradeImpactSet(json));
Assert.Contains("Unsupported scheduler schema version", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void UpgradeSchedule_Legacy0_UpgradesToLatestVersion()
{
var legacy = new JsonObject
{
["schemaVersion"] = SchedulerSchemaVersions.ScheduleLegacy0,
["id"] = "sch-legacy",
["tenantId"] = "tenant-alpha",
["name"] = "Legacy Nightly",
["enabled"] = true,
["cronExpression"] = "0 2 * * *",
["timezone"] = "UTC",
["mode"] = "analysis-only",
["selection"] = new JsonObject
{
["scope"] = "all-images",
["tenantId"] = "tenant-alpha",
},
["notify"] = new JsonObject
{
["onNewFindings"] = "true",
["minSeverity"] = "HIGH",
},
["limits"] = new JsonObject
{
["maxJobs"] = "5",
["parallelism"] = -2,
},
["subscribers"] = "ops-team",
["createdAt"] = "2025-10-10T00:00:00Z",
["createdBy"] = "system",
["updatedAt"] = "2025-10-10T01:00:00Z",
["updatedBy"] = "system",
};
var result = SchedulerSchemaMigration.UpgradeSchedule(legacy, strict: true);
Assert.Equal(SchedulerSchemaVersions.ScheduleLegacy0, result.FromVersion);
Assert.Equal(SchedulerSchemaVersions.Schedule, result.ToVersion);
Assert.Equal(SchedulerSchemaVersions.Schedule, result.Value.SchemaVersion);
Assert.True(result.Value.Notify.IncludeKev);
Assert.Empty(result.Value.Subscribers);
Assert.Contains(result.Warnings, warning => warning.Contains("schedule.limits.parallelism", StringComparison.Ordinal));
Assert.Contains(result.Warnings, warning => warning.Contains("schedule.subscribers", StringComparison.Ordinal));
}
[Fact]
public void UpgradeRun_Legacy0_BackfillsMissingStats()
{
var legacy = new JsonObject
{
["schemaVersion"] = SchedulerSchemaVersions.RunLegacy0,
["id"] = "run-legacy",
["tenantId"] = "tenant-alpha",
["trigger"] = "manual",
["state"] = "queued",
["stats"] = new JsonObject
{
["candidates"] = "4",
["queued"] = 2,
},
["createdAt"] = "2025-10-10T02:00:00Z",
};
var result = SchedulerSchemaMigration.UpgradeRun(legacy, strict: true);
Assert.Equal(SchedulerSchemaVersions.RunLegacy0, result.FromVersion);
Assert.Equal(SchedulerSchemaVersions.Run, result.ToVersion);
Assert.Equal(SchedulerSchemaVersions.Run, result.Value.SchemaVersion);
Assert.Equal(4, result.Value.Stats.Candidates);
Assert.Equal(0, result.Value.Stats.NewMedium);
Assert.Equal(RunState.Queued, result.Value.State);
Assert.Empty(result.Value.Deltas);
Assert.Contains(result.Warnings, warning => warning.Contains("run.stats.newMedium", StringComparison.Ordinal));
}
[Fact]
public void UpgradeImpactSet_Legacy0_ComputesTotal()
{
var legacy = new JsonObject
{
["schemaVersion"] = SchedulerSchemaVersions.ImpactSetLegacy0,
["selector"] = JsonNode.Parse("""{"scope":"all-images","tenantId":"tenant-alpha"}"""),
["images"] = new JsonArray(
JsonNode.Parse("""{"imageDigest":"sha256:1111111111111111111111111111111111111111111111111111111111111111","registry":"docker.io","repository":"library/nginx"}"""),
JsonNode.Parse("""{"imageDigest":"sha256:2222222222222222222222222222222222222222222222222222222222222222","registry":"docker.io","repository":"library/httpd"}""")),
["usageOnly"] = "false",
["generatedAt"] = "2025-10-10T03:00:00Z",
};
var result = SchedulerSchemaMigration.UpgradeImpactSet(legacy, strict: true);
Assert.Equal(SchedulerSchemaVersions.ImpactSetLegacy0, result.FromVersion);
Assert.Equal(SchedulerSchemaVersions.ImpactSet, result.ToVersion);
Assert.Equal(2, result.Value.Total);
Assert.Equal(2, result.Value.Images.Length);
Assert.Contains(result.Warnings, warning => warning.Contains("impact set total", StringComparison.OrdinalIgnoreCase));
}
}

View File

@@ -0,0 +1,19 @@
<?xml version='1.0' encoding='utf-8'?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../__Libraries/StellaOps.Scheduler.Models/StellaOps.Scheduler.Models.csproj" />
<ProjectReference Include="../../../Notify/__Libraries/StellaOps.Notify.Models/StellaOps.Notify.Models.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="..\..\docs\events\samples\scheduler.rescan.delta@1.sample.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>