Files
DodoSSH/tests/DodoSSH.Client.App.Tests/ShellFlowTests.cs
T
jaap-jan 0500e43e02 Stop the terminal's WebView painting over the setup screens
The shell layered its setup and unlock screens over the terminal, which does
not work: NativeWebView attaches a real Win32 child HWND through
NativeControlHost, and a child window composites above everything its parent
paints regardless of visual-tree z-order. The cards rendered sliced at the
terminal column's left edge; at the window's default width every one of their
buttons fell inside the WebView's rectangle, so the flow could only be
completed by keyboard, and a click in that region handed Win32 focus to
WebView2 so the text boxes silently stopped accepting keystrokes.

The WebView is now collapsed while the vault is not unlocked. The comment
that previously forbade this — hiding it means never realising it — was
wrong: NativeControlHost creates the native attachment on attach to the
visual tree, never consulting layout or visibility, and NativeWebView replays
a Source assigned before its adapter exists. A collapsed WebView still starts
WebView2, loads the page and lets the renderer attach. Confirmed: 35
msedgewebview2 processes with the control collapsed. What the first
connection after unlocking actually depends on is the existing await on
WaitForRendererAsync, since the data plane drops frames when no renderer is
attached.

Also fixes the second visible defect: the default server URL was
https://localhost:7217, the API's *second* launch profile, while the README,
its appsettings and a plain `dotnet run` all use http://localhost:5233 — so
nothing was listening, and an HTTPS client against a plaintext port reports
"The SSL connection could not be established", which reads as a certificate
problem. The default now matches, a missing scheme is rejected by name
instead of parsing as scheme "localhost", and that specific TLS failure now
suggests http://. Both new tests fail when the fixes are reverted.

Corrections to claims I made earlier and should not have:

- docs/platform-flags.md asserted the opposite of the mechanism above and
  cited an established msedgewebview2 connection as verification. That
  observation was taken while the overlay was showing but, because of this
  very bug, the WebView was uncovered and in plain view — so it confirmed
  only that a visible WebView is realised. A process-level check cannot
  verify a rendering claim. The entry was also filed under "Local cache".
- ITerminalHost was documented as the live seam the app plugs into, with a
  stub standing in for headless tests. It has no implementation anywhere and
  no test uses it; the view navigates the control directly. It also counted
  Avalonia.Controls.WebView and NativeWebView as two interchangeable
  backends when they are one component, with the Linux backend backwards.
- The README claimed the shell's whole path was covered by tests. Its state
  machine is; its layout is covered by nothing, and a headless test could
  not have caught this — headless has no native window, so it would have
  rendered correctly and confirmed the wrong belief.

Verified by screenshotting the running app: the card renders complete and
centred at the default size, with the button clickable.
2026-07-29 13:26:30 +02:00

482 lines
16 KiB
C#

