Files
DodoSSH/tests/DodoSSH.Client.Terminal.Tests/FakeShellSession.cs
T
jaap-jan eb354bcdd9 Add the SSH session layer and the terminal data plane
The throughput harness the plan requires before any UI, plus the SSH
plumbing under it. 94 new tests, no WebView involved.

Credit-based flow control is what makes `yes` survivable. A terminal renders
at 60 Hz at best while a remote produces output as fast as the network
allows, and the difference has to accumulate somewhere or be refused.
Credit is reserved *before* reading, never after: because the pump cannot
read more than the renderer has room for, the coalescing buffer is bounded
by the window rather than by how fast the remote can talk. When credit runs
out the pump stops reading, SSH's own receive window closes, and the remote
sshd blocks -- backpressure to the source with no custom protocol.

Verified by falsification, not just by passing: with the credit gate removed
three tests fail, including the throughput harness's bounded-memory
assertion. Acknowledgements are clamped because they cross into JavaScript,
where a buggy or hostile page could otherwise claim to have rendered a
gigabyte and talk the host into an unbounded read.

Host key trust is enforced by *failing* the connection rather than
prompting inside the handshake. SSH.NET raises verification synchronously,
so consulting the user there would block the handshake on a UI round trip
and deadlock the first time the prompt needed the UI thread. Unknown host
and changed key become distinct exceptions the caller resolves
asynchronously. A mismatch has no retry path at all: a dialog offering to
continue is how users are trained to click through the one warning that
actually indicates interception. A legitimately rebuilt server is handled by
removing the pin in settings, away from the moment of connecting.

The data plane serves the renderer page from the same loopback listener as
the socket, which makes Origin predictable -- always http://127.0.0.1:{port}
-- where a WebView virtual-host mapping would give a different origin per
backend and nothing to validate. The token is substituted at serve time, so
it never touches disk and never appears in a URL. Being clear about what
that buys: not protection from a process running as this user, which can
read our memory anyway, but from a page in the user's browser attempting
WebSocket connections to loopback ports, which is a real and routine thing.

Two bugs the tests caught. The accept loop handled connections serially, so
an upgraded WebSocket parked it inside the receive loop and every later
request went unanswered -- the page's own script among them. The suite hung
rather than failed, which is how I found it. And SHA-1 is unavoidable here:
RFC 6455 mandates it for Sec-WebSocket-Accept, where it authenticates
nothing. Suppressed narrowly with that reasoning; the alternative,
HttpListener.AcceptWebSocketAsync, throws PlatformNotSupportedException off
Windows.
2026-07-28 21:58:55 +02:00

168 lines
4.8 KiB
C#

using DodoSSH.Client.Ssh;
namespace DodoSSH.Client.Terminal.Tests;
/// <summary>A shell session that produces output on demand, for exercising the pump.</summary>
internal sealed class FakeShellSession : ISshShellSession
{
private readonly List<byte> written = [];
private readonly Lock gate = new();
private long remaining;
private byte pattern;
/// <param name="bytesToProduce">
/// How many bytes to emit before reporting end of stream. <see cref="long.MaxValue"/> for an
/// endless producer, which is what a runaway remote process looks like — those sessions are ended
/// by disposing the pump rather than by running out of data.
/// </param>
internal FakeShellSession(long bytesToProduce = 0) => remaining = bytesToProduce;
/// <inheritdoc />
public bool IsOpen { get; private set; } = true;
/// <summary>Reads issued against this session, to detect a pump that kept reading.</summary>
public int ReadCount { get; private set; }
/// <summary>Bytes the pump wrote toward the remote.</summary>
public byte[] Written
{
get
{
lock (gate)
{
return [.. written];
}
}
}
/// <summary>The last size the pump forwarded, or null if it forwarded none.</summary>
public TerminalSize? LastResize { get; private set; }
/// <summary>How many resizes were forwarded, so a dropped one is observable.</summary>
public int ResizeCount { get; private set; }
/// <inheritdoc />
/// <remarks>
/// Returns 0 once the configured budget is spent, which is what a remote closing the channel looks
/// like. Not synchronous: a fake that never yields would let the pump's read loop monopolise the
/// thread and hide any ordering problem between reading and flushing.
/// </remarks>
public async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
{
ReadCount++;
await Task.Yield();
cancellationToken.ThrowIfCancellationRequested();
if (remaining <= 0)
{
return 0;
}
var count = (int)Math.Min(buffer.Length, remaining);
buffer.Span[..count].Fill(unchecked(pattern++));
remaining -= count;
return count;
}
/// <inheritdoc />
public ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
{
lock (gate)
{
written.AddRange(data.ToArray());
}
return ValueTask.CompletedTask;
}
/// <inheritdoc />
public void Resize(TerminalSize size)
{
// Mirrors the real session: an unusable size is dropped rather than forwarded.
if (!size.IsUsable)
{
return;
}
ResizeCount++;
LastResize = size;
}
/// <inheritdoc />
public ValueTask DisposeAsync()
{
IsOpen = false;
remaining = 0;
return ValueTask.CompletedTask;
}
}
/// <summary>Records frames, and can acknowledge them to keep credit flowing.</summary>
internal sealed class RecordingTransport : ITerminalTransport
{
private readonly List<byte[]> frames = [];
private readonly Lock gate = new();
/// <summary>Set to acknowledge every output frame immediately, as a keeping-up renderer would.</summary>
internal TerminalSessionPump? AutoAcknowledge { get; set; }
/// <summary>Frames sent so far.</summary>
internal IReadOnlyList<byte[]> Frames
{
get
{
lock (gate)
{
return [.. frames];
}
}
}
/// <inheritdoc />
public ValueTask SendAsync(ReadOnlyMemory<byte> frame, CancellationToken cancellationToken)
{
var copy = frame.ToArray();
lock (gate)
{
frames.Add(copy);
}
if (AutoAcknowledge is { } pump
&& TerminalFrame.TryRead(copy, out var opcode, out _, out var payload)
&& opcode == (byte)TerminalServerOpcode.Output)
{
pump.Acknowledge((uint)payload.Length);
}
return ValueTask.CompletedTask;
}
/// <summary>Concatenated payloads of every output frame.</summary>
internal byte[] OutputBytes()
{
var output = new List<byte>();
foreach (var frame in Frames)
{
if (TerminalFrame.TryRead(frame, out var opcode, out _, out var payload)
&& opcode == (byte)TerminalServerOpcode.Output)
{
output.AddRange(payload);
}
}
return [.. output];
}
/// <summary>Counts frames of one opcode.</summary>
internal int CountOf(TerminalServerOpcode opcode) =>
Frames.Count(frame =>
TerminalFrame.TryRead(frame, out var actual, out _, out _)
&& actual == (byte)opcode);
}