Files
jaap-jan 8a77b7ca68
ci / build and test (pull_request) Failing after 2m34s
ci / desktop nightly (pull_request) Skipped
ci / api image (pull_request) Skipped
ci / android head (pull_request) Successful in 3m28s
Say how far a connection has got while it is still being made
The connecting card set its status string once, when the tab was created, and
never touched it again. Every connection therefore looked identical from the
outside: one three seconds into a key exchange, one waiting out a fifteen-second
timeout against a machine that is asleep, and one that had hung all drew the
same "connecting…". The card now draws the five steps of getting there, each lit
at the moment the handshake reports reaching it, over an amber track that fills
as they finish.

◆ NOTHING ON THE LIST IS INVENTED. Every row changes state because a layer below
it said so, at the instant the thing it names actually began.

That is the whole reason it is worth showing, and it is why most of this commit
is plumbing rather than XAML: there was no progress reporting anywhere in the
stack to hook a step list onto, and a card animating plausible progress would
have been indistinguishable from one that had stopped receiving any.

SshConnectionPhase names four phases and deliberately not more. SSH.NET runs the
entire handshake inside one ConnectAsync and raises exactly one event from the
middle of it — HostKeyReceived, once the key exchange has produced a key to show
— so that event is the only interior moment there is to report. Everything
before it is Reaching and everything after it is Authenticating. A fifth phase
in that assembly would have to be a timer, so there is not one. OpeningShell is
reported by TerminalWorkspace instead, because that is where it happens: the
factory's work ends with an authenticated connection, and asking for a
pseudo-terminal on one is a separate round trip. The SFTP path passes null — a
second connection opened behind an already-open shell has nobody watching a step
list for it.

The card's fifth step, "Starting the terminal", is the renderer wait and lives
in the shell rather than in the SSH assembly, which has never heard of a
renderer. On the first connection after a cold start it is a real wait with a
real failure mode of its own — a missing WebView2 runtime — so a list that began
at "reaching the host" would leave the one wait most likely to hang unnamed.

Amber for the step in flight, and that follows the palette's rule rather than
bending it. Green is what is true and purple is what you can press; a step still
happening is neither, and it is exactly the caveat-worth-reading that amber
exists for. Steps behind it go green as they become true. Nothing animates,
which is the argument TransfersScreen.axaml already makes for its own track,
reaching a screen with far more reason to want a spinner: a spinner is furniture
invented to fill a state nobody measured, and these states are measured, so the
track fills to what has finished and then waits there.

A refusal keeps the step it stopped on, in red, with the ones behind it still
green. That is the half a progress bar could not do, and it is the difference
between "that host is not there" and "that host is there and would not have me"
— a question the reason sentence alone frequently does not settle.

The strip's dot goes amber while a tab is connecting, on both heads. It was
grey, and so is a tab whose shell has exited: the two states in that strip with
the least in common, one worth waiting for and one over. PhoneShell's own
comment already recorded half of this — the dot stopped being green before
anything had answered — and this is the other half.

Progress is raised inline rather than through System.Progress<T>, which captures
whatever synchronisation context it was constructed on and posts to it. That
reads like a convenience and is really a second place the marshalling decision
gets made: silently, differently under a test with no context, and out of order
with respect to the failure that follows a phase. The shell marshals once, in
one handler, through a new optional post parameter on MainWindowViewModel — the
same seam TransfersViewModel already uses, and for the reason its own remark
gives. The three Dispatcher.UIThread.Post calls that predate it are the ones
this suite's comments record as out of reach; they are left alone rather than
swept in here.

Both heads draw the list. They differ in one place: Phone.axaml's mono class
sets a colour and a size along with the family, so the caption rule names its
own family instead of composing the two and asking two rules for one Foreground.
The desktop's mono sets the family alone, which is why ConnectingCard does
compose them. Each head also gains SHOW LOGS beside the button that gives up —
the step list is this attempt and the log is every other one, which is what a
connection taking too long actually raises.

Seven tests, and the two that matter most run against the container rather than
a fake: a real handshake reports its phases in order, and a host-key refusal
never claims to have authenticated. A fake asserting what it was written to
assert would have established nothing about either. The rest cover the tab
advancing while the connection is gated, the step a refusal stops on, and a
phase reported after the user has given up on the tab. 1,861 tests, none
failing.

The Android head's layout is not verified by anything. It compiles, and
compiled bindings mean every new binding path resolves, but that project is not
in DodoSSH.slnx, there is no test project for it and no device here — so unlike
the desktop card, whose shapes the layout harness measures, these rows have not
been drawn. Vertical fit is reasoned, not observed.
2026-08-10 15:47:45 +02:00

240 lines
11 KiB
C#

