diff --git a/serverbox/lib/core/utils/proxy_command_socket.dart b/serverbox/lib/core/utils/proxy_command_socket.dart index 3a89e35..300c261 100644 --- a/serverbox/lib/core/utils/proxy_command_socket.dart +++ b/serverbox/lib/core/utils/proxy_command_socket.dart @@ -33,6 +33,10 @@ class ProxyCommandSocket implements SSHSocket { _sink = sink, _done = done, _release = release { + _stderrDone = process.stderr.forEach(_captureStderr).onError((_, _) {}); + _exitObserved = process.exitCode.then((code) { + _exitCode = code; + }, onError: (_, _) {}); // The guest stays "in use" — and so cannot be deleted — for exactly as // long as the proxy runs. unawaited(_done.whenComplete(_releaseOnce).catchError((_) {})); @@ -44,8 +48,85 @@ class ProxyCommandSocket implements SSHSocket { final IOSink _sink; final Future _done; final void Function()? _release; + late final Future _stderrDone; + late final Future _exitObserved; + static const _stderrLimit = 2048; + final _stderrTail = []; + int? _exitCode; + bool _authenticated = false; + var _terminating = false; var _released = false; + void _terminate() { + if (_terminating) return; + _terminating = true; + if (_exitCode != null && _processGroupId == null) return; + ProcessTree.terminate(_process, _processGroupId); + } + + void _captureStderr(List data) { + if (_authenticated) return; + if (data.length >= _stderrLimit) { + _stderrTail + ..clear() + ..addAll(data.skip(data.length - _stderrLimit)); + return; + } + final overflow = _stderrTail.length + data.length - _stderrLimit; + if (overflow > 0) _stderrTail.removeRange(0, overflow); + _stderrTail.addAll(data); + } + + // Only forward known gateway wording. A helper can also print its command, + // identity paths or a configuration error to stderr. + static const _authMethod = + r'(?:publickey|password|keyboard-interactive|hostbased|' + r'gssapi-with-mic|gssapi-keyex|none)'; + static final _authDenial = RegExp( + r'^(?:[\w.@:\[\]-]+: )?' + '(permission denied(?: \\($_authMethod(?:,$_authMethod)*\\))?' + r'|access denied|(?:public[ -]?key )?authentication (?:failed|denied)' + r'|public[ -]?key (?:rejected|denied))\.?$', + caseSensitive: false, + ); + static final _stderrControls = RegExp(r'[\x00-\x09\x0b-\x1f\x7f-\x9f]'); + + Future _settleDiagnostics() async { + // stdout and stderr have independent readers. An EOF may arrive first, + // and dartssh2 will terminate the helper as soon as it sees that EOF. + await Future.wait([ + _stderrDone, + _exitObserved, + ]).timeout(const Duration(milliseconds: 50), onTimeout: () => []); + } + + void markAuthenticated() { + _authenticated = true; + _stderrTail.clear(); + } + + /// Reads the reason for an EOF before the SSH server sent its identification. + SSHErr? preHandshakeError() { + final stderr = utf8 + .decode(_stderrTail, allowMalformed: true) + .replaceAll(_stderrControls, ''); + for (final line in stderr.split('\n').reversed) { + final denial = _authDenial.firstMatch(line.trim()); + if (denial != null) { + return SSHErr( + type: SSHErrType.auth, + message: 'ProxyCommand: ${denial.group(1)}.', + ); + } + } + final code = _exitCode; + if (code == null || code <= 0) return null; + return SSHErr( + type: SSHErrType.connect, + message: _explain('ProxyCommand exited with code $code.'), + ); + } + void _releaseOnce() { if (_released) return; _released = true; @@ -107,16 +188,14 @@ class ProxyCommandSocket implements SSHSocket { 'Starting ProxyCommand for ${Redact.host(host)}:$port', ); + // A normal child exposes exitCode. ProcessTree uses the child tree when + // the command does not lead its own process group. final processFuture = Process.start( shellCommand.executable, shellCommand.arguments, // The guest's own PATH and home: Android's names directories that do // not exist inside it, and the command would find none of its tools. environment: guest == null ? null : AndroidRootfs.environment, - // This creates a separate Unix session. The returned PID is the final - // fork rather than the session leader, so its actual PGID is queried - // below. Windows cleanup uses taskkill /T. - mode: ProcessStartMode.detachedWithStdio, ); late final Process process; try { @@ -146,7 +225,17 @@ class ProxyCommandSocket implements SSHSocket { rethrow; } final processGroupId = await ProcessTree.groupId(process); + // Socket completion follows stdout. A helper can outlive its stdout or + // exit nonzero after forwarding has ended. final stdoutController = StreamController(); + final socket = ProxyCommandSocket._( + process: process, + processGroupId: processGroupId, + stream: stdoutController.stream, + sink: process.stdin, + done: stdoutController.done, + release: guest?.release, + ); process.stdout.listen( (data) { @@ -156,45 +245,14 @@ class ProxyCommandSocket implements SSHSocket { onError: (error, stackTrace) { stdoutController.addError(error, stackTrace); }, - onDone: () { - stdoutController.close(); + onDone: () async { + if (!socket._authenticated && !socket._terminating) { + await socket._settleDiagnostics(); + } + unawaited(stdoutController.close()); }, ); - process.stderr.listen( - (data) { - const maxLoggedBytes = 4096; - final capped = data.length <= maxLoggedBytes - ? data - : data.sublist(0, maxLoggedBytes); - final message = utf8.decode(capped, allowMalformed: true).trimRight(); - if (message.isEmpty) return; - final suffix = data.length > maxLoggedBytes ? ' [truncated]' : ''; - Loggers.app.warning('ProxyCommand stderr: $message$suffix'); - }, - onError: (error, stackTrace) { - Loggers.app.warning( - 'ProxyCommand stderr stream error', - error, - stackTrace, - ); - }, - ); - - // The SSH socket's lifecycle is the byte stream, not the helper process. - // A proxy that keeps its process alive after closing the transport would - // otherwise leave SSHSocket.done pending forever, while a shell that - // exits non-zero after forwarding ended would incorrectly report a - // transport failure. - final done = stdoutController.done; - - return ProxyCommandSocket._( - process: process, - processGroupId: processGroupId, - stream: stdoutController.stream, - sink: process.stdin, - done: done, - release: guest?.release, - ); + return socket; } /// [message], plus what a sandboxed build has almost certainly done to it. @@ -291,7 +349,7 @@ class ProxyCommandSocket implements SSHSocket { @override Future close() async { // Kill first so a child that ignores stdin EOF does not block close(). - ProcessTree.terminate(_process, _processGroupId); + _terminate(); try { await _sink.close().timeout(const Duration(seconds: 2)); } catch (_) {} @@ -299,9 +357,11 @@ class ProxyCommandSocket implements SSHSocket { await _done.timeout(const Duration(seconds: 2)).catchError((_) {}); } catch (_) {} // Ensure the process is gone even if the above timed out. - try { - _process.kill(ProcessSignal.sigkill); - } catch (_) {} + if (_exitCode == null) { + try { + _process.kill(ProcessSignal.sigkill); + } catch (_) {} + } try { if (!Platform.isWindows && _processGroupId != null) { Process.killPid(-_processGroupId, ProcessSignal.sigkill); @@ -315,7 +375,7 @@ class ProxyCommandSocket implements SSHSocket { @override void destroy() { - ProcessTree.terminate(_process, _processGroupId); + _terminate(); _releaseOnce(); } diff --git a/serverbox/lib/core/utils/server.dart b/serverbox/lib/core/utils/server.dart index 0f75702..167e262 100644 --- a/serverbox/lib/core/utils/server.dart +++ b/serverbox/lib/core/utils/server.dart @@ -371,6 +371,7 @@ Future> resolvePrivateKeysAsync( return keys; } +/// Opens the transport and starts authentication without waiting for it. Future genClient( Spi spi, { void Function(GenSSHClientStatus)? onStatus, @@ -629,8 +630,22 @@ Future genClient( prompt: hostKeyPrompt, ), ); - if (Diag.enabled) { - Diag.crumb(SbDiag.server, 'ssh connect ok', data: {'via': via}); + if (socket is ProxyCommandSocket || Diag.enabled) { + unawaited( + client.authenticated.then( + (_) { + if (socket is ProxyCommandSocket) socket.markAuthenticated(); + if (Diag.enabled) { + Diag.crumb(SbDiag.server, 'ssh connect ok', data: {'via': via}); + } + }, + onError: (Object e, StackTrace _) { + if (Diag.enabled) { + connectFailed('auth', _preHandshakeProxyError(client, e) ?? e); + } + }, + ), + ); } return client; } catch (e) { @@ -640,6 +655,29 @@ Future genClient( } } +/// Waits for SSH authentication and reports any ProxyCommand startup failure. +Future awaitSshAuthentication(SSHClient client) async { + try { + await client.authenticated; + } on SSHAuthAbortError catch (error, stackTrace) { + final proxyError = _preHandshakeProxyError(client, error); + if (proxyError == null) rethrow; + Error.throwWithStackTrace(proxyError, stackTrace); + } +} + +SSHErr? _preHandshakeProxyError(SSHClient client, Object error) { + final socket = client.socket; + if (socket is ProxyCommandSocket && + client.remoteVersion == null && + error is SSHAuthAbortError && + error.reason == null && + error.message.startsWith('Connection closed before authentication.')) { + return socket.preHandshakeError(); + } + return null; +} + /// The client itself, once there is a socket to build it on. /// /// Split out so that [genClient] has one place to undo the socket from: every diff --git a/serverbox/lib/data/provider/server/all.dart b/serverbox/lib/data/provider/server/all.dart index c56a6ae..42cb407 100644 --- a/serverbox/lib/data/provider/server/all.dart +++ b/serverbox/lib/data/provider/server/all.dart @@ -15,7 +15,6 @@ import 'package:server_box/core/utils/sudo_password.dart'; import 'package:server_box/data/model/app/error.dart'; import 'package:server_box/data/model/server/server.dart'; import 'package:server_box/data/model/server/server_private_info.dart'; -import 'package:server_box/data/model/server/try_limiter.dart'; import 'package:server_box/data/provider/port_forward_provider.dart'; import 'package:server_box/data/provider/remote_desktop.dart'; import 'package:server_box/data/provider/server/refresh_scheduler.dart'; @@ -179,12 +178,12 @@ class ServersNotifier extends _$ServersNotifier { )..remove(spi.id); state = state.copyWith(manualDisconnectedIds: newManualDisconnected); final serverNotifier = ref.read(serverProvider(spi.id).notifier); + serverNotifier.resetConnectionRetries(); await serverNotifier.refresh(interactive: true); return; } final serversToRefresh = >[]; - final idsToResetLimiter = []; for (final entry in state.servers.entries) { final serverId = entry.key; @@ -195,7 +194,11 @@ class ServersNotifier extends _$ServersNotifier { final serverState = ref.read(serverProvider(serverId)); final error = serverState.status.err; - if (error is SSHErr && error.type == SSHErrType.interactiveAuth) { + if (error is SSHErr && + (error.type == SSHErrType.interactiveAuth || + (!onlyFailed && + serverState.conn == ServerConn.failed && + error.type == SSHErrType.auth))) { continue; } @@ -203,7 +206,7 @@ class ServersNotifier extends _$ServersNotifier { if (serverState.conn != ServerConn.failed) { continue; } - idsToResetLimiter.add(serverId); + ref.read(serverProvider(serverId).notifier).resetConnectionRetries(); } if (serverState.conn == ServerConn.disconnected && !spi.autoConnect) { @@ -213,10 +216,6 @@ class ServersNotifier extends _$ServersNotifier { serversToRefresh.add(entry); } - for (final id in idsToResetLimiter) { - TryLimiter.reset(id); - } - await _refreshEach(serversToRefresh.map((e) => e.key).toList()); } @@ -237,7 +236,7 @@ class ServersNotifier extends _$ServersNotifier { if (ids.isEmpty) return; state = state.copyWith(manualDisconnectedIds: const {}); for (final id in ids) { - TryLimiter.reset(id); + ref.read(serverProvider(id).notifier).resetConnectionRetries(); } await _refreshEach(ids); } @@ -570,8 +569,6 @@ class ServersNotifier extends _$ServersNotifier { // Only reconnect if neccessary if (newSpi.shouldReconnect(old)) { - // Use [newSpi.id] instead of [old.id] because [old.id] may be changed - TryLimiter.reset(newSpi.id); unawaited(refresh(spi: newSpi)); } } diff --git a/serverbox/lib/data/provider/server/single.dart b/serverbox/lib/data/provider/server/single.dart index 051e95a..9ec7433 100644 --- a/serverbox/lib/data/provider/server/single.dart +++ b/serverbox/lib/data/provider/server/single.dart @@ -398,6 +398,7 @@ class ServerNotifier extends _$ServerNotifier { return; } + resetConnectionRetries(); _operationGeneration++; unawaited(_disposePersistentShell()); state.client?.close(); @@ -909,6 +910,12 @@ class ServerNotifier extends _$ServerNotifier { ({Spi spi, Stopwatch since, Object error, bool transient})? _backgroundShellFailure; + void resetConnectionRetries() { + TryLimiter.reset(state.spi.id); + TryLimiter.reset(_shellTryId); + _backgroundShellFailure = null; + } + /// Something that can run a command on this server. /// /// The one place that decides *how* a command reaches a server. Callers — @@ -1234,7 +1241,7 @@ class ServerNotifier extends _$ServerNotifier { onHostKeyPrompt: interactive ? null : (_) async => false, allowKeyPrompt: interactive, ); - await client.authenticated; + await awaitSshAuthentication(client); // Checked after, as every await in the refresh paths already does. // Authenticating takes as long as the far side and the user take, and // editing the server or disconnecting it bumps the generation — so @@ -1275,16 +1282,22 @@ class ServerNotifier extends _$ServerNotifier { TryLimiter.inc(_shellTryId); if (!interactive || resetRetries) { final cause = e is SSHAuthAbortError ? e.reason ?? e : e; - final droppedBeforeAuth = e is SSHAuthAbortError && + final droppedBeforeAuth = + e is SSHAuthAbortError && e.reason == null && e.message.startsWith('Connection closed before authentication.'); + final authRejected = e is SSHErr && e.type == SSHErrType.auth; _backgroundShellFailure = ( spi: spi, since: Stopwatch()..start(), error: e, - transient: isJumpFailoverError(cause) || e is TimeoutException || - droppedBeforeAuth || - (e is SSHAuthAbortError && e.message == 'Authentication timed out'), + transient: + !authRejected && + (isJumpFailoverError(cause) || + e is TimeoutException || + droppedBeforeAuth || + (e is SSHAuthAbortError && + e.message == 'Authentication timed out')), ); } Loggers.app.warning('Connect shell for ${spi.name}', e, s); @@ -1399,7 +1412,7 @@ class ServerNotifier extends _$ServerNotifier { return KeyboardInteractiveAuth.handle(server, request); }, ); - await client.authenticated; + await awaitSshAuthentication(client); if (!_isRefreshCurrent(operation, spi)) { client.close(); return; @@ -1455,16 +1468,40 @@ class ServerNotifier extends _$ServerNotifier { final durationMs = elapsed.elapsedMilliseconds; + // dartssh2 uses SSHAuthAbortError for transport loss as well as auth + // failures. A network drop must remain eligible for the next poll. + final transportAbort = + e is SSHAuthAbortError && + e.reason is! SSHHostkeyError && + (e.message.startsWith('Connection closed before authentication.') || + e.message == 'Authentication timed out'); + final SSHErr error; + if (keyboardInteractiveRequested && !interactive) { + error = SSHErr( + type: SSHErrType.interactiveAuth, + message: e.toString(), + ); + } else if (e is SSHErr && + (e.type == SSHErrType.auth || e.type == SSHErrType.connect)) { + error = e; + } else { + error = SSHErr( + type: e is SSHAuthError && !transportAbort + ? SSHErrType.auth + : SSHErrType.connect, + message: e.toString(), + ); + } + ConnectionResult failureResult; final errStr = e.toString().toLowerCase(); - if (errStr.contains('timed out') || errStr.contains('timeout')) { - failureResult = ConnectionResult.timeout; - } else if (errStr.contains('auth') || - errStr.contains('authentication') || - errStr.contains('permission denied') || - errStr.contains('access denied')) { + if (error.type == SSHErrType.auth || + error.type == SSHErrType.interactiveAuth) { failureResult = ConnectionResult.authFailed; - } else if (errStr.contains('connection refused') || + } else if (errStr.contains('timed out') || errStr.contains('timeout')) { + failureResult = ConnectionResult.timeout; + } else if (transportAbort || + errStr.contains('connection refused') || errStr.contains('no route to host') || errStr.contains('network') || errStr.contains('socket')) { @@ -1490,20 +1527,8 @@ class ServerNotifier extends _$ServerNotifier { if (!_isRefreshCurrent(operation, spi)) return; if (!(state.client?.isClosed ?? true)) return; - final SSHErrType errType; - if (keyboardInteractiveRequested && !interactive) { - errType = SSHErrType.interactiveAuth; - } else if (e is SSHAuthError) { - errType = SSHErrType.auth; - } else { - errType = SSHErrType.connect; - } _setFailedState( - _copyStatus( - state.status, - err: SSHErr(type: errType, message: e.toString()), - setErr: true, - ), + _copyStatus(state.status, err: error, setErr: true), closeClient: true, ); // Removed, not just marked dead: there is no session to reconnect to diff --git a/serverbox/test/unit/ssh/proxy_command_auth_test.dart b/serverbox/test/unit/ssh/proxy_command_auth_test.dart new file mode 100644 index 0000000..4418b65 --- /dev/null +++ b/serverbox/test/unit/ssh/proxy_command_auth_test.dart @@ -0,0 +1,315 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; +import 'package:fl_lib/fl_lib.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:server_box/core/utils/proxy_command_socket.dart'; +import 'package:server_box/core/utils/server.dart'; +import 'package:server_box/data/model/app/error.dart'; +import 'package:server_box/data/model/server/server.dart'; +import 'package:server_box/data/model/server/server_private_info.dart'; +import 'package:server_box/data/model/server/ssh_credential.dart'; +import 'package:server_box/data/model/server/try_limiter.dart'; +import 'package:server_box/data/provider/server/all.dart'; +import 'package:server_box/data/provider/server/single.dart'; +import 'package:server_box/data/res/store.dart'; + +const _denial = r"printf 'Permission denied (publickey).\n' >&2; exit 23"; +const _authError = 'ProxyCommand: Permission denied (publickey).'; +const _largeStderrPreamble = r""" + printf '%3072s\nAccess denied.\n' '' >&2 + IFS= read -r line && [ "$line" = 'release-fixture' ] || exit 1 +"""; + +Spi _server(String command, {String id = 'proxy-fixture'}) => Spi( + id: id, + name: id, + autoConnect: true, + ssh: SshCredential( + ip: 'target.example', + user: 'fixture', + proxyCommand: command, + ), +); + +Matcher _sshError(SSHErrType type, Matcher message) => isA() + .having((err) => err.type, 'type', type) + .having((err) => err.message, 'message', message); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('process-backed ProxyCommand', () { + Future connect(String command) async { + final client = await genClient( + _server(command), + knownHostFingerprints: {}, + ); + addTearDown(client.close); + return client; + } + + Future connectSocket(String command) async { + final socket = await ProxyCommandSocket.connect( + command: command, + host: 'target.example', + port: 22, + user: 'fixture', + originalHost: 'proxy-fixture', + jump: '', + ); + final proxy = socket as ProxyCommandSocket; + addTearDown(proxy.close); + return proxy; + } + + test( + 'reports a sanitized gateway denial and no success breadcrumb', + () async { + final sink = _ConnectionDiagnostics(); + Diag.install(sink); + addTearDown(Diag.uninstall); + + final client = await connect(r""" + exec 1>&- + printf '%4096s\n' '' >&2 + printf 'Could not open config file /synthetic/config: Permission denied\n' >&2 + printf 'fixture@gateway.example: Permission den' >&2 + printf 'ied (publickey).\r\n' >&2 + exit 23 + """); + await expectLater( + awaitSshAuthentication(client), + throwsA(_sshError(SSHErrType.auth, equals(_authError))), + ); + expect(sink.events, ['ssh connect', 'ssh connect failed']); + }, + ); + + test('reports a later gateway denial after a large stderr chunk', () async { + final socket = await connectSocket('$_largeStderrPreamble\n$_denial'); + final stdoutDone = socket.stream.drain(); + await _waitForStderrPreamble(socket); + await _releaseProxyFixture(socket); + await stdoutDone.timeout(const Duration(seconds: 5)); + expect( + socket.preHandshakeError(), + _sshError(SSHErrType.auth, equals(_authError)), + ); + }); + + test( + 'authentication clears a large stderr tail and keeps draining', + () async { + final socket = await connectSocket( + _largeStderrPreamble + + r""" + printf '%262144s\nAccess denied.\n' '' >&2 && + printf 'forwarded\n' + """, + ); + final output = utf8.decoder.bind(socket.stream).join(); + await _waitForStderrPreamble(socket); + socket.markAuthenticated(); + expect(socket.preHandshakeError(), isNull); + await _releaseProxyFixture(socket); + expect(await output.timeout(const Duration(seconds: 5)), 'forwarded\n'); + expect(socket.preHandshakeError(), isNull); + }, + ); + + test('reports a nonzero exit without exposing local stderr', () async { + final client = await connect(r""" + printf 'Could not open config file /synthetic/config: Permission denied\n' >&2 + exit 17 + """); + await expectLater( + awaitSshAuthentication(client), + throwsA( + _sshError( + SSHErrType.connect, + allOf( + startsWith('ProxyCommand exited with code 17.'), + isNot(contains('/synthetic/config')), + ), + ), + ), + ); + }); + + test( + 'a clean EOF before the banner still reports a transport abort', + () async { + final client = await connect('exit 0'); + await expectLater( + awaitSshAuthentication(client), + throwsA( + isA().having( + (err) => err.reason, + 'reason', + isNull, + ), + ), + ); + }, + ); + + test('forwards input and output unchanged', () async { + final socket = await connectSocket('exec cat'); + final echo = socket.stream.first; + socket.sink.add(utf8.encode('synthetic payload\n')); + await socket.flush(); + expect(utf8.decode(await echo), 'synthetic payload\n'); + }); + }, skip: !(Platform.isLinux || Platform.isMacOS)); + + group('proxy connection retries', () { + late Directory directory; + late ProviderContainer container; + + setUpAll(() async { + directory = await Directory.systemTemp.createTemp('proxy-auth-fixture-'); + Paths.doc = directory.path; + }); + + tearDownAll(() => directory.delete(recursive: true)); + + setUp(() async { + SqliteDb.openInMemory(); + await Stores.init(); + container = ProviderContainer(); + }); + + tearDown(() async { + container.dispose(); + TryLimiter.clear(); + await getIt.reset(); + await SqliteDb.close(); + }); + + test( + 'polling pauses on auth while manual refresh and edits dial again', + () async { + final attempts = File('${directory.path}/attempts'); + final quotedPath = "'${attempts.path.replaceAll("'", "'\"'\"'")}'"; + final spi = _server('printf x >> $quotedPath; $_denial'); + Stores.server.put(spi); + final servers = container.read(serversProvider.notifier); + final provider = serverProvider(spi.id); + SSHErr statusError() => container.read(provider).status.err! as SSHErr; + + Stores.setting.maxRetryCount.put(0); + await servers.refresh(); + expect(container.read(provider).conn, ServerConn.failed); + expect(statusError(), _sshError(SSHErrType.auth, equals(_authError))); + await servers.refresh(); + await servers.refresh(); + expect(await attempts.readAsString(), 'x'); + + Stores.setting.maxRetryCount.put(1); + expect(TryLimiter.canTry(spi.id), isFalse); + await servers.refresh(onlyFailed: true); + expect(await attempts.readAsString(), 'xx'); + + final manual = servers.refresh(spi: spi); + _drawFrame(); + await manual; + expect(await attempts.readAsString(), 'xxx'); + + final retry = Completer(); + final subscription = container.listen(provider, (_, next) { + if (next.conn == ServerConn.failed && + (next.status.err as SSHErr?)?.type == SSHErrType.connect && + !retry.isCompleted) { + retry.complete(); + } + }); + addTearDown(subscription.close); + await servers.updateServer( + spi, + _server('printf y >> $quotedPath; exit 0'), + ); + _drawFrame(); + await retry.future.timeout(const Duration(seconds: 5)); + expect(await attempts.readAsString(), 'xxxy'); + + Stores.setting.maxRetryCount.put(0); + await servers.refresh(); + expect(await attempts.readAsString(), 'xxxyy'); + }, + ); + + test('only transient shell errors retry after the cooldown', () async { + Stores.setting.maxRetryCount.put(1); + final rejected = _server(_denial); + final dropped = _server('exit 0', id: 'transport-fixture'); + Stores.server.put(rejected); + Stores.server.put(dropped); + var rejectedDials = 0; + var droppedDials = 0; + final rejectedNotifier = container.read( + serverProvider(rejected.id).notifier, + ); + final droppedNotifier = container.read( + serverProvider(dropped.id).notifier, + ); + Future checkRejected() => expectLater( + rejectedNotifier.ensureShellClient( + interactive: false, + onDial: () => rejectedDials++, + ), + throwsA(_sshError(SSHErrType.auth, equals(_authError))), + ); + Future checkDropped() => expectLater( + droppedNotifier.ensureShellClient( + interactive: false, + onDial: () => droppedDials++, + ), + throwsA(isA()), + ); + + await checkRejected(); + await checkDropped(); + await Future.delayed(const Duration(seconds: 31)); + await checkRejected(); + await checkDropped(); + expect(rejectedDials, 1); + expect(droppedDials, 2); + }, timeout: const Timeout(Duration(minutes: 1))); + }, skip: !(Platform.isLinux || Platform.isMacOS)); +} + +Future _waitForStderrPreamble(ProxyCommandSocket socket) async { + // Keep the child blocked until its first write has reached the stderr reader. + final timer = Stopwatch()..start(); + while (socket.preHandshakeError()?.message != + 'ProxyCommand: Access denied.') { + if (timer.elapsed >= const Duration(seconds: 3)) { + fail('ProxyCommand stderr preamble did not arrive'); + } + await Future.delayed(const Duration(milliseconds: 5)); + } +} + +Future _releaseProxyFixture(ProxyCommandSocket socket) async { + socket.sink.add(utf8.encode('release-fixture\n')); + await socket.flush(); +} + +void _drawFrame() { + SchedulerBinding.instance.handleBeginFrame(null); + SchedulerBinding.instance.handleDrawFrame(); +} + +class _ConnectionDiagnostics extends DiagnosticsSink { + final events = []; + + @override + void breadcrumb(Breadcrumb crumb) { + if (crumb.message.startsWith('ssh connect')) events.add(crumb.message); + } +}