using System.IO; using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Text; using Chronos.Core.Localization; using Chronos.Core.Updates; using Chronos.Testing; using Chronos.Ui.Mvvm; using Chronos.Ui.Updates; using Chronos.Uploader.Infrastructure; using Chronos.Uploader.Shell; namespace Chronos.App.Tests.Uploader; /// /// The Uploader's update check (owner review 5, #64): on by default, also for a 1.0 settings file; skipped on start when /// Chronos Desktop sits beside it while Check now still works; Check now reads the releases feed; Download verifies the /// single setup against SHA256SUMS and Show setup reveals it. /// public sealed class UploaderUpdatesTests(TestContext context) { private const string Repository = "https://gitea.example/o/r"; private const string SetupName = "Chronos-Setup-1.1.0.exe"; private static readonly byte[] Setup = Encoding.UTF8.GetBytes("the single setup of Chronos 1.1.0"); [Test] public void CheckOnStartIsOnByDefaultAndA10SettingsFileKeepsIt() { Assert.True(new UploaderSettings().CheckForUpdates); var folder = context.CreateTempDirectory(); var path = Path.Combine(folder, "uploader.json"); // An Uploader 1.0 settings file: no checkForUpdates key. File.WriteAllText(path, """ { "serverUrl": "https://nas.local:8443/", "username": "alberto", "bandwidthLimit": 50, "minimizeToTray": true, "deleteAfterUpload": false, "target": "Sessions", "watchFolders": [], "theme": "Dark" } """); var loaded = UploaderSettings.Load(path); Assert.True(loaded.CheckForUpdates, "a 1.0 file loads with the check on"); Assert.Equal("alberto", loaded.Username); loaded.CheckForUpdates = false; loaded.Save(path); Assert.Contains("\"checkForUpdates\": false", File.ReadAllText(path)); Assert.False(UploaderSettings.Load(path).CheckForUpdates, "the opt-out survives a restart"); } [Test] public void TheDesktopIsFoundBesideTheUploader() { var folder = context.CreateTempDirectory(); Assert.False(UploaderEnvironment.IsDesktopBeside(folder)); File.WriteAllText(Path.Combine(folder, UploaderEnvironment.DesktopExecutable), "desktop"); Assert.True(UploaderEnvironment.IsDesktopBeside(folder)); } [Test] public void TheStartUpCheckIsSkippedBesideTheDesktopWhileCheckNowStillWorks() => SingleThreadedContext.Run(async () => { Assert.True(UpdatesViewModel.ChecksOnStart(enabled: true, desktopBeside: false)); Assert.False(UpdatesViewModel.ChecksOnStart(enabled: true, desktopBeside: true)); Assert.False(UpdatesViewModel.ChecksOnStart(enabled: false, desktopBeside: false)); var feed = new Feed().Release("v1.1.0"); using var vm = Notice(feed, out _); ReleaseInfo? found = null; vm.Found += r => found = r; await vm.CheckOnStartAsync(desktopBeside: true); Assert.Equal(0, feed.FeedRequests); Assert.Equal(UpdateState.Unknown, vm.State); Assert.Null(vm.StatusText); await RunAsync(vm.CheckCommand); Assert.Equal(1, feed.FeedRequests); Assert.Equal(Loc.L("Uploader.Updates.Available", "1.1.0"), vm.StatusText); Assert.Null(found, "Check now reports in the panel, not in a toast"); }); [Test] public void TheStartUpCheckFollowsTheOptOutAndOffersANewerRelease() => SingleThreadedContext.Run(async () => { var feed = new Feed().Release("v1.1.0"); var settings = new UploaderSettings { CheckForUpdates = false }; var saves = 0; using var vm = new UpdatesViewModel(Host(feed, context.CreateTempDirectory(), []), settings, () => saves++); ReleaseInfo? found = null; vm.Found += r => found = r; await vm.CheckOnStartAsync(desktopBeside: false); Assert.Equal(0, feed.FeedRequests); vm.CheckOnStart = true; Assert.True(settings.CheckForUpdates); Assert.Equal(1, saves); await vm.CheckOnStartAsync(desktopBeside: false); Assert.Equal(1, feed.FeedRequests); Assert.Equal("v1.1.0", found?.Tag); Assert.True(vm.IsDownloadOffered); }); [Test] public void CheckNowShowsUpToDateAvailableOrFailed() => SingleThreadedContext.Run(async () => { var current = new Feed().Release("v1.0.0"); using (var vm = Notice(current, out _)) { await RunAsync(vm.CheckCommand); Assert.Equal(UpdateState.UpToDate, vm.State); Assert.Equal(Loc.L("Uploader.Updates.UpToDate"), vm.StatusText); Assert.Equal(Loc.L("Tooltips.Uploader.Updates.UpToDate"), vm.StatusToolTip); Assert.False(vm.IsDownloadOffered); } var newer = new Feed().Release("v1.1.0"); using (var vm = Notice(newer, out _)) { await RunAsync(vm.CheckCommand); Assert.Equal(Loc.L("Uploader.Updates.Available", "1.1.0"), vm.StatusText); Assert.Equal(Loc.L("Tooltips.Uploader.Updates.Available"), vm.StatusToolTip); Assert.True(vm.IsDownloadOffered); Assert.Contains("SHA-256", vm.DownloadToolTip); } foreach (var status in new[] { HttpStatusCode.NotFound, HttpStatusCode.InternalServerError }) { var broken = new Feed { FeedStatus = status }; using var vm = Notice(broken, out _); await RunAsync(vm.CheckCommand); Assert.Equal(UpdateState.Failed, vm.State); Assert.Equal(Loc.L("Uploader.Updates.Failed"), vm.StatusText); Assert.Equal(Loc.L("Tooltips.Uploader.Updates.Failed"), vm.StatusToolTip); } }); [Test] public void DownloadVerifiesTheSetupAndShowSetupRevealsIt() => SingleThreadedContext.Run(async () => { var feed = new Feed().Release("v1.1.0"); using var vm = Notice(feed, out var revealed); await RunAsync(vm.CheckCommand); await RunAsync(vm.DownloadCommand); Assert.Equal(UpdateState.Downloaded, vm.State); Assert.True(vm.IsReady); Assert.Equal(Loc.L("Uploader.Updates.Ready", "1.1.0"), vm.StatusText); var path = Assert.NotNull(vm.PackagePath); Assert.Equal(SetupName, Path.GetFileName(path)); Assert.SequenceEqual(Setup, File.ReadAllBytes(path)); Assert.SequenceEqual(new[] { path }, revealed); Assert.True(vm.ShowSetupCommand.CanExecute(null)); vm.ShowSetupCommand.Execute(null); Assert.SequenceEqual(new[] { path, path }, revealed); }); [Test] public void ASetupThatDoesNotMatchItsChecksumIsRefused() => SingleThreadedContext.Run(async () => { var feed = new Feed { WrongChecksum = true }.Release("v1.1.0"); using var vm = Notice(feed, out var revealed); await RunAsync(vm.CheckCommand); await RunAsync(vm.DownloadCommand); Assert.Equal(UpdateState.NotVerified, vm.State); Assert.Equal(Loc.L("Uploader.Updates.NotVerified"), vm.StatusText); Assert.Null(vm.PackagePath); Assert.Empty(revealed); Assert.False(vm.ShowSetupCommand.CanExecute(null)); Assert.True(vm.IsDownloadOffered, "the download can be tried again"); }); [Test] public void TheCaptureNoticeNeverTouchesTheNetwork() => SingleThreadedContext.Run(async () => { using var vm = new UpdatesViewModel(UploaderUpdates.Offline("1.0.0"), new UploaderSettings(), () => { }); await vm.CheckOnStartAsync(desktopBeside: false); await RunAsync(vm.CheckCommand); Assert.Equal(UpdateState.Unknown, vm.State); }); private UpdatesViewModel Notice(Feed feed, out List revealed) { revealed = []; return new UpdatesViewModel(Host(feed, context.CreateTempDirectory(), revealed), new UploaderSettings(), () => { }); } private static UpdateHost Host(Feed feed, string downloadRoot, List revealed) { var http = new HttpClient(feed, disposeHandler: false); return UploaderUpdates.Host(http, http, Repository, "1.0.0", portable: false, downloadRoot, _ => { }, revealed.Add); } private static async Task RunAsync(System.Windows.Input.ICommand command) { var async = (AsyncRelayCommand)command; async.Execute(null); for (var i = 0; i < 500 && async.IsRunning; i++) await Task.Delay(10); Assert.False(async.IsRunning, "the command did not finish"); } /// The releases API, the setup and its SHA256SUMS, served from memory. private sealed class Feed : HttpMessageHandler { private string _json = "[]"; private string _sums = string.Empty; private string _tag = string.Empty; public HttpStatusCode FeedStatus { get; init; } = HttpStatusCode.OK; public bool WrongChecksum { get; init; } public int FeedRequests { get; private set; } public Feed Release(string tag) { _tag = tag; var hash = WrongChecksum ? new string('0', 64) : Convert.ToHexStringLower(SHA256.HashData(Setup)); _sums = $"{hash} {SetupName}\n"; _json = $$""" [{"tag_name":"{{tag}}","draft":false,"prerelease":false,"html_url":"{{Repository}}/releases/tag/{{tag}}", "assets":[{"name":"{{SetupName}}","size":{{Setup.Length}},"browser_download_url":"x"}, {"name":"SHA256SUMS","size":{{_sums.Length}},"browser_download_url":"x"}]}] """; return this; } protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var path = request.RequestUri!.AbsolutePath; if (path == "/api/v1/repos/o/r/releases") { FeedRequests++; return Answer(FeedStatus, Encoding.UTF8.GetBytes(_json)); } if (path == $"/o/r/releases/download/{_tag}/SHA256SUMS") return Answer(HttpStatusCode.OK, Encoding.UTF8.GetBytes(_sums)); if (path == $"/o/r/releases/download/{_tag}/{SetupName}") return Answer(HttpStatusCode.OK, Setup); return Answer(HttpStatusCode.NotFound, []); } private static Task Answer(HttpStatusCode status, byte[] body) => Task.FromResult(new HttpResponseMessage(status) { Content = new ByteArrayContent(body) }); } }