fix(server): show the audit clean-up's real age limit and lock it before the first pass

Settings › Logs › Keep audit showed ServerOptions.AuditRetentionDays, a second
copy of the audit clean-up schedule's age limit. Edits made on Jobs › Scheduled
never reached it, so the panel could say "kept forever" while entries were
being deleted every night. Saving 0 there then changed nothing, because the
endpoint only compared against the stale option value.

- GET and PUT /server/settings now report the schedule's limit in force (0
  while the schedule is off). Saving compares against that value. A value sent
  back unchanged leaves the server.json reset default and the env lock alone. A
  new value sets the schedule and becomes the reset default.
- ApplyAgeAsync also turns the schedule on when it already holds the days but
  is off.
- CHRONOS_AUDIT_RETENTION_DAYS is now applied before the scheduler's first
  pass, through a new Scheduler.StartAsync overload with a beforeFirstPass hook.
  Before, a missed 04:30 run was caught up at start with the stale days, which
  could delete entries the variable says to keep. While the variable fixes a
  limit above 0, turning the schedule off is a 409 setting_locked.
- Corrected the comments in SchedulerHost, ServerOptions, ServerSettingsStore,
  LogSettingsDto, the header of settings.js and ARCHITECTURE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 490ed286e9f32745174b13b1963d6ec91955196b)
This commit is contained in:
Alby96 committed 2026-10-27 09:56:46 +01:00
1 parent ac121acf7c
commit 422f33d5f3
12 files changed
+232 -52

No files matched your search

