merge: or5 parcel p4

# Conflicts:
#	src/Chronos.App/Sections/ServerView.xaml
#	src/Chronos.App/Sections/ServerViewModel.cs
#	src/Chronos.Server/Jobs/JobEngineHost.cs
This commit is contained in:
Alby96 committed 2026-11-15 15:01:31 +01:00
commit e367f03c80
127 files changed
+6822 -1117

No files matched your search

@@ -0,0 +1,117 @@
using System.Text.Json;
using Chronos.Data;
using Chronos.Data.Repositories;
using Chronos.Protocol;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
/// <summary>The server's stable id announced by <c>/server/info</c> (owner review 5, #66).</summary>
[Category("server")]
public sealed class ServerInfoIdTests(TestContext context)
{
private static async Task<ServerInfo> InfoAsync(TestServer server)
{
using var response = await server.Client.GetAsync("/api/v1/server/info");
return await response.ReadAsync(ProtocolJson.Default.ServerInfo);
}
[Test]
public async Task TheIdIsMadeOnceAndKeptAcrossRestarts()
{
var root = context.CreateTempDirectory("kept");
void Same(Configuration.ServerOptions o)
{
o.DataPath = Path.Combine(root, "data");
o.ArchivePath = Path.Combine(root, "archive");
}
Guid first;
await using (var server = await TestServer.StartAsync(context, Same))
{
first = Assert.NotNull((await InfoAsync(server)).ServerId);
Assert.NotEqual(Guid.Empty, first);
var stored = await server.Database.Settings.GetJsonAsync(SettingScope.App, null, ServerHost.ServerIdKey, context.Cancellation);
Assert.Equal("\"" + first.ToString("D") + "\"", stored);
}
await using (var again = await TestServer.StartAsync(context, Same))
Assert.Equal((Guid?)first, (await InfoAsync(again)).ServerId);
// Another server (another database) has another id.
await using (var other = await TestServer.StartAsync(context))
Assert.NotEqual((Guid?)first, (await InfoAsync(other)).ServerId);
}
[Test]
public async Task TheIdSurvivesARestoreOfTheIndex()
{
var folder = context.CreateTempDirectory("restore");
Guid id;
string backup;
await using (var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation))
{
id = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
backup = await db.BackupAsync(Path.Combine(folder, "backups"), cancellationToken: context.Cancellation);
}
// A new index (the disk replaced), then the backup put back.
await using var restored = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "new.db")), context.Cancellation);
await restored.RestoreAsync(backup, context.Cancellation);
Assert.Equal(id, await ServerHost.ServerIdAsync(restored, null, context.Cancellation));
}
[Test]
public async Task AStoredIdThatIsNotOneIsMadeAgain()
{
var folder = context.CreateTempDirectory("damaged");
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation);
foreach (var damaged in new[] { "\"not a guid\"", "\"" + Guid.Empty.ToString("D") + "\"", "42" })
{
await db.Settings.SetJsonAsync(SettingScope.App, null, ServerHost.ServerIdKey, damaged, context.Cancellation);
var made = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
Assert.NotEqual(Guid.Empty, made);
Assert.Equal(made, await ServerHost.ServerIdAsync(db, null, context.Cancellation));
}
}
[Test]
[RequiresEnvironment("CHRONOS_TEST_PG")]
public async Task TheIdIsKeptOnPostgres()
{
var baseConnection = Environment.GetEnvironmentVariable("CHRONOS_TEST_PG")!;
var admin = DatabaseFactory.Open(DatabaseOptions.Postgres(baseConnection));
var schema = "chronos_s_" + Guid.NewGuid().ToString("N")[..16];
await using (var session = await admin.OpenAsync(context.Cancellation))
await session.ExecuteScriptAsync($"CREATE SCHEMA {schema}", context.Cancellation);
try
{
var options = DatabaseOptions.Postgres(baseConnection.TrimEnd(';', ' ') + $";Search Path={schema}");
Guid id;
await using (var db = await ChronosDatabase.OpenAsync(options, context.Cancellation))
id = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
await using (var db = await ChronosDatabase.OpenAsync(options, context.Cancellation))
Assert.Equal(id, await ServerHost.ServerIdAsync(db, null, context.Cancellation));
}
finally
{
await using (var session = await admin.OpenAsync(CancellationToken.None))
await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {schema} CASCADE", CancellationToken.None);
await admin.DisposeAsync();
}
}
[Test]
public void AnOlderClientAndAnOlderServerReadEachOther()
{
var id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
var info = new ServerInfo("Studio NAS", "1.1.0", 1, ["sync"], null, ["jpeg"], new ServerLimits(1, 1), null, 3, id);
var json = JsonSerializer.Serialize(info, ProtocolJson.Default.ServerInfo);
Assert.Contains("\"serverId\":\"" + id.ToString("D") + "\"", json);
Assert.Equal(info.ServerId, Assert.NotNull(JsonSerializer.Deserialize(json, ProtocolJson.Default.ServerInfo)).ServerId);
// A 1.0 server sends no id: it reads as null, and a 1.0 client ignores the member it does not know.
const string older = """{"name":"NAS","version":"1.0.0","apiVersion":1,"capabilities":["sync"],"formats":["jpeg"],"limits":{"maxUploadBytes":1,"chunkSizeBytes":1}}""";
Assert.Null(Assert.NotNull(JsonSerializer.Deserialize(older, ProtocolJson.Default.ServerInfo)).ServerId);
Assert.False(JsonSerializer.Serialize(info with { ServerId = null }, ProtocolJson.Default.ServerInfo).Contains("serverId", StringComparison.Ordinal));
using var parsed = JsonDocument.Parse(json);
Assert.Equal("Studio NAS", parsed.RootElement.GetProperty("name").GetString());
}
}
@@ -0,0 +1,336 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Diagnostics;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
using Chronos.Core.Video.Managed;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Server.Api;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Server.Jobs;
using Chronos.Server.Security;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
/// <summary>
/// The server Chronos Desktop hosts to share this PC's library (owner review 5, #67): built over an index, engines, a job
/// engine and a scheduler the test owns, as the desktop does, which it never creates, starts, stops or disposes.
/// </summary>
[Category("server")]
[Serial] // Log.Sink is process-wide: the standalone server tests running beside these set their own
public sealed class HostedServerTests(TestContext context)
{
[Test]
public async Task ItAnswersWithTheCertificateOfItsDataFolderAndKeepsItsIdAcrossRestarts()
{
await using var desktop = await DesktopFixture.StartAsync(context);
Guid? firstId;
string? fingerprint;
await using (var shared = await desktop.ShareAsync())
{
using var http = desktop.Client(shared);
using var health = await http.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, health.StatusCode);
var info = Assert.NotNull(await http.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo));
var pfx = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(desktop.ShareData, "tls", "server.pfx"), null);
Assert.Equal(CertificateStore.Fingerprint(pfx), shared.Fingerprint);
Assert.Equal(shared.ServerId, info.ServerId);
Assert.True(shared.HttpsPort > 0, "the HTTPS listener's port");
firstId = shared.ServerId;
fingerprint = shared.Fingerprint;
}
// A second start on the same folder and index: the same certificate, id and administrator.
await using var again = await desktop.ShareAsync();
Assert.Equal(fingerprint, again.Fingerprint);
Assert.Equal(firstId, again.ServerId);
Assert.Count(1, (await desktop.Database.Users.ListAsync()).Where(u => u.Role == UserRole.Admin));
}
[Test]
public async Task JobsQueuedByClientsRunOnTheDesktopsEngineWhichOutlivesTheServer()
{
await using var desktop = await DesktopFixture.StartAsync(context);
var sink = Log.Sink;
await using (var shared = await desktop.ShareAsync())
{
Assert.Same(desktop.Engine, shared.Services.GetRequiredService<JobEngineHost>().Engine);
Assert.True(shared.Services.GetRequiredService<JobEngineHost>().Hosted, "hosted");
using var admin = await desktop.AdminAsync(shared);
using var created = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("scan", [], null), ProtocolJson.Default.CreateJobRequest);
Assert.Equal(HttpStatusCode.Accepted, created.StatusCode);
var job = Assert.NotNull(await created.Content.ReadFromJsonAsync(ProtocolJson.Default.JobDto));
var done = await desktop.WaitAsync(job.Id);
Assert.Equal(JobState.Done, done.State);
Assert.Equal(DesktopFixture.WorkerId, done.NodeId);
Assert.Same(sink, Log.Sink);
}
// Stopped: the index answers, the engine runs jobs, the scheduler still works, the log sink is the desktop's.
Assert.Same(sink, Log.Sink);
var after = await desktop.Engine.EnqueueAsync(JobKind.Scan, [desktop.Archive.Id], "after");
Assert.Equal(JobState.Done, (await desktop.WaitAsync(after.Id)).State);
Assert.NotNull(await desktop.Scheduler.ListAsync(context.Cancellation));
}
[Test]
public async Task TheServerAddsOnlyItsOwnSystemSchedulesToTheDesktops()
{
await using var desktop = await DesktopFixture.StartAsync(context);
var before = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType<string>().ToHashSet();
await using var shared = await desktop.ShareAsync();
var after = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType<string>().ToHashSet();
Assert.SequenceEqual([ServerScheduleHost.AuditCleanup, ServerScheduleHost.UploadCleanup], after.Except(before).Order(StringComparer.Ordinal));
Assert.SequenceEqual([DesktopFixture.ScanKey], before);
}
[Test]
public async Task ItServesTheDesktopsArchiveAloneAndHidesItsPrivateJobs()
{
await using var desktop = await DesktopFixture.StartAsync(context);
var mine = await desktop.SequenceAsync(desktop.Archive);
var other = await desktop.Archives.CreateAsync(context.CreateTempDirectory("other"), "Another archive", cancellationToken: context.Cancellation);
var theirs = await desktop.SequenceAsync(other);
var workspace = await desktop.Engine.EnqueueAsync(JobKind.WorkspaceCopy, [mine.Id], "workspace");
await using var shared = await desktop.ShareAsync();
using var admin = await desktop.AdminAsync(shared);
using (var ok = await admin.GetAsync($"/api/v1/sequences/{mine.Id}")) Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
foreach (var path in new[] { $"/api/v1/sequences/{theirs.Id}", $"/api/v1/sequences/{theirs.Id}/projects", $"/api/v1/sequences/{theirs.Id}/frames" })
{
using var hidden = await admin.GetAsync(path);
Assert.Equal(HttpStatusCode.NotFound, hidden.StatusCode, path);
}
using (var job = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("thumbs", [theirs.Id], null), ProtocolJson.Default.CreateJobRequest))
Assert.Equal(HttpStatusCode.NotFound, job.StatusCode);
var listed = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/jobs", ProtocolJson.Default.PageJobDto));
Assert.False(listed.Items.Any(j => j.Id == workspace.Id), "a workspace job is the desktop's own");
using (var get = await admin.GetAsync($"/api/v1/jobs/{workspace.Id}")) Assert.Equal(HttpStatusCode.NotFound, get.StatusCode);
using (var cancel = await admin.PostAsync($"/api/v1/jobs/{workspace.Id}/cancel", null)) Assert.Equal(HttpStatusCode.NotFound, cancel.StatusCode);
Assert.Equal(JobState.Queued, (await desktop.Database.Jobs.GetAsync(workspace.Id))!.State);
}
[Test]
public async Task TheDesktopOwnsItsSettingsAndTheFirstAdministratorsPasswordIsInTheShareFolder()
{
await using var desktop = await DesktopFixture.StartAsync(context);
Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", "from a variable");
try
{
var options = ServerOptions.ForHosted(desktop.ShareData, desktop.Settings with { ServerName = "Studio PC" });
Assert.Equal("Studio PC", options.ServerName);
Assert.True(options.Hosted, "hosted");
Assert.Contains(nameof(ServerOptions.HttpsPort), options.Locked);
Assert.Equal(ServerOptions.DesktopLock, options.LockedBy[nameof(ServerOptions.Parallelism)]);
Assert.False(options.Locked.Contains(nameof(ServerOptions.TokenLifetimeDays)), "the admin panel owns the token lifetime");
Assert.Equal(Microsoft.Extensions.Logging.LogLevel.None, options.ConsoleLogLevel);
}
finally
{
Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", null);
}
await using var shared = await desktop.ShareAsync();
Assert.True(File.Exists(shared.AdminPasswordFile), "the temporary password's file");
Assert.Equal(Path.Combine(desktop.ShareData, AdminBootstrap.PasswordFileName), shared.AdminPasswordFile);
Assert.NotNull(shared.AdminPassword());
using var admin = await desktop.AdminAsync(shared);
Assert.Null(shared.AdminPassword());
var settings = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/server/settings", ProtocolJson.Default.ServerSettingsDto));
Assert.Equal(ServerOptions.DesktopLock, settings.LockedBy["HttpsPort"]);
}
[Test]
public async Task ClientsAreKeptForFiveMinutes()
{
var time = new ManualTime(DateTimeOffset.Parse("2026-11-15T10:00:00Z", System.Globalization.CultureInfo.InvariantCulture));
var activity = new ClientActivity(time);
var user = new User { Id = Guid.CreateVersion7(), Username = "alberto", PasswordHash = "x", Role = UserRole.Editor, Created = time.GetUtcNow() };
activity.Record(new Caller(user, "hash", CredentialSource.Bearer, "Chronos Uploader (Studio)"), "192.168.1.20");
activity.Record(new Caller(user, "hash", CredentialSource.Cookie, null), "192.168.1.21");
var seen = activity.Recent();
Assert.Count(2, seen);
Assert.Contains("Chronos Uploader (Studio)", seen.Select(s => s.Client));
Assert.Contains(ClientActivity.AdminPanel, seen.Select(s => s.Client));
time.Advance(TimeSpan.FromMinutes(6));
Assert.Count(0, activity.Recent());
}
[Test]
public void ARenderNeverKeepsTheExportFolderAClientChose()
{
var parameters = new RenderJobParameters("1080p", """{"preset":"1080p","Folder":"C:\\Users\\someone","nameTemplate":"{title}"}""", "h264", 1920, 1080, false, null);
var stripped = JobEndpoints.WithoutExportFolder(parameters);
Assert.False(stripped.PresetJson.Contains("Users", StringComparison.Ordinal), stripped.PresetJson);
Assert.True(stripped.PresetJson.Contains("nameTemplate", StringComparison.Ordinal), stripped.PresetJson);
var plain = parameters with { PresetJson = """{"preset":"1080p"}""" };
Assert.Same(plain, JobEndpoints.WithoutExportFolder(plain));
}
[Test]
public void TheServiceSwitchesAreGone()
{
var parsed = ServerCommandLine.Parse(["--service", "--install-service", "--uninstall-service"]);
Assert.Equal(ServerCommand.Run, parsed.Command);
Assert.SequenceEqual(["--service", "--install-service", "--uninstall-service"], parsed.HostArguments);
Assert.False(ServerCommandLine.Usage.Contains("service", StringComparison.OrdinalIgnoreCase), "usage names a service");
}
/// <summary>A clock the test moves.</summary>
private sealed class ManualTime(DateTimeOffset start) : TimeProvider
{
private DateTimeOffset _now = start;
public override DateTimeOffset GetUtcNow() => _now;
public void Advance(TimeSpan by) => _now += by;
}
}
/// <summary>
/// What Chronos Desktop has when it shares its library: a SQLite index, the archive and processing services (managed
/// codecs), a started job engine and a started scheduler with one system schedule of its own.
/// </summary>
internal sealed class DesktopFixture : IAsyncDisposable
{
public const string WorkerId = "STUDIO-PC";
public const string ScanKey = "archive-scan";
private readonly TestContext _context;
private DesktopFixture(TestContext context, string root, ChronosDatabase db, ArchiveService archives, ProcessingService processing, JobEngine engine,
Scheduler scheduler, Archive archive)
{
_context = context;
Root = root;
Database = db;
Archives = archives;
Processing = processing;
Engine = engine;
Scheduler = scheduler;
Archive = archive;
}
public string Root { get; }
public ChronosDatabase Database { get; }
public ArchiveService Archives { get; }
public ProcessingService Processing { get; }
public JobEngine Engine { get; }
public Scheduler Scheduler { get; }
public Archive Archive { get; }
public string ShareData => Path.Combine(Root, "data", "server");
public HostedSettings Settings => new(null, 0, 0, null, null, Discovery: false, Archive.RootPath, null, 2, false, new Dictionary<string, string>(), "en",
LogLevel.Warning, 14, 50, 1024, LogRotation.Daily, 4);
public static async Task<DesktopFixture> StartAsync(TestContext context)
{
var root = context.CreateTempDirectory("desktop");
Directory.CreateDirectory(Path.Combine(root, "data"));
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(root, "data", "chronos.db")), context.Cancellation);
var archiveOptions = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Parallelism = () => 2 };
var archives = new ArchiveService(db, archiveOptions);
var processing = new ProcessingService(db, new ProcessingOptions { Archive = archiveOptions, Encoders = [new ManagedEncoderProvider()] });
var archive = await archives.CreateAsync(Path.Combine(root, "archive"), "Studio", cancellationToken: context.Cancellation);
var handlers = archives.CreateJobHandlers().Concat(processing.CreateJobHandlers()).ToList();
var engine = new JobEngine(db, handlers, new JobEngineOptions
{
WorkerId = WorkerId,
Kinds = [.. handlers.Select(h => h.Kind).Distinct()],
PollInterval = TimeSpan.FromMilliseconds(100),
});
await engine.StartAsync(context.Cancellation);
var scheduler = new Scheduler(db, engine);
await scheduler.StartAsync(new Host(archives, archive), context.Cancellation);
return new DesktopFixture(context, root, db, archives, processing, engine, scheduler, archive);
}
public async Task<HostedServer> ShareAsync()
{
var options = ServerOptions.ForHosted(ShareData, Settings);
options.LoginAttemptsPerMinute = 1000;
var server = ServerHost.BuildHosted(options, new HostedEngine(Database, Archives, Processing, Engine, Scheduler, Archive));
await server.StartAsync(_context.Cancellation);
return server;
}
public HttpClient Client(HostedServer server, string? token = null)
{
var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.HttpPort}"), Timeout = TimeSpan.FromSeconds(60) };
if (token is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return client;
}
/// <summary>The first administrator, signed in with its temporary password, which it then replaces.</summary>
public async Task<HttpClient> AdminAsync(HostedServer server)
{
var temporary = server.AdminPassword() ?? throw new InvalidOperationException("No temporary password");
using var anonymous = Client(server);
using var login = await anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", temporary, "tests"), ProtocolJson.Default.LoginRequest);
login.EnsureSuccessStatusCode();
var token = (await login.Content.ReadFromJsonAsync(ProtocolJson.Default.LoginResponse))!.Token!;
var client = Client(server, token);
using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(temporary, "a-good-password-1"),
ProtocolJson.Default.ChangePasswordRequest);
changed.EnsureSuccessStatusCode();
return client;
}
public async Task<Sequence> SequenceAsync(Archive archive)
{
var sequence = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = archive.Id,
Title = "Roof " + archive.Name,
Folder = string.Empty,
Origin = SequenceOrigin.Server,
UpdatedAt = DateTimeOffset.UtcNow,
};
await Database.Sequences.UpsertAsync(sequence, _context.Cancellation);
return sequence;
}
public async Task<Job> WaitAsync(Guid id)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (true)
{
if (await Database.Jobs.GetAsync(id, _context.Cancellation) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } job) return job;
Assert.True(DateTime.UtcNow < until, "the job did not finish");
await Task.Delay(50, _context.Cancellation);
}
}
public async ValueTask DisposeAsync()
{
await Scheduler.DisposeAsync();
await Engine.DisposeAsync();
await Database.DisposeAsync();
}
/// <summary>A desktop's schedule host: one archive scan schedule, the archive service's clean-up steps.</summary>
private sealed class Host(ArchiveService archives, Archive archive) : IScheduleHost
{
public TimeZoneInfo TimeZone => TimeZoneInfo.Utc;
public IReadOnlyList<SystemSchedule> SystemSchedules =>
[new(ScanKey, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(10, RecurrenceUnit.Minutes), CatchUp: false)];
public IReadOnlyList<string> CleanupSteps => [.. archives.CleanupSteps.Select(s => s.Name)];
public bool DeepAnalysisAfterScan => false;
public ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken) => ValueTask.FromResult<Archive?>(archive);
public string? Unavailable(string action) => null;
}
}
@@ -1,152 +0,0 @@
using System.Diagnostics.Eventing.Reader;
using System.Security.AccessControl;
using System.Security.Principal;
using Chronos.Server.Hosting;
using Chronos.Server.Hosting.Windows;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
public sealed class WindowsServiceTests(TestContext context)
{
[Test]
public void CommandSwitchesAreParsedAndTheRestPassedOn()
{
Assert.Equal(ServerCommand.Run, ServerCommandLine.Parse([]).Command);
var service = ServerCommandLine.Parse(["--service", "--urls", "x"]);
Assert.Equal(ServerCommand.Service, service.Command);
Assert.SequenceEqual(["--urls", "x"], service.HostArguments);
Assert.Equal(ServerCommand.InstallService, ServerCommandLine.Parse(["--install-service"]).Command);
Assert.Equal(ServerCommand.UninstallService, ServerCommandLine.Parse(["--uninstall-service"]).Command);
Assert.Equal(ServerCommand.HealthCheck, ServerCommandLine.Parse(["--healthcheck"]).Command);
Assert.Equal(ServerCommand.Help, ServerCommandLine.Parse(["/?"]).Command);
Assert.NotNull(ServerCommandLine.Parse(["--install-service", "--uninstall-service"]).Error);
Assert.Null(ServerCommandLine.Parse(["--service", "--service"]).Error);
}
[Test]
public void StatusReportsFollowTheServiceControlManagerRules()
{
var tracker = new ServiceStatusTracker();
var start = tracker.StartPending(60_000);
Assert.Equal((ServiceState.StartPending, 0u, 1u, 60_000u), (start.State, start.ControlsAccepted, start.CheckPoint, start.WaitHintMilliseconds));
Assert.Equal(2u, tracker.StartPending(60_000).CheckPoint);
var running = tracker.Running();
Assert.Equal((ServiceState.Running, ServiceStatusTracker.AcceptStop | ServiceStatusTracker.AcceptShutdown, 0u), (running.State, running.ControlsAccepted, running.CheckPoint));
Assert.Throws<InvalidOperationException>(() => tracker.Running());
Assert.Equal(1u, tracker.StopPending(35_000).CheckPoint);
Assert.Equal(2u, tracker.StopPending(35_000).CheckPoint);
var stopped = tracker.Stopped(0);
Assert.Equal((ServiceState.Stopped, 0u, 0u), (stopped.State, stopped.ControlsAccepted, stopped.CheckPoint));
Assert.Throws<InvalidOperationException>(() => tracker.StopPending(1));
Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode);
}
[Test]
public void AServiceFailureLeadsWithTheReasonTheServerGave()
{
var refused = new InvalidOperationException(@"C:\ProgramData\Chronos Server belongs to PC\ada, not to SYSTEM, Administrators or the account Chronos Server runs as.");
var text = ServiceEventLog.Describe("Chronos Server did not start:", refused);
Assert.True(text.StartsWith(@"Chronos Server did not start: C:\ProgramData\Chronos Server belongs to PC\ada", StringComparison.Ordinal), text);
Assert.Contains("System.InvalidOperationException", text);
// ReportEvent refuses a longer string: the text is cut, never between the halves of a surrogate pair.
var cut = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength)));
Assert.Equal(ServiceEventLog.MaxLength, cut.Length);
Assert.True(cut.EndsWith("a\u2026", StringComparison.Ordinal), cut[^5..]);
var pair = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength - 4) + "\uD83D\uDE00" + new string('b', 99)));
Assert.Equal(ServiceEventLog.MaxLength - 1, pair.Length);
Assert.True(pair.EndsWith("a\u2026", StringComparison.Ordinal), pair[^5..]);
}
[Test]
[WindowsOnly]
public void AServiceFailureReachesTheApplicationEventLog()
{
if (!OperatingSystem.IsWindows()) return;
// Written as a source of its own, so a test run never looks like a failed service in Event Viewer.
const string source = "Chronos.Server.Tests";
var marker = source + " " + Guid.NewGuid().ToString("N");
Assert.True(ServiceEventLog.Error(source, ServiceEventLog.StartFailed, marker), "the Application log takes the event");
var filter = $"*[System[Provider[@Name='{source}'] and EventID={ServiceEventLog.StartFailed}]]";
var query = new EventLogQuery("Application", PathType.LogName, filter) { ReverseDirection = true };
for (var attempt = 0; attempt < 50; attempt++)
{
using (var reader = new EventLogReader(query))
{
for (var read = 0; read < 100 && reader.ReadEvent() is { } record; read++)
{
using (record)
{
// The event's one string, which Event Viewer shows whole.
if (record.Properties.Count != 1 || record.Properties[0].Value as string != marker) continue;
Assert.Equal((byte?)2, record.Level, "an error");
return;
}
}
}
Thread.Sleep(100);
}
Assert.Fail($"No {source} event carries '{marker}'.");
}
[Test]
[WindowsOnly]
public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()
{
if (!OperatingSystem.IsWindows()) return;
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Chronos", "Chronos.Server.exe")));
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles));
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Chronos"));
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Chronos")));
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Chronos")));
// The test build is not under Program Files: registering it is refused, naming the folder.
Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation()));
}
[Test]
[WindowsOnly]
public void AnyFileOrdinaryUsersCanChangeIsFound()
{
if (!OperatingSystem.IsWindows()) return;
using var identity = WindowsIdentity.GetCurrent();
if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator");
var folder = new DirectoryInfo(context.CreateTempDirectory("program"));
File.WriteAllBytes(Path.Combine(folder.FullName, "Chronos.Server.exe"), [1]);
var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Chronos.Core.resources.dll"));
File.WriteAllBytes(satellite.FullName, [1]);
// Like Program Files: administrators may change the folder, users only read it.
var locked = new DirectorySecurity();
locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! })
locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow));
locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything,
PropagationFlags.None, AccessControlType.Allow));
folder.SetAccessControl(locked);
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true));
// One satellite assembly users may replace is enough: the service would load it as SYSTEM.
var open = satellite.GetAccessControl();
open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow));
satellite.SetAccessControl(open);
Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true));
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false));
}
[Test]
[WindowsOnly]
public void TheDispatcherDeclinesAConsoleProcess()
{
if (!OperatingSystem.IsWindows()) return;
var built = false;
Assert.False(WindowsServiceHost.Run(() =>
{
built = true;
throw new InvalidOperationException("never built outside the SCM");
}));
Assert.False(built);
}
}