using System.Security.Cryptography;
using System.Text;
using Renci.SshNet.Common;
namespace DodoSSH.Client.Ssh.Tests;
/// <summary>
/// Public-key authentication through the path the vault actually uses, against a real sshd.
/// </summary>
/// <remarks>
/// <para>
/// <c>PtyAndResizeSpikeTests</c> also authenticates with this fixture's key, and it does so by building
/// SSH.NET's <c>PrivateKeyAuthenticationMethod</c> itself — correct for a spike whose subject is the PTY,
/// and it leaves the application's own path unexercised. What runs here is what a vault-held key goes
/// through: <see cref="SshPrivateKeyCredential"/> carrying PEM bytes rather than a path, into
/// <see cref="SshNetConnectionFactory"/>, which hands them to <c>PrivateKeyFile</c> as a
/// <c>MemoryStream</c>. That indirection is the reason a key in this product never becomes a file on disk,
/// and until now nothing established that it authenticates.
/// </para>
/// <para>
/// The fixture's key is RSA because there is no BCL Ed25519, and the fixture has to render the public half
/// in <c>authorized_keys</c> form to install it. Which algorithm it is does not matter to anything under
/// test here — the client never parses the key, it forwards it.
/// </para>
/// </remarks>
[Collection(SshCollection.Name)]
public sealed class KeyAuthenticationTests(SshServerFixture fixture)
{
private static CancellationToken Token => TestContext.Current.CancellationToken;
[Fact]
public async Task AKeyHeldAsBytes_AuthenticatesAndOpensAShell()
{
await using var connection = await ConnectTrustedAsync(
new SshPrivateKeyCredential(Pkcs1(fixture.ClientKey), Passphrase: null));
connection.IsConnected.ShouldBeTrue();
// The one place this suite checks Cipher against a real handshake rather than a fake's fixed string.
// SSH.NET negotiates whatever the container's sshd offers first from its own preference list, so the
// exact algorithm is not pinned here — only that ConnectionInfo.CurrentServerEncryption came back as
// something rather than the empty string a stalled or pre-handshake read would produce.
connection.Cipher.ShouldNotBeNullOrEmpty();
// Authenticated is not the same as usable: a channel has to open on the connection too.
await using var shell = await connection.OpenShellAsync(TerminalSize.Default, Token);
shell.IsOpen.ShouldBeTrue();
}
[Fact]
public async Task TheSameKeyInPkcs8Armour_AlsoAuthenticates()
{
// SshKeySecret stores whatever armour it was given, verbatim, and declines to normalise it. This is
// the half of that claim which is about SSH.NET rather than the codec: the two commonest forms
// ssh-keygen and openssl produce both load without the client knowing which it has.
await using var connection = await ConnectTrustedAsync(
new SshPrivateKeyCredential(Pkcs8(fixture.ClientKey), Passphrase: null));
connection.IsConnected.ShouldBeTrue();
}
[Fact]
public async Task AKeyTheServerDoesNotKnow_FailsAsAnAuthenticationError()
{
// The specific failure worth pinning is a misreport. The host key is already trusted here, so the
// factory's gate must translate nothing and let the authentication error through — if it answered
// with SshHostKeyUnknownException instead, the user would be shown a fingerprint to approve for a
// problem that approving it cannot fix.
using var stranger = RSA.Create(2048);
var knownHosts = await TrustedStoreAsync();
var factory = new SshNetConnectionFactory(knownHosts);
await Should.ThrowAsync<SshAuthenticationException>(async () =>
await factory.ConnectAsync(
Request(new SshPrivateKeyCredential(Pkcs1(stranger), null)), progress: null, Token));
}
[Fact]
public async Task APassphraseOnAnUnprotectedKey_IsIgnoredRatherThanRefused()
{
// Written expecting the opposite, and it records what SSH.NET measurably does: PrivateKeyFile
// accepts a passphrase for a key that has none, and the connection authenticates as if it had not
// been given. See docs/platform-flags.md — the consequence is that nothing downstream will catch a
// stray passphrase, so a client that wants that caught has to notice it itself, and a client that
// does not can stop worrying about the case.
await using var connection = await ConnectTrustedAsync(
new SshPrivateKeyCredential(Pkcs1(fixture.ClientKey), "a passphrase this key does not have"));
connection.IsConnected.ShouldBeTrue();
}
/// <remarks>
/// <para>
/// <b>The test the key generator exists to pass.</b> Everything else about the hand-written
/// <c>openssh-key-v1</c> container is checked against SSH.NET's own parser, which is the parser this
/// application uses and therefore a fair oracle — but it is still one implementation agreeing with
/// another. This is the one that puts the public half on a real OpenSSH server and authenticates with
/// the private half, which is the only thing anybody actually wants to know.
/// </para>
/// <para>
/// Both algorithms, because they are encoded by entirely different code: Ed25519 goes through the
/// hand-written container, and RSA through the BCL's PKCS#1 export with only the public line
/// hand-encoded. A failure on one says nothing about the other.
/// </para>
/// </remarks>
[Theory]
[InlineData(SshKeyAlgorithm.Ed25519)]
[InlineData(SshKeyAlgorithm.Rsa4096)]
public async Task AKeyThisClientGenerated_AuthenticatesAgainstARealServer(SshKeyAlgorithm algorithm)
{
var generated = SshKeyGenerator.Generate(algorithm, "dodossh@generated");
await fixture.AuthorizeAsync(generated.PublicKeyLine, Token);
await using var connection = await ConnectTrustedAsync(
new SshPrivateKeyCredential(
Encoding.UTF8.GetBytes(generated.PrivateKeyArmour), Passphrase: null));
connection.IsConnected.ShouldBeTrue();
// Authenticated is not the same as usable, as above.
await using var shell = await connection.OpenShellAsync(TerminalSize.Default, Token);
shell.IsOpen.ShouldBeTrue();
}
/// <remarks>
/// <para>
/// The claim the connecting card is built on, checked where it can actually be checked: against a real
/// handshake rather than a fake that reports whatever it was written to report. Every other test of the
/// step list asserts that the shell draws what it is told; this one asserts that what it is told is
/// true.
/// </para>
/// <para>
/// The order is the assertion. A step list is only readable if the reports arrive in the order it draws
/// them, and the middle one is the load-bearing part — <see cref="SshConnectionPhase.CheckingHostKey"/>
/// comes out of SSH.NET's <c>HostKeyReceived</c>, which is the single interior moment the library gives
/// anybody, and it has to land between the other two rather than beside them.
/// </para>
/// <para>
/// <see cref="SshConnectionPhase.OpeningShell"/> is deliberately absent: this factory's work ends with
/// an authenticated connection, and the phase for opening a channel on one belongs to the layer that
/// opens it. <c>TerminalWorkspaceTests</c> covers that half.
/// </para>
/// </remarks>
[Fact]
public async Task AHandshake_ReportsItsPhasesInTheOrderTheyHappen()
{
var knownHosts = await TrustedStoreAsync();
var reported = new List<SshConnectionPhase>();
await using var connection = await new SshNetConnectionFactory(knownHosts).ConnectAsync(
Request(new SshPrivateKeyCredential(Pkcs1(fixture.ClientKey), Passphrase: null)),
new DelegateProgress<SshConnectionPhase>(phase =>
{
lock (reported)
{
// Locked because the last two are reported from SSH.NET's own handshake thread rather
// than from the awaiting one, which is the whole reason the shell marshals them.
reported.Add(phase);
}
}),
Token);
connection.IsConnected.ShouldBeTrue();
lock (reported)
{
reported.ShouldBe(
[
SshConnectionPhase.Reaching,
SshConnectionPhase.CheckingHostKey,
SshConnectionPhase.Authenticating,
]);
}
}
/// <remarks>
/// The other half of the phase contract, and the one that would be easy to get wrong by reporting
/// optimistically: a refused key stops at the check. Nothing may claim the credential was offered, and
/// against an unknown host nothing ever is — the gate returns false and SSH.NET abandons the handshake
/// before authentication.
/// </remarks>
[Fact]
public async Task AHostKeyRefusal_NeverClaimsToHaveAuthenticated()
{
var reported = new List<SshConnectionPhase>();
await Should.ThrowAsync<SshHostKeyUnknownException>(async () =>
await new SshNetConnectionFactory(new InMemoryKnownHostStore()).ConnectAsync(
Request(new SshPasswordCredential(SshServerFixture.Password)),
new DelegateProgress<SshConnectionPhase>(phase =>
{
lock (reported)
{
reported.Add(phase);
}
}),
Token));
lock (reported)
{
reported.ShouldBe([SshConnectionPhase.Reaching, SshConnectionPhase.CheckingHostKey]);
}
}
private static byte[] Pkcs1(RSA key) => Encoding.UTF8.GetBytes(key.ExportRSAPrivateKeyPem());
private static byte[] Pkcs8(RSA key) => Encoding.UTF8.GetBytes(key.ExportPkcs8PrivateKeyPem());
private SshConnectionRequest Request(SshCredential credential) =>
new(fixture.Host, fixture.Port, SshServerFixture.Username, credential);
/// <summary>A store that already trusts the container's host key, so first contact is not the subject.</summary>
private async Task<InMemoryKnownHostStore> TrustedStoreAsync()
{
var knownHosts = new InMemoryKnownHostStore();
var factory = new SshNetConnectionFactory(knownHosts);
// Learned by being refused, which is the only way this client learns a host key.
var unknown = await Should.ThrowAsync<SshHostKeyUnknownException>(async () =>
await factory.ConnectAsync(
Request(new SshPasswordCredential(SshServerFixture.Password)), progress: null, Token));
await knownHosts.TrustAsync(unknown.Presentation, Token);
return knownHosts;
}
private async Task<ISshConnection> ConnectTrustedAsync(SshCredential credential)
{
var knownHosts = await TrustedStoreAsync();
return await new SshNetConnectionFactory(knownHosts)
.ConnectAsync(Request(credential), progress: null, Token);
}
}