@@ -10,6 +10,7 @@ using Chronos.Core.Diagnostics;
using Chronos.Protocol;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Server.Storage;
using Chronos.Testing;
using CoreLog = Chronos.Core.Diagnostics.Log;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
@@ -83,7 +84,8 @@ public sealed partial class LoggingTests(TestContext context)
[Test]
public async Task LogSettingsAreSavedAppliedAndValidated()
{
await using var server = await TestServer.StartAsync(context);
// With the archive module: its audit step is what the audit retention, the audit clean-up's age limit, deletes with.
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
var settings = await SettingsAsync(admin);
Assert.Equal(new LogSettingsDto("warning", "warning", 14, 50, 1024, "daily", 0, 4), settings.Logs);
@@ -1,9 +1,11 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Abstractions;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
@@ -216,9 +218,9 @@ public sealed class ScheduleEndpointTests(TestContext context)
}
/// <summary>
/// Owner review 2, R10 and R11: the audit retention has one source of truth, the audit clean-up schedule's age limit. The
/// field of Settings › Logs sets it (and turns the schedule on, or off at 0), Reset goes back to it, and at 0 the audit
/// step deletes nothing.
/// Owner review 2, R10 and R11: the audit retention has one source of truth, the audit clean-up schedule's age limit.
/// Settings › Logs shows it wherever it was set (0 while the schedule is off) and sets it (turning the schedule on, or
/// off at 0); Reset goes back to the value last saved there, and at 0 the audit step deletes nothing.
/// </summary>
[Test]
public async Task TheAuditRetentionOfTheSettingsIsTheAgeLimitOfTheAuditCleanUp()
@@ -243,28 +245,58 @@ public sealed class ScheduleEndpointTests(TestContext context)
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)30, true), (audit.Parameters.OlderThanDays, audit.Enabled));
// Without an environment variable the schedule stays editable; Reset goes back to the setting.
using (var edit = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 60)),
ProtocolJson.Default.UpdateScheduleRequest))
Assert.Equal((int?)60, (await edit.ReadAsync(ProtocolJson.Default.ScheduleDto)).Parameters.OlderThanDays);
// Without an environment variable the schedule stays editable, and Settings shows its limit.
await EditAsync(admin, audit.Id, new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 60)));
Assert.Equal(60, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
// Saved back as shown, it changes neither the schedule nor the value Reset goes back to.
await SaveAuditRetentionAsync(admin, 60);
Assert.Equal(30, server.Options.AuditRetentionDays);
Assert.Equal((int?)60, SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup).Parameters.OlderThanDays);
using (var reset = await admin.PostAsync($"/api/v1/schedules/{audit.Id}/reset", null))
Assert.Equal((int?)30, (await reset.ReadAsync(ProtocolJson.Default.ScheduleDto)).Parameters.OlderThanDays);
Assert.Equal(30, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
// Turned off on the schedule, nothing is deleted: Settings shows 0, and saving 30 there turns it on again.
await EditAsync(admin, audit.Id, new UpdateScheduleRequest(Enabled: false));
Assert.Equal(0, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
await SaveAuditRetentionAsync(admin, 30);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)30, true), (audit.Parameters.OlderThanDays, audit.Enabled));
// Back to 0: kept forever, the schedule off.
await SaveAuditRetentionAsync(admin, 0);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)0, false), (audit.Parameters.OlderThanDays, audit.Enabled));
// A limit set on the schedule while the setting is 0 is shown, and saving 0 turns the schedule off.
await EditAsync(admin, audit.Id, new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 45), Enabled: true));
Assert.Equal(45, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
await SaveAuditRetentionAsync(admin, 0);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)0, false), (audit.Parameters.OlderThanDays, audit.Enabled));
}
/// <summary>Saves Settings › Logs › Keep audit (days) as the admin panel does.</summary>
private static async Task SaveAuditRetentionAsync(HttpClient admin, int days)
private static async Task<ServerSettingsDto> SettingsAsync(HttpClient admin)
{
using var read = await admin.GetAsync("/api/v1/server/settings");
var settings = await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
return await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
}
/// <summary>Saves Settings › Logs › Keep audit (days) as the admin panel does; the answer shows the value saved.</summary>
private static async Task SaveAuditRetentionAsync(HttpClient admin, int days)
{
var settings = await SettingsAsync(admin);
// The test server listens on ports the OS chose, which the settings refuse: real ones are sent with the edit.
using var saved = await admin.PutAsJsonAsync("/api/v1/server/settings",
settings with { HttpPort = 18080, HttpsPort = 18443, Logs = settings.Logs with { AuditRetentionDays = days } }, ProtocolJson.Default.ServerSettingsDto);
await saved.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(days, (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).Logs.AuditRetentionDays);
}
private static async Task EditAsync(HttpClient admin, Guid id, UpdateScheduleRequest request)
{
using var edit = await admin.PutAsJsonAsync($"/api/v1/schedules/{id}", request, ProtocolJson.Default.UpdateScheduleRequest);
await edit.ExpectAsync(HttpStatusCode.OK);
}
[Test]
@@ -444,10 +476,79 @@ public sealed class ScheduleEndpointTests(TestContext context)
using (var changed = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 60)),
ProtocolJson.Default.UpdateScheduleRequest))
Assert.Equal("AuditRetentionDays", (await changed.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
// Turned off, it would keep what the variable says to delete.
using (var off = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Enabled: false), ProtocolJson.Default.UpdateScheduleRequest))
Assert.Equal("AuditRetentionDays", (await off.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
// Everything else stays editable.
using var timing = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Recurrence: new RecurrenceDto("daily", Time: "05:00"),
Parameters: new ScheduleParametersDto(Steps: ["audit", "job-history"], OlderThanDays: 30)), ProtocolJson.Default.UpdateScheduleRequest);
await timing.ExpectAsync(HttpStatusCode.OK);
// Settings shows the fixed value, and the other settings still save with it.
Assert.Equal(30, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
await SaveAuditRetentionAsync(admin, 30);
}
/// <summary>
/// A missed audit clean-up caught up at start runs with the retention CHRONOS_AUDIT_RETENTION_DAYS fixes, not with the
/// age limit the schedule held before: the variable is applied before the first pass.
/// </summary>
[Test]
public async Task ALockedAuditRetentionAppliesToTheRunCaughtUpAtStart()
{
foreach (var days in new[] { 365, 0 })
{
var root = context.CreateTempDirectory($"catch-up-{days}");
void Paths(ServerOptions o)
{
o.DataPath = Path.Combine(root, "data");
o.ArchivePath = Path.Combine(root, "archive");
Directory.CreateDirectory(o.ArchivePath);
}
DatabaseOptions database;
await using (var first = await TestServer.StartAsync(context, Paths, ArchiveModule.Register))
database = first.Options.ToDatabaseOptions();
// While the server was off: a 90-day audit clean-up whose run passed an hour ago, and an entry 200 days old.
var old = Guid.CreateVersion7();
await using (var db = await ChronosDatabase.OpenAsync(database, Ct))
{
var row = Assert.NotNull(await db.Schedules.GetBySystemKeyAsync(ServerScheduleHost.AuditCleanup, Ct));
var parameters = ScheduleMapping.Parameters(row) with { OlderThanDays = 90 };
Assert.True(await db.Schedules.UpdateAsync(row with
{
ParametersJson = ScheduleMapping.ParametersJson(row.Action, parameters),
Enabled = true,
NextRun = DateTimeOffset.UtcNow.AddHours(-1),
}, setNextRun: true, Ct));
await db.Audit.AppendAsync(new AuditEntry { Id = old, At = DateTimeOffset.UtcNow.AddDays(-200), Action = "user.login" }, Ct);
}
// CHRONOS_AUDIT_RETENTION_DAYS at the next start.
await using var second = await TestServer.StartAsync(context, o =>
{
Paths(o);
o.AuditRetentionDays = days;
o.Locked = [nameof(ServerOptions.AuditRetentionDays)];
}, ArchiveModule.Register);
var schedule = Assert.NotNull(await second.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.AuditCleanup, Ct));
var queued = await second.Database.Jobs.ListByScheduleAsync(schedule.Id, cancellationToken: Ct);
if (days == 0)
{
// Kept forever: the schedule is off before its missed run could fire.
Assert.False(schedule.Enabled);
Assert.Empty(queued);
}
else
{
Assert.Count(1, queued);
var job = queued[0];
using (var json = JsonDocument.Parse(job.ParametersJson!))
Assert.Equal(days, json.RootElement.GetProperty("olderThanDays").GetInt32());
await JobApiTests.WaitForAsync(await second.AdminAsync(), job.Id, "done");
}
var kept = (await second.Database.Audit.ListByActionsAsync(null, [], 1000, null, Ct)).Items.Select(e => e.Id);
Assert.Contains(old, kept);
}
}
[Test]