using DodoSSH.Client.App.ViewModels;
using DodoSSH.Client.Session;
using DodoSSH.Client.Ssh;
using DodoSSH.Client.Storage;
using DodoSSH.Client.Terminal;
using DodoSSH.Crypto;
namespace DodoSSH.Client.App.Tests;
/// <summary>
/// The whole path a user walks: sign in, enroll, keep the recovery code, unlock, add a host, sync.
/// </summary>
/// <remarks>
/// Runs with no Avalonia, no browser and no identity provider, because the view models are plain
/// observable objects and sign-in is a delegate. What that buys is that the states most likely to be got
/// wrong — the one that must not be skipped, and the one that has to work offline — are checked by a test
/// rather than by remembering to click through them.
/// </remarks>
public sealed class ShellFlowTests : IAsyncLifetime
{
private const string Passphrase = "a sufficiently long passphrase";
/// <remarks>
/// Far below the shipped profile, for the same reason as everywhere else: these tests are about the
/// state machine, not about how expensive the passphrase is to attack.
/// </remarks>
private static readonly Argon2Profile CheapProfile =
Argon2Profile.FromStoredParameters(memoryKibibytes: 8 * 1024, passes: 1, parallelism: 1);
private readonly FakeVaultServer server = new();
private int signInAttempts;
private string directory = null!;
private ClientPaths paths = null!;
private ClientCacheFactory caches = null!;
private TerminalWorkspace workspace = null!;
private MainWindowViewModel shell = null!;
/// <inheritdoc />
public ValueTask InitializeAsync()
{
// A real directory and a real SQLite file, because the production path is what StartAsync runs and
// an in-memory database would skip the migration that creates the file.
directory = Path.Combine(Path.GetTempPath(), $"dodossh-shell-{Guid.CreateVersion7():N}");
paths = new ClientPaths(directory);
caches = ClientCacheFactory.ForFile(paths.CacheFile);
var knownHosts = new InMemoryKnownHostStore();
// In-memory assets rather than the application's Avalonia-resource provider, which reads the
// resource system at construction and needs an initialised toolkit. This is what
// ITerminalAssetProvider is for; nothing in this suite renders anything.
workspace = new TerminalWorkspace(
new InMemoryTerminalAssetProvider(
new Dictionary<string, TerminalAsset>(StringComparer.Ordinal)
{
["/terminal"] = new("text/html; charset=utf-8", "<!doctype html>"u8.ToArray()),
}),
new SshNetConnectionFactory(knownHosts),
TimeProvider.System);
shell = new MainWindowViewModel(
paths,
caches,
workspace,
knownHosts,
SignInAsync,
TimeProvider.System,
CheapProfile);
return ValueTask.CompletedTask;
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
await shell.DisposeAsync();
await workspace.DisposeAsync();
caches.Dispose();
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
[Fact]
public async Task AFreshMachine_AsksForAServer()
{
await shell.StartAsync(Token);
shell.State.ShouldBe(ShellState.NeedsServer);
shell.IsNeedingServer.ShouldBeTrue();
shell.IsOnline.ShouldBeFalse();
// The migration ran, so the file exists before anyone has signed in to anything.
File.Exists(paths.CacheFile).ShouldBeTrue();
}
[Fact]
public async Task SigningInToAnUnenrolledAccount_AsksForAPassphrase()
{
await shell.StartAsync(Token);
await shell.SignInCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.NeedsEnrollment);
shell.IsOnline.ShouldBeTrue();
shell.AccountName.ShouldBe("Alice Example");
}
[Fact]
public async Task AnUnreachableServer_ReportsAndStaysPut()
{
server.SignInFailure = new HttpRequestException("No such host is known.");
await shell.StartAsync(Token);
await shell.SignInCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.NeedsServer);
shell.StatusMessage.ShouldContain("No such host");
shell.IsBusy.ShouldBeFalse("a failed command must not leave the window disabled");
}
[Fact]
public async Task AnInvalidServerUrl_IsRejectedWithoutTouchingTheNetwork()
{
await shell.StartAsync(Token);
shell.ServerUrl = "not a url";
await shell.SignInCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.NeedsServer);
shell.IsOnline.ShouldBeFalse();
}
/// <remarks>
/// Separate from the case above because it is not caught by the same check. <c>Uri.TryCreate</c>
/// accepts this happily as an absolute URI whose <em>scheme</em> is "localhost" and whose host is
/// empty, so without an explicit scheme check the mistake surfaces much later as something that reads
/// like a network fault.
/// </remarks>
[Fact]
public async Task AServerUrlWithNoScheme_SaysSoRatherThanFailingLater()
{
await shell.StartAsync(Token);
shell.ServerUrl = "localhost:5233";
await shell.SignInCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.NeedsServer);
shell.IsOnline.ShouldBeFalse();
shell.StatusMessage.ShouldContain("http://");
signInAttempts.ShouldBe(0, "a malformed URL must not open a browser");
}
/// <remarks>
/// The shipped default is a value a user is invited to accept unread, so it is worth one assertion.
/// It was <c>https://localhost:7217</c> — the API's second launch profile — while the README, the
/// API's appsettings and a plain <c>dotnet run</c> all use HTTP on 5233, and pointing an HTTPS client
/// at a plaintext port reports a TLS failure that reads like a certificate problem. Nothing failed
/// except the first thing a new user does.
/// </remarks>
[Fact]
public void TheDefaultServerUrl_IsTheAddressTheApiActuallyServes()
{
shell.ServerUrl.ShouldBe("http://localhost:5233");
}
[Theory]
[InlineData("short", "short")]
[InlineData("a sufficiently long passphrase", "a different one")]
public async Task AWeakOrMismatchedPassphrase_DoesNotEnroll(string entered, string confirmation)
{
await SignedInAsync();
shell.Passphrase = entered;
shell.ConfirmPassphrase = confirmation;
await shell.EnrollCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.NeedsEnrollment);
server.EnrollmentCount.ShouldBe(0);
}
[Fact]
public async Task TheRecoveryCodeScreen_CannotBeSkipped()
{
// The only moment the code exists. Losing it along with the passphrase means the vault is
// unrecoverable and there is no server-side reset, so this is the one screen that has to insist.
await EnrolledAsync();
shell.State.ShouldBe(ShellState.ShowingRecoveryCode);
shell.RecoveryCode.ShouldNotBeNullOrWhiteSpace();
// Trying to continue without confirming gets nowhere.
shell.ConfirmRecoveryCodeCommand.Execute(null);
shell.State.ShouldBe(ShellState.ShowingRecoveryCode);
shell.RecoveryCode.ShouldNotBeNull();
shell.RecoveryCodeWrittenDown = true;
shell.ConfirmRecoveryCodeCommand.Execute(null);
shell.State.ShouldBe(ShellState.Locked);
// And it is dropped from memory, not merely hidden. It was never persisted; keeping it in a view
// model for the rest of the session would undo that.
shell.RecoveryCode.ShouldBeNull();
}
[Fact]
public async Task AWrongPassphrase_KeepsTheVaultLocked()
{
await ReadyToUnlockAsync();
shell.Passphrase = "not the passphrase";
await shell.UnlockCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.Locked);
shell.Vault.ShouldBeNull();
shell.StatusMessage.ShouldContain("did not open");
}
[Fact]
public async Task UnlockingOpensTheVault()
{
await UnlockedAsync();
shell.State.ShouldBe(ShellState.Unlocked);
shell.Vault.ShouldNotBeNull();
shell.Vault.VaultName.ShouldBe("Personal");
// Cleared once used, so it is not sitting in a bound property for the rest of the session.
shell.Passphrase.ShouldBeEmpty();
}
[Fact]
public async Task ARestartUnlocksWithNoNetworkAtAll()
{
// The property the whole storage layer exists for, from the shell's point of view. The second
// shell is given a sign-in delegate that fails if called.
await EnrolledAndConfirmedAsync();
await shell.LockCommand.ExecuteAsync(null);
var offline = new MainWindowViewModel(
paths,
caches,
workspace,
new InMemoryKnownHostStore(),
(_, _) => throw new InvalidOperationException("The shell went to the network to unlock."),
TimeProvider.System,
CheapProfile);
await using var _ = offline.ConfigureAwait(false);
await offline.StartAsync(Token);
offline.State.ShouldBe(ShellState.Locked);
offline.AccountName.ShouldBe("Alice Example");
offline.IsOnline.ShouldBeFalse();
offline.Passphrase = Passphrase;
await offline.UnlockCommand.ExecuteAsync(null);
offline.State.ShouldBe(ShellState.Unlocked);
offline.Vault.ShouldNotBeNull();
}
[Fact]
public async Task AddingAHost_ShowsItImmediatelyAndQueuesIt()
{
await UnlockedAsync();
var vault = shell.Vault!;
vault.NewHostCommand.Execute(null);
vault.IsEditing.ShouldBeTrue();
vault.EditorLabel = "prod-db";
vault.EditorHostname = "db.internal";
vault.EditorUsername = "deploy";
vault.EditorPort = 2222;
await vault.SaveHostCommand.ExecuteAsync(null);
vault.IsEditing.ShouldBeFalse();
var row = vault.Hosts.ShouldHaveSingleItem();
row.Label.ShouldBe("prod-db");
row.Address.ShouldBe("deploy@db.internal:2222");
row.HasUnsyncedChanges.ShouldBeTrue();
row.Badge.ShouldBe("not synced");
vault.PendingChanges.ShouldBe(1);
server.LiveRowCount.ShouldBe(0, "nothing should have been pushed yet");
}
[Fact]
public async Task AnInvalidHost_IsRefusedWithAReason()
{
await UnlockedAsync();
var vault = shell.Vault!;
vault.NewHostCommand.Execute(null);
vault.EditorLabel = " ";
vault.EditorHostname = "db.internal";
await vault.SaveHostCommand.ExecuteAsync(null);
vault.IsEditing.ShouldBeTrue("the editor should stay open so the user can fix it");
vault.Hosts.ShouldBeEmpty();
vault.Status.ShouldContain("needs a name");
}
[Fact]
public async Task SyncingSendsTheQueueAndClearsIt()
{
await UnlockedAsync();
var vault = shell.Vault!;
await AddHostAsync(vault, "prod-db");
await vault.SyncCommand.ExecuteAsync(null);
server.LiveRowCount.ShouldBe(1);
vault.PendingChanges.ShouldBe(0);
vault.Hosts.ShouldHaveSingleItem().HasUnsyncedChanges.ShouldBeFalse();
vault.Status.ShouldContain("Synchronised");
}
[Fact]
public async Task EditingAHostRoundTripsThroughTheEditor()
{
await UnlockedAsync();
var vault = shell.Vault!;
await AddHostAsync(vault, "prod-db");
await vault.SyncCommand.ExecuteAsync(null);
vault.SelectedHost = vault.Hosts[0];
vault.EditSelectedHostCommand.Execute(null);
vault.EditorLabel.ShouldBe("prod-db");
vault.EditorHostname.ShouldBe("db.internal");
vault.EditorNotes = "rotate quarterly";
await vault.SaveHostCommand.ExecuteAsync(null);
await vault.SyncCommand.ExecuteAsync(null);
vault.Hosts.ShouldHaveSingleItem().Host.Notes.ShouldBe("rotate quarterly");
}
[Fact]
public async Task DeletingAHostRemovesItLocallyBeforeTheServerAgrees()
{
await UnlockedAsync();
var vault = shell.Vault!;
await AddHostAsync(vault, "prod-db");
await vault.SyncCommand.ExecuteAsync(null);
vault.SelectedHost = vault.Hosts[0];
await vault.DeleteHostCommand.ExecuteAsync(null);
vault.Hosts.ShouldBeEmpty();
server.LiveRowCount.ShouldBe(1, "the tombstone has not been pushed yet");
await vault.SyncCommand.ExecuteAsync(null);
server.LiveRowCount.ShouldBe(0);
}
[Fact]
public async Task SyncingWhileOffline_QueuesRatherThanFailing()
{
await EnrolledAndConfirmedAsync();
await shell.LockCommand.ExecuteAsync(null);
// Locking does not drop the connection, so take a fresh shell that never signed in.
var offline = new MainWindowViewModel(
paths,
caches,
workspace,
new InMemoryKnownHostStore(),
(_, _) => throw new InvalidOperationException("unreachable"),
TimeProvider.System,
CheapProfile);
await using var _ = offline.ConfigureAwait(false);
await offline.StartAsync(Token);
offline.Passphrase = Passphrase;
await offline.UnlockCommand.ExecuteAsync(null);
var vault = offline.Vault!;
await AddHostAsync(vault, "offline-host");
await vault.SyncCommand.ExecuteAsync(null);
vault.Status.ShouldContain("Offline");
vault.PendingChanges.ShouldBe(1, "the change is kept, not discarded");
server.PushCount.ShouldBe(0);
}
[Fact]
public async Task LockingForgetsTheVault()
{
await UnlockedAsync();
await shell.LockCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.Locked);
shell.Vault.ShouldBeNull();
// And unlocking again works, so locking released rather than corrupted anything.
shell.Passphrase = Passphrase;
await shell.UnlockCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.Unlocked);
}
// ---- Helpers ----
private static CancellationToken Token => TestContext.Current.CancellationToken;
private Task<IVaultServer> SignInAsync(Uri serverUrl, CancellationToken cancellationToken)
{
// Counted so a test can assert that a rejected URL never got this far. Reaching here means a
// browser would have opened in the real application.
signInAttempts++;
return server.SignInFailure is { } failure
? Task.FromException<IVaultServer>(failure)
: Task.FromResult<IVaultServer>(server);
}
private async Task SignedInAsync()
{
await shell.StartAsync(Token);
await shell.SignInCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.NeedsEnrollment);
}
private async Task EnrolledAsync()
{
await SignedInAsync();
shell.Passphrase = Passphrase;
shell.ConfirmPassphrase = Passphrase;
await shell.EnrollCommand.ExecuteAsync(null);
}
private async Task EnrolledAndConfirmedAsync()
{
await EnrolledAsync();
shell.RecoveryCodeWrittenDown = true;
shell.ConfirmRecoveryCodeCommand.Execute(null);
shell.State.ShouldBe(ShellState.Locked);
}
private Task ReadyToUnlockAsync() => EnrolledAndConfirmedAsync();
private async Task UnlockedAsync()
{
await EnrolledAndConfirmedAsync();
shell.Passphrase = Passphrase;
await shell.UnlockCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.Unlocked, shell.StatusMessage);
}
private static async Task AddHostAsync(VaultViewModel vault, string label)
{
vault.NewHostCommand.Execute(null);
vault.EditorLabel = label;
vault.EditorHostname = "db.internal";
vault.EditorUsername = "deploy";
await vault.SaveHostCommand.ExecuteAsync(null);
}
}