fix: full verification against the brief — 137 confirmed findings fixed over six passes #4

Merged
Alby96 merged 169 commits from claude/keen-knuth-uhxv8w into main 2026-10-13 12:10:04 +02:00
15 changed files with 218 additions and 31 deletions
Showing only changes of commit 4850af2443 - Show all commits

No files matched your search

+1
View File
@@ -17,6 +17,7 @@
<data name="Archive.Blocked.NoChanges" xml:space="preserve"><value>Nothing would change.</value><comment>long</comment></data>
<data name="Archive.Blocked.NotOnline" xml:space="preserve"><value>The archive must be online and writable.</value><comment>long</comment></data>
<data name="Archive.Blocked.Planning" xml:space="preserve"><value>Wait for the dry run.</value><comment>long</comment></data>
<data name="Archive.Blocked.Reading" xml:space="preserve"><value>Wait until the archive is read.</value><comment>long</comment></data>
<data name="Archive.Blocked.Searching" xml:space="preserve"><value>A search is running; cancel it or wait.</value><comment>long</comment></data>
<data name="Archive.Chart.Cameras" xml:space="preserve"><value>By camera</value></data>
<data name="Archive.Chart.Formats" xml:space="preserve"><value>By format</value></data>
+1
View File
@@ -17,6 +17,7 @@
<data name="Archive.Blocked.NoChanges" xml:space="preserve"><value>Non cambierebbe nulla.</value></data>
<data name="Archive.Blocked.NotOnline" xml:space="preserve"><value>L'archivio deve essere raggiungibile e scrivibile.</value></data>
<data name="Archive.Blocked.Planning" xml:space="preserve"><value>Attendi la simulazione.</value></data>
<data name="Archive.Blocked.Reading" xml:space="preserve"><value>Attendi la lettura dell'archivio.</value></data>
<data name="Archive.Blocked.Searching" xml:space="preserve"><value>Una ricerca è in corso: annullala o attendi.</value></data>
<data name="Archive.Chart.Cameras" xml:space="preserve"><value>Per fotocamera</value></data>
<data name="Archive.Chart.Formats" xml:space="preserve"><value>Per formato</value></data>
+11
View File
@@ -0,0 +1,11 @@
using System.IO;
namespace Titano.App.Editor;
/// <summary>
/// A sequence the editor could not read or store, for a reason the editor words itself in one localized sentence (the
/// sequence is gone, its project cannot be read, the account may not change it, the settings kept changing elsewhere,
/// the frames changed on the server). A toast shows <see cref="Exception.Message"/> as it is (BRIEF §0.2 rule 6); any
/// other failure is mapped to a catalog sentence by its cause.
/// </summary>
public class EditorException(string message, Exception? innerException = null) : IOException(message, innerException);
+3 -2
View File
@@ -832,12 +832,13 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// <summary>
/// The first failure of a run of failed saves (they are retried until one succeeds); Retry tries at once. Why it
/// failed is one localized sentence (BRIEF §0.2 rule 6); the exception's own text is in the log.
/// failed is one localized sentence (BRIEF §0.2 rule 6): the editor's own (frames changed, changed elsewhere, gone,
/// unreadable, not allowed), else the cause on the server or in the archive; the exception's own text is in the log.
/// </summary>
private void OnSaveFailed(Exception ex) => Shell.ShowToast(new Toast
{
Title = Loc.L("Editor.Save.Failed"),
Message = Session.IsRemote ? ErrorText.ForServer(ex) : ArchiveFailures.Cause(ex),
Message = ex is EditorException ? ex.Message : Session.IsRemote ? ErrorText.ForServer(ex) : ArchiveFailures.Cause(ex),
IsError = true,
ActionText = Loc.L("Editor.Save.Retry"),
ActionToolTip = Loc.L("Tooltips.Editor.Save.Retry"),
+2 -1
View File
@@ -41,7 +41,7 @@ public interface ISequenceSource : IAsyncDisposable
event Action<Job>? JobChanged;
/// <summary>Everything the editor shows of the sequence; read off the UI thread.</summary>
/// <exception cref="InvalidDataException">The project cannot be read (corrupt, or written by a newer Titano).</exception>
/// <exception cref="EditorException">The sequence is gone, or its project cannot be read (corrupt, or written by a newer Titano).</exception>
Task<SequenceContent> LoadAsync(CancellationToken cancellationToken);
/// <summary>
@@ -55,6 +55,7 @@ public interface ISequenceSource : IAsyncDisposable
/// change made meanwhile by someone else is kept where this edit left the value alone (<see cref="ProjectMerge"/>).
/// Returns the stored project.
/// </summary>
/// <exception cref="EditorException">The editor's own reason the project was not stored, worded for the user.</exception>
Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken);
/// <summary>Queues an analysis or render job for the sequence; returns the job id.</summary>
+5 -5
View File
@@ -146,7 +146,7 @@ public sealed class LocalSequenceSource : ISequenceSource
throw Missing();
// The settings moved in the index meanwhile (server API): merge again on top of them; the file follows the next write.
case SequenceEditOutcome.Conflict when attempt == SaveAttempts:
throw new IOException(Loc.L("Editor.Error.SaveConflict"));
throw new EditorException(Loc.L("Editor.Error.SaveConflict"));
}
}
}, cancellationToken);
@@ -175,7 +175,7 @@ public sealed class LocalSequenceSource : ISequenceSource
}
/// <summary>The settings in force: the index copy, else <c>project.json</c>, else defaults.</summary>
/// <exception cref="InvalidDataException">The settings are not a project or come from a newer Titano.</exception>
/// <exception cref="EditorException">The settings are not a project or come from a newer Titano.</exception>
internal static ProjectSettings ReadProject(Sequence sequence, SequencePaths folder)
{
var json = sequence.SettingsJson ?? (File.Exists(folder.ProjectPath) ? File.ReadAllText(folder.ProjectPath) : null);
@@ -184,9 +184,9 @@ public sealed class LocalSequenceSource : ISequenceSource
{
return ProjectSettings.FromJson(json);
}
catch (JsonException ex)
catch (Exception ex) when (ex is JsonException or InvalidDataException)
{
throw new InvalidDataException(Loc.L("Editor.Error.Project"), ex);
throw new EditorException(Loc.L("Editor.Error.Project"), ex);
}
}
@@ -212,5 +212,5 @@ public sealed class LocalSequenceSource : ISequenceSource
private void OnJobChanged(Job job) => JobChanged?.Invoke(job);
private static InvalidOperationException Missing() => new(Loc.L("Editor.Error.Missing"));
private static EditorException Missing() => new(Loc.L("Editor.Error.Missing"));
}
@@ -145,7 +145,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
var merged = changedThere ? ProjectMerge.Merge(basis, project, stored) : project;
if (ProjectMerge.SameValues(merged, stored)) return merged;
if (IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
if (_noEditRight) throw new InvalidOperationException(Loc.L("Editor.Error.RemoteReadOnly"));
if (_noEditRight) throw new EditorException(Loc.L("Editor.Error.RemoteReadOnly"));
if (changedThere && ProjectMerge.Conflicts(basis, project, stored) is { Count: > 0 } conflicts)
throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, conflicts);
var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged);
@@ -159,7 +159,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
// Changed on the server since this editor read it: merge again on top of the server's settings.
if (attempt == SaveAttempts) throw new IOException(Loc.L("Editor.Error.SaveConflict"), ex);
if (attempt == SaveAttempts) throw new EditorException(Loc.L("Editor.Error.SaveConflict"), ex);
var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
if (!SameFrames(manifest)) throw Outdated();
Volatile.Write(ref _stored, new Stored(Parse(manifest.SettingsJson), manifest.SettingsVersion));
@@ -359,7 +359,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
private Guid HeroFrameId(ProjectSettings project) =>
project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty;
/// <exception cref="InvalidDataException">The settings are not a project or come from a newer Titano.</exception>
/// <exception cref="EditorException">The settings are not a project or come from a newer Titano.</exception>
private static ProjectSettings Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings();
@@ -367,9 +367,9 @@ public sealed class RemoteSequenceSource : ISequenceSource
{
return ProjectSettings.FromJson(json);
}
catch (JsonException ex)
catch (Exception ex) when (ex is JsonException or InvalidDataException)
{
throw new InvalidDataException(Loc.L("Editor.Error.Project"), ex);
throw new EditorException(Loc.L("Editor.Error.Project"), ex);
}
}
@@ -398,7 +398,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
throw new EditorException(Loc.L("Editor.Error.Missing"), ex);
}
}
@@ -423,4 +423,4 @@ public sealed class ProjectConflictException(string message, ProjectSettings ser
/// The proxies of a server sequence are for frames the server no longer has (added or removed since they were fetched):
/// they must be fetched again before the sequence can be edited.
/// </summary>
public sealed class ProxiesOutdatedException(string message) : IOException(message);
public sealed class ProxiesOutdatedException(string message) : EditorException(message);
+2 -1
View File
@@ -211,7 +211,8 @@ public sealed class LibraryActions(ShellViewModel shell)
await client.CreateJobAsync(request);
shell.Notify(Loc.L("Library.QueuedServer", JobText.Kind(kind), label));
}
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException or TaskCanceledException)
// A certificate the server changed since sign-in is refused by the pin, not by the network (UntrustedCertificateException).
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException)
{
Log.Warning("library", $"Posting a {kind} job to {address} failed", ex);
shell.Notify(Loc.L("Library.Post.Failed"), ErrorText.ForServer(ex), isError: true);
+29 -9
View File
@@ -46,6 +46,10 @@ public sealed class ArchiveViewModel : SectionViewModel
private IReadOnlyList<Core.Model.Archive> _archives = [];
private Core.Model.Archive? _archive;
private ArchiveAvailability _availability = ArchiveAvailability.Offline;
/// <summary>The archive whose availability, figures and tree were read last: until it is the picked one, nothing acts on them.</summary>
private Guid? _readId;
private ArchiveStats? _stats;
private int _withoutProxies;
private ArchiveTree? _tree;
@@ -79,7 +83,7 @@ public sealed class ArchiveViewModel : SectionViewModel
_ = LoadAsync();
};
ScanCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Scan(a)), IsOnline);
RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), () => _archive is not null);
RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), IsRead);
VerifyCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Verify(a)), IsOnline);
AdoptCommand = new AsyncRelayCommand(AdoptAsync);
CopyFolderCommand = new RelayCommand(CopyFolder, () => _archive is not null);
@@ -128,11 +132,15 @@ public sealed class ArchiveViewModel : SectionViewModel
_orphans = null;
if (other)
{
// Until the picked archive is read, nothing of the previous one stays actionable: no tree to take a set
// from, no availability to allow a scan.
// Until the picked archive is read (IsRead), nothing of the previous one stays actionable: no tree to take
// a set from, no availability to allow a scan, no figures for the rebuild dialog or the health fixes, no
// search results. The tooltips say the archive is being read.
_search?.Cancel();
_tree = null;
_availability = ArchiveAvailability.Offline;
_stats = null;
_health = [];
RebuildRows();
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
}
_ = LoadAsync();
@@ -425,6 +433,7 @@ public sealed class ArchiveViewModel : SectionViewModel
if (!IsShowing(archive)) return;
_availability = availability;
_stats = stats;
_readId = archive.Id;
ShowFigures(stats, withoutProxies);
ShowTree(ArchiveTree.Build(archive, availability, sequences));
await LoadRecentAsync(db, archive);
@@ -444,7 +453,7 @@ public sealed class ArchiveViewModel : SectionViewModel
/// <summary>Opens the rebuild dialog (BRIEF §12.5) and counts, off the UI thread, the sidecars the rebuild will read.</summary>
public async Task<RebuildDialogViewModel?> OpenRebuildDialogAsync()
{
if (_archive is not { } archive || Services.Engine is not { } engine) return null;
if (_archive is not { } archive || !IsRead() || Services.Engine is not { } engine) return null;
var dialog = new RebuildDialogViewModel(archive, _availability, _stats?.Sequences ?? 0, async () =>
{
var request = ArchiveJobs.Rebuild(archive);
@@ -649,13 +658,19 @@ public sealed class ArchiveViewModel : SectionViewModel
// ---------------- Actions ----------------
private bool IsOnline() => _archive is not null && _availability == ArchiveAvailability.Online;
private bool IsOnline() => IsRead() && _availability == ArchiveAvailability.Online;
/// <summary>The picked archive's availability and figures are known (a slow volume is probed for seconds).</summary>
private bool IsRead() => _archive is { } archive && _readId == archive.Id;
/// <summary>The archive a read started with is still the one picked.</summary>
private bool IsShowing(Core.Model.Archive archive) => _archive?.Id == archive.Id;
/// <summary>A command's tooltip, or why it is disabled: these commands write to the archive or read all of it.</summary>
private string WhenOnline(string key) => _archive is null || IsOnline() ? Loc.L(key) : Loc.L("Archive.Blocked.NotOnline");
private string WhenOnline(string key) =>
_archive is null || IsOnline() ? Loc.L(key)
: !IsRead() ? Loc.L("Archive.Blocked.Reading")
: Loc.L("Archive.Blocked.NotOnline");
private bool HasSet() => _archive is not null && _tree is not null && Set().Count > 0;
@@ -853,7 +868,10 @@ public sealed class ArchiveViewModel : SectionViewModel
try
{
var groups = await Task.Run(() => archives.FindDuplicatesAsync(archive.Id, search.Token), search.Token);
Duplicates = DuplicateRows(groups, await db.Sequences.ListLocationsAsync(archive.Id, search.Token));
var locations = await db.Sequences.ListLocationsAsync(archive.Id, search.Token);
// Picking another archive cancels the search; one that ended just then is not the picked archive's.
if (!IsShowing(archive)) return;
Duplicates = DuplicateRows(groups, locations);
Log.Info("archive", $"Duplicates search in {archive.RootPath}: {groups.Count} group(s)");
}
catch (OperationCanceledException) when (search.IsCancellationRequested)
@@ -881,7 +899,9 @@ public sealed class ArchiveViewModel : SectionViewModel
try
{
var report = await Task.Run(() => archives.FindOrphansAsync(archive.Id, search.Token), search.Token);
Orphans = OrphanRows(report, await db.Sequences.ListLocationsAsync(archive.Id, search.Token));
var locations = await db.Sequences.ListLocationsAsync(archive.Id, search.Token);
if (!IsShowing(archive)) return;
Orphans = OrphanRows(report, locations);
Log.Info("archive", $"Orphans search in {archive.RootPath}: {report.UnindexedFiles} unlisted, {report.MissingFiles} missing, "
+ $"{report.MissingSequences.Count} rows without sidecar, {report.UnindexedFolders.Count} new folders");
}
@@ -189,6 +189,10 @@ public sealed class ArchiveScreenSmokeTests
Assert.Empty(archive.TreeRows);
Assert.False(archive.AnalyseSetCommand.CanExecute(null), "nothing of the first archive can be acted on while the picked one is read");
Assert.False(archive.ScanCommand.CanExecute(null), "the picked archive is not known to be online yet");
Assert.Equal(Loc.L("Archive.Blocked.Reading"), archive.ScanToolTip, "not yet read is not offline");
Assert.False(archive.RebuildCommand.CanExecute(null), "the rebuild dialog waits for the picked archive's own state and figures");
Assert.Null(await archive.OpenRebuildDialogAsync());
Assert.Empty(archive.Health);
await reading;
Assert.Equal(second.Id, archive.SelectedArchive!.Id);
@@ -196,6 +200,13 @@ public sealed class ArchiveScreenSmokeTests
Assert.True(archive.TreeRows[0].IsArchive);
Assert.False(archive.TreeRows.Any(r => r.Node.Kind == TreeNodeKind.Sequence), "the tree is the picked, empty archive's");
Assert.True(archive.ScanCommand.CanExecute(null), "the picked archive was probed: it is online");
Assert.Equal(Loc.L("Tooltips.Archive.Scan"), archive.ScanToolTip);
Assert.True(archive.RebuildCommand.CanExecute(null));
var rebuild = Assert.NotNull(await archive.OpenRebuildDialogAsync());
Assert.Equal(second.Id, rebuild.Archive.Id);
Assert.Equal(ArchiveAvailability.Online, rebuild.Availability, "the dialog shows the picked archive's availability");
Assert.Equal(0, rebuild.Indexed, "and its own index, not the first archive's");
rebuild.CloseCommand.Execute(null);
});
[Test]
@@ -1,5 +1,6 @@
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Windows;
using System.Windows.Controls;
@@ -255,6 +256,7 @@ public sealed class EditorSmokeTests
}
// A failed save says why in one localized sentence (BRIEF §0.2 rule 6); the exception's own text stays in the log.
// The editor's own reasons keep their sentence (they are I/O failures too, which would read "does not answer").
var toasts = new List<Toast>();
NotifyCollectionChangedEventHandler collect = (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
shell.PendingToasts.CollectionChanged += collect;
@@ -264,6 +266,10 @@ public sealed class EditorSmokeTests
{
(true, new HttpRequestException("No such host is known."), "Server.Error.Unreachable"),
(false, new UnauthorizedAccessException(@"Access to the path 'D:\Archive\.titano\sequence.json' is denied."), "Archive.Failed.Access"),
(true, new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged")), "Editor.Error.FramesChanged"),
(true, new EditorException(Loc.L("Editor.Error.RemoteReadOnly")), "Editor.Error.RemoteReadOnly"),
(false, new EditorException(Loc.L("Editor.Error.SaveConflict")), "Editor.Error.SaveConflict"),
(false, new EditorException(Loc.L("Editor.Error.Project"), new InvalidDataException("project.json version 9 is newer")), "Editor.Error.Project"),
})
{
toasts.Clear();
@@ -4,6 +4,7 @@ using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Localization;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Core.Project;
@@ -147,7 +148,8 @@ public sealed class ProjectStoreTests(TestContext context)
new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) });
var content = await source.LoadAsync(context.Cancellation);
Assert.True(await db.Sequences.DeleteAsync(sequenceId));
await Assert.ThrowsAsync<InvalidOperationException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
var gone = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.Missing"), gone.Message, "the toast shows the editor's own sentence");
}
}
@@ -178,8 +180,15 @@ public sealed class ProjectStoreTests(TestContext context)
var path = Path.Combine(root, "Synthetic", ".titano", "project.json");
File.WriteAllText(path, "{ not json");
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null);
await Assert.ThrowsAsync<InvalidDataException>(() => source.LoadAsync(context.Cancellation));
var unreadable = await Assert.ThrowsAsync<EditorException>(() => source.LoadAsync(context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.Project"), unreadable.Message);
Assert.Equal("{ not json", File.ReadAllText(path));
// A project written by a newer Titano reads the same, not as the parser's English sentence.
var newer = $"{{\"version\":{ProjectSettings.CurrentVersion + 1}}}";
File.WriteAllText(path, newer);
Assert.Equal(Loc.L("Editor.Error.Project"), (await Assert.ThrowsAsync<EditorException>(() => source.LoadAsync(context.Cancellation))).Message);
Assert.Equal(newer, File.ReadAllText(path));
}
}
@@ -5,6 +5,7 @@ using Titano.Core.Codecs.Jpeg;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Processing;
@@ -229,7 +230,8 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
return (theirs with { Camera = theirs.Camera with { OffsetX = offset } }).ToJson();
});
}
await Assert.ThrowsAsync<IOException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation));
var conflict = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.SaveConflict"), conflict.Message, "the toast shows the editor's own sentence");
Assert.False(api.Edits.Any(e => e.Accepted));
}
}
@@ -268,8 +270,9 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
// The source refuses a change as well; the same project is no change.
await Assert.ThrowsAsync<InvalidOperationException>(() =>
var refused = await Assert.ThrowsAsync<EditorException>(() =>
source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.RemoteReadOnly"), refused.Message);
Assert.True(ProjectMerge.SameValues(content.Project, await source.SaveProjectAsync(content.Project, content.Project, context.Cancellation)));
Assert.Empty(api.Edits);
}
@@ -366,8 +369,9 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
{
var content = await source.LoadAsync(context.Cancellation);
api.Gone = true;
await Assert.ThrowsAsync<InvalidOperationException>(() => source.LoadAsync(context.Cancellation));
await Assert.ThrowsAsync<InvalidOperationException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.Missing"), (await Assert.ThrowsAsync<EditorException>(() => source.LoadAsync(context.Cancellation))).Message);
var gone = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.Missing"), gone.Message);
}
}
@@ -1,3 +1,4 @@
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
@@ -9,7 +10,9 @@ using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Library;
@@ -180,6 +183,46 @@ public sealed class LibraryScreenSmokeTests
static string Readout(LibraryViewModel library) => library.TimelineBands[0].ToolTips!.First(t => !string.IsNullOrEmpty(t))!;
});
/// <summary>
/// A remote card's Analyse posted to a server whose certificate changed since sign-in: the pin refuses it before
/// anything is sent, and the error toast says so (it used to escape the action unreported).
/// </summary>
[Test]
public Task APostRefusedByThePinnedCertificateSaysSo() => ScreenHost.RunAsync(async () =>
{
using var server = new UntrustedTlsEndpoint();
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
app.Services.Settings.ServerUrl = server.Address.ToString();
await app.Shell.Services.Server.RestoreAsync();
var actions = new LibraryActions(app.Shell);
Assert.True(actions.CanPost, "signed in to the endpoint (the sample's own certificate was trusted at sign-in)");
var toasts = new List<Toast>();
NotifyCollectionChangedEventHandler collect = (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
app.Shell.PendingToasts.CollectionChanged += collect;
try
{
var remote = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.Empty,
Folder = "Harbour",
Title = "Harbour sunset",
Origin = SequenceOrigin.Server,
SyncState = SyncState.RemoteOnly,
};
await actions.AnalyseAsync([remote]);
}
finally
{
app.Shell.PendingToasts.CollectionChanged -= collect;
}
var toast = Assert.Contains(toasts, t => t.Title == Loc.L("Library.Post.Failed"));
Assert.Equal(Loc.L("Server.Error.Untrusted"), toast.Message);
Assert.True(toast.IsError);
});
private static void Press(UIElement target, Key key) =>
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent });
@@ -0,0 +1,78 @@
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Titano.App.Tests.Library;
/// <summary>
/// A TLS endpoint on loopback with a self-signed certificate no client trusted (a server whose certificate changed since
/// sign-in): the client's pinning refuses every handshake, so nothing is ever sent.
/// </summary>
internal sealed class UntrustedTlsEndpoint : IDisposable
{
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private readonly X509Certificate2 _certificate;
private readonly CancellationTokenSource _stop = new();
private readonly Task _accepting;
public UntrustedTlsEndpoint()
{
using var key = RSA.Create(2048);
var request = new CertificateRequest("CN=127.0.0.1", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
// Schannel serves only a certificate whose key it can open: a PKCS #12 round trip gives it one.
_certificate = X509CertificateLoader.LoadPkcs12(created.Export(X509ContentType.Pkcs12), null);
_listener.Start();
_accepting = Task.Run(AcceptAsync);
}
public Uri Address => new($"https://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}/");
public void Dispose()
{
_stop.Cancel();
_listener.Stop();
try
{
_accepting.Wait(TimeSpan.FromSeconds(5));
}
catch (AggregateException)
{
// The loop ends with the listener; how it ended does not matter.
}
_certificate.Dispose();
_stop.Dispose();
}
private async Task AcceptAsync()
{
while (!_stop.IsCancellationRequested)
{
TcpClient client;
try
{
client = await _listener.AcceptTcpClientAsync(_stop.Token);
}
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
{
return;
}
using (client)
{
try
{
await using var tls = new SslStream(client.GetStream());
await tls.AuthenticateAsServerAsync(new SslServerAuthenticationOptions { ServerCertificate = _certificate }, _stop.Token);
}
catch (Exception ex) when (ex is AuthenticationException or IOException or OperationCanceledException or SocketException)
{
// The client refused the certificate: the handshake ends here, as intended.
}
}
}
}
}