Let a host marked for the relay actually be reached through it
ci / build and test (pull_request) Successful in 6m27s
ci / desktop nightly (pull_request) Skipped
ci / android head (pull_request) Successful in 15m47s
ci / api image (pull_request) Failing after 28s

The relay checkbox said it was not wired up, and the plan said the server
half was built and shipped. It was not: there was ADR 0004, the contract
records, RelayOptions and a CHECK constraint, and RelayOptions said in its
own remarks that there was no endpoint and no dialler. So both halves are
built here, as step 3 of docs/reaching-a-host-you-cannot-dial.md.

Server, in Features/Relay:

- POST /api/v1/relay/tickets makes every decision: the host, Connect on
  its vault, the relay switched on, and the stored name resolved once and
  judged by RelayAddressPolicy. Loopback, link-local, 0.0.0.0/8,
  multicast and the metadata endpoints are refused with no configuration
  escape, with IPv4-mapped and NAT64 spellings unwrapped first; then the
  operator's denials, allow-list and private-network switch. What passes
  goes into a Data Protection ticket, and nothing resolves the name again.
  Every target refusal is the same 403, so the endpoint cannot be used to
  map the operator's DNS; the real reason is logged.
- GET /api/v1/relay/connect takes the ticket as a second subprotocol,
  checks its expiry against TimeProvider and spends it with a unique
  insert into relay_ticket_use before accepting the upgrade. After the
  upgrade a refusal is a close code: 4502 for a host the server could not
  reach, 4429 for a limit, 4408 idle, 4409 lifetime, 1001 after a drain.
- relay_session is the audit row, written from short-lived scopes.

Client:

- RelayBridge is a loopback SOCKS5 listener that accepts once and pipes
  to the relay socket. It rides on the new SshLoopbackProxy.Lifetime, so
  the connection disposes it on every way a session ends and a failed
  connect disposes it before throwing.
- ServerRelay, exposed as IVaultServer.Relay from /api/v1/meta, asks for
  the ticket, opens the socket, starts the bridge and turns every refusal
  into a sentence.
- VaultViewModel and TransfersViewModel reach a relayed host through it,
  never fall back to dialling it directly, and replace SSH.NET's transport
  error with the relay's own reason when it gave one.

Neither side ever cancels a WebSocket operation. Cancelling one aborts
the socket, and an aborted socket sends no close frame, which is the only
way the client learns the server could not reach the host.
AnIdleSession_IsClosedWithTheIdleCode asserts that the code arrives.

Three departures from ADR 0004, recorded in it: awaited copy loops rather
than Pipelines (same backpressure, two 32 KiB buffers), no ?ticket=
fallback, and no device id in the ticket.

Tests: API 245, shell 582 (5 skipped), layout 170, SSH 110 including a
real login through the bridge, API client 30, contracts 25. Not run: the
Android build (its change is copy only) and the Alpine layout oracle.
This commit is contained in:
jaap-jan committed 2026-09-28 14:37:20 +02:00
1 parent 54bc142dce
commit b20f7cae04
51 files changed
+6455 -88

No files matched your search

+262
View File
@@ -0,0 +1,262 @@
using System.Net;
using System.Net.WebSockets;
using DodoSSH.Client.Api;
using DodoSSH.Client.Ssh;
using DodoSSH.Contracts;
namespace DodoSSH.Client.Session;
/// <summary>
/// Reaches a host through the server, for a host this machine cannot dial itself.
/// </summary>
/// <remarks>
/// Always present on <see cref="IVaultServer"/>, like <see cref="IVaultServer.Events"/>: a server that does
/// not relay supplies <see cref="UnavailableServerRelay"/>, whose answer is a sentence saying so. That keeps
/// the connect path on one shape, and it means the refusal a user reads is the same whether the server said
/// no before being asked or when it was.
/// </remarks>
public interface IServerRelay
{
/// <summary>Whether this server advertises a relay at all.</summary>
bool IsOffered { get; }
/// <summary>
/// Opens a relay to one host, ready for a connection to be made through it.
/// </summary>
/// <remarks>
/// Asks for a ticket, opens the socket and starts the bridge, in that order and at once — the ticket is
/// spent by the socket and dead thirty seconds after issue, so this is called by the connect that will
/// use it and never ahead of one.
/// </remarks>
/// <exception cref="ServerRelayException">The relay could not be opened; the message says why.</exception>
Task<RelayRoute> OpenAsync(Guid hostId, CancellationToken cancellationToken);
}
/// <summary>
/// An open relay, one connection long.
/// </summary>
/// <remarks>
/// Handing <see cref="Proxy"/> to a connection hands the bridge over with it, so the connection's own
/// disposal is what closes the relay. <see cref="DisposeAsync"/> is for a caller that ends up not
/// connecting; after a hand-over it does nothing, because the bridge's disposal is idempotent.
/// </remarks>
public sealed class RelayRoute : IAsyncDisposable
{
private readonly RelayBridge bridge;
internal RelayRoute(RelayBridge bridge) => this.bridge = bridge;
/// <summary>The loopback proxy to connect through, which owns the relay from then on.</summary>
public SshLoopbackProxy Proxy => bridge.Proxy;
/// <summary>
/// What the relay said when it closed, in words a user can act on; null when it has not closed, or
/// closed with nothing to say.
/// </summary>
/// <remarks>
/// For a connect that failed. SSH.NET reports a relay that hung up as a stream that ended — which reads
/// exactly like the direct connection that failed and sent the user to the relay — so the relay's own
/// reason, when it gave one, replaces it.
/// </remarks>
public string? Failure => bridge.CloseStatus is { } status ? Describe((int)status) : null;
/// <inheritdoc />
public ValueTask DisposeAsync() => bridge.DisposeAsync();
private static string? Describe(int code) => code switch
{
RelayProtocol.TargetUnreachableCloseCode =>
"The server relay could not reach this host. The server dials it on your behalf, so the "
+ "address has to be one the server can reach — check it from the server's side.",
RelayProtocol.TooManySessionsCloseCode =>
"The server relay has as many sessions open as it allows. Close one and try again.",
(int)WebSocketCloseStatus.EndpointUnavailable =>
"The server relay is restarting. Try again in a moment.",
RelayProtocol.IdleTimeoutCloseCode => "The server relay closed the connection for being idle.",
RelayProtocol.DurationLimitCloseCode =>
"The server relay closed the connection: it reached the longest session the server allows.",
_ => null,
};
}
/// <summary>A relay that could not be opened, with the reason in its message.</summary>
/// <remarks>
/// Its own type so the connect path can tell a relay refusal from a connection failure. The first has an
/// exact reason already, and running the reachability probe over it would dial the direct address — the one
/// the user chose the relay because they cannot reach — and append a finding about the wrong path.
/// </remarks>
public sealed class ServerRelayException : Exception
{
/// <summary>A refusal with nothing underneath it.</summary>
public ServerRelayException(string message)
: base(message)
{
}
/// <summary>A refusal and what caused it.</summary>
public ServerRelayException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>The relay of a server that does not offer one.</summary>
public sealed class UnavailableServerRelay : IServerRelay
{
private UnavailableServerRelay()
{
}
/// <summary>The one instance.</summary>
public static UnavailableServerRelay Instance { get; } = new();
/// <inheritdoc />
public bool IsOffered => false;
/// <inheritdoc />
public Task<RelayRoute> OpenAsync(Guid hostId, CancellationToken cancellationToken) =>
Task.FromException<RelayRoute>(new ServerRelayException(ServerRelay.NotOffered));
}
/// <summary>
/// The relay of a server that offers one: a ticket from the API, a socket, and a bridge.
/// </summary>
/// <remarks>
/// See ADR 0004 for the protocol and <c>docs/reaching-a-host-you-cannot-dial.md</c> for why the bridge
/// speaks SOCKS5. Every way this can fail is turned into a sentence here, because the codes are the
/// server's and the one place that should know what each means is the one that asked.
/// </remarks>
public sealed class ServerRelay : IServerRelay
{
/// <summary>What a user is told when the server they are signed in to does not relay.</summary>
internal const string NotOffered =
"This host is set to connect through the server relay, and this server does not offer one. "
+ "Untick “Connect through the server relay” in the host's settings to dial it directly.";
private readonly IRelayApi api;
private readonly Func<Uri, IReadOnlyList<string>, CancellationToken, Task<WebSocket>> connect;
/// <summary>A relay reached through this API client.</summary>
public ServerRelay(IRelayApi api)
: this(api, DialAsync)
{
}
/// <summary>A relay whose socket is opened by <paramref name="connect"/>, for tests.</summary>
internal ServerRelay(
IRelayApi api,
Func<Uri, IReadOnlyList<string>, CancellationToken, Task<WebSocket>> connect)
{
this.api = api;
this.connect = connect;
}
/// <inheritdoc />
public bool IsOffered => true;
/// <inheritdoc />
public async Task<RelayRoute> OpenAsync(Guid hostId, CancellationToken cancellationToken)
{
RelayTicketResponse ticket;
try
{
ticket = await api.IssueRelayTicketAsync(hostId, cancellationToken).ConfigureAwait(false);
}
catch (DodoSshApiException exception)
{
throw new ServerRelayException(Describe(exception), exception);
}
catch (HttpRequestException exception)
{
throw new ServerRelayException(
$"The server could not be reached to open the relay: {exception.Message}",
exception);
}
// The ticket as a second subprotocol, which is how ADR 0004 carries it: a header every WebSocket
// client can set. The server echoes the first alone.
var socket = await connect(
ticket.WebSocketUrl,
[RelayProtocol.SubProtocol, RelayProtocol.TicketProtocolPrefix + ticket.Ticket],
cancellationToken)
.ConfigureAwait(false);
return new RelayRoute(RelayBridge.Start(socket));
}
private static string Describe(DodoSshApiException exception) => exception.Code switch
{
ProblemCodes.RelayUnavailable => NotOffered,
// Deliberately unspecific on the server's side, so that it cannot be used to map the operator's
// network. The likeliest causes from here are the two this machine can check.
ProblemCodes.RelayTargetRejected =>
"The server refused to relay to this host. Check that the change turning the relay on has "
+ "synchronised, and that the address is one the server is allowed to reach; the server's log "
+ "records which.",
ProblemCodes.RelayLimitReached =>
"You have as many relay sessions open as the server allows. Close one and try again.",
_ => $"The server would not open the relay: {exception.Message}",
};
/// <summary>Opens the relay socket, and translates a refused upgrade into its reason.</summary>
/// <remarks>
/// The status of a refused upgrade is collected, which a constrained client could not do and this one
/// can: a 401 is a ticket the relay would not take — spent, expired, or issued by a node whose key ring
/// this one does not share — and asking again is the remedy.
/// </remarks>
private static async Task<WebSocket> DialAsync(
Uri url,
IReadOnlyList<string> protocols,
CancellationToken cancellationToken)
{
var socket = new ClientWebSocket();
try
{
foreach (var protocol in protocols)
{
socket.Options.AddSubProtocol(protocol);
}
socket.Options.CollectHttpResponseDetails = true;
await socket.ConnectAsync(url, cancellationToken).ConfigureAwait(false);
}
catch (WebSocketException exception)
{
var status = socket.HttpStatusCode;
socket.Dispose();
throw new ServerRelayException(
status == HttpStatusCode.Unauthorized
? "The server relay refused its ticket. Try connecting again."
: $"The server relay could not be reached: {exception.Message}",
exception);
}
catch
{
socket.Dispose();
throw;
}
if (!string.Equals(socket.SubProtocol, RelayProtocol.SubProtocol, StringComparison.Ordinal))
{
socket.Abort();
socket.Dispose();
throw new ServerRelayException(
"The server relay answered in a protocol this app does not speak. Update the app or the server.");
}
return socket;
}
}