Recover from zero servers, sign each machine in on its own, offer every route

- Removing the primary machine hands pipelines/runs to the next saved machine
  on native hosts; removing the last machine returns to the connect screen
  instead of stranding the app on "Server endpoint not configured".
- Add server probes the new machine and asks for its own password in the same
  page; Settings rows show Connected / Sign in required / Unreachable with the
  reason and offer Sign in; no other machine's credential is ever reused.
- Unreachable addresses explain why: a TLS failure against an IP points at the
  Tailscale name, a non-Pipelines answer points at the port.
- Discovered machines list every advertised route (LAN, Tailscale IP, Tailscale
  name) as a checklist; chosen routes are saved as one machine.
- tool/connection_probe.dart replays the native login and websocket against
  real addresses for diagnosis.
This commit is contained in:
2026-11-08 23:59:20 +00:00
parent 929e4cc017
commit 079924d19a
40 changed files with 2524 additions and 259 deletions
@@ -0,0 +1,185 @@
import 'dart:async';
import 'package:flutter/material.dart' hide ConnectionState;
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
import 'package:pipelines_app/application/pipelines_root.dart';
import 'package:pipelines_app/application/server_endpoint.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/chat/chat_server_pool.dart';
import 'package:pipelines_app/core/servers/server_catalog.dart';
import 'package:pipelines_app/core/servers/server_catalog_store.dart';
import 'package:pipelines_app/core/session/server_session.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/onboarding/onboarding_flow.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
class _Gateway implements ApiGateway {
final events = StreamController<JsonMap>.broadcast();
@override
Stream<JsonMap> get frames => events.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async =>
switch (type) {
'attention_acks' || 'ack_attention' => {
'type': 'attention_acks',
'attention_acks': {'chat_seen': {}, 'dismissed': []},
},
_ => {'type': 'chat_sessions', 'chat_sessions': <Object>[]},
};
}
ChatMachineConnection _connection(SavedServer server) {
final states = StreamController<ConnectionState>.broadcast();
return ChatMachineConnection(
gateway: _Gateway(),
endpoint: () => server.endpoints.first,
connected: () => true,
states: states.stream,
close: states.close,
retry: () async {},
);
}
SavedServer saved(String id) => SavedServer.validated(
id: id,
name: id,
endpoints: ['wss://$id.test/connect'],
);
Future<void> frames(WidgetTester tester) async {
for (var frame = 0; frame < 12; frame++) {
await tester.pump(const Duration(milliseconds: 20));
}
}
void main() {
setUp(() async {
SharedPreferences.setMockInitialValues({
'pipelines.session.v2.mac.cookie': 'pipelines_session=mac',
'pipelines.session.v2.tank.cookie': 'pipelines_session=tank',
});
await ServerSession.load();
});
testWidgets(
'removing the primary, then the last machine, returns to Add server',
(tester) async {
final store = MemoryServerCatalogStore(
catalog: ServerCatalog(
servers: [saved('mac'), saved('tank')],
selectedId: 'mac',
),
);
PipelinesClient factory() => PipelinesClient(
channelFactory: (_) => FakeChannel()..readyCompleter.complete(),
);
await tester.pumpWidget(
PipelinesRoot(
nativeUpdatesSupported: false,
server: ServerEndpoint.resolve(
base: Uri.parse('file:///'),
web: false,
configured: 'wss://mac.test/connect',
),
signedIn: true,
catalogStore: store,
clientFactory: factory,
settingsStore: MemorySettingsStore(),
check: (_) async => SessionState.signedIn,
chatPoolFactory: (servers) => ChatServerPool(
servers,
web: false,
connect: (server) async => _connection(server),
probeProfile: ({required id, required endpoints}) async =>
const ServerProbeResult(SessionState.signedIn),
),
),
);
await frames(tester);
final app = tester.widget<PipelinesApp>(find.byType(PipelinesApp));
expect(app.serverId, 'mac');
expect(app.servers!.authenticator, isNotNull);
// The primary goes: the other machine takes over pipelines and runs
// instead of the app losing its endpoint.
// Activation waits for a frame, so pump while the removal runs.
final removedPrimary = app.servers!.remove('mac');
await frames(tester);
expect(await removedPrimary, isTrue);
final remaining = tester.widget<PipelinesApp>(find.byType(PipelinesApp));
expect(remaining.serverId, 'tank');
expect(remaining.server.uri, Uri.parse('wss://tank.test/connect'));
expect(remaining.server.requiresConfiguration, isFalse);
expect(find.text('Server endpoint not configured'), findsNothing);
// The last machine goes: Add server comes back, nothing is deleted.
final removedLast = remaining.servers!.remove('tank');
await frames(tester);
expect(await removedLast, isTrue);
expect(find.byType(PipelinesApp), findsNothing);
expect(find.byType(OnboardingFlow), findsOneWidget);
expect(find.byKey(const Key('onboarding-server')), findsOneWidget);
expect(find.byKey(const Key('discovery-scan')), findsOneWidget);
expect(store.catalog?.servers, isEmpty);
// Both sign-ins survive for when the machines are added again.
final preferences = await SharedPreferences.getInstance();
expect(
preferences.getString('pipelines.session.v2.mac.cookie'),
'pipelines_session=mac',
);
await tester.pumpWidget(const SizedBox.shrink());
},
);
testWidgets('removing a non-primary last machine also recovers', (
tester,
) async {
// The pre-fix path: the catalog ends up with a machine that is not the
// primary (a browser-aligned or stale selection), and removing it never
// activated anything.
final store = MemoryServerCatalogStore(
catalog: ServerCatalog(servers: [saved('mac'), saved('tank')]),
);
PipelinesClient factory() => PipelinesClient(
channelFactory: (_) => FakeChannel()..readyCompleter.complete(),
);
await tester.pumpWidget(
PipelinesRoot(
nativeUpdatesSupported: false,
server: ServerEndpoint.resolve(
base: Uri.parse('file:///'),
web: false,
configured: '',
),
signedIn: true,
catalogStore: store,
clientFactory: factory,
settingsStore: MemorySettingsStore(),
check: (_) async => SessionState.signedIn,
chatPoolFactory: (servers) => ChatServerPool(
servers,
web: false,
connect: (server) async => _connection(server),
probeProfile: ({required id, required endpoints}) async =>
const ServerProbeResult(SessionState.signedIn),
),
),
);
await frames(tester);
final app = tester.widget<PipelinesApp>(find.byType(PipelinesApp));
expect(app.serverId, isNull);
final removedFirst = app.servers!.remove('mac');
await frames(tester);
expect(await removedFirst, isTrue);
final removedLast = app.servers!.remove('tank');
await frames(tester);
expect(await removedLast, isTrue);
expect(find.byType(OnboardingFlow), findsOneWidget);
expect(find.text('Server endpoint not configured'), findsNothing);
await tester.pumpWidget(const SizedBox.shrink());
});
}
@@ -6,6 +6,7 @@ import 'package:pipelines_app/core/session/server_session.dart';
import 'package:pipelines_app/core/servers/server_catalog.dart';
import 'package:pipelines_app/core/servers/server_catalog_store.dart';
import 'package:pipelines_app/core/servers/chat/chat_server_pool.dart';
import 'package:pipelines_app/core/servers/machine_access.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/settings/server_connections.dart';
@@ -279,4 +280,77 @@ void main() {
}
},
);
test('a socket that did not open is classified with the machine\'s own login', () async {
final profile = _server('tank');
final servers = await _servers([profile]);
final probed = <String>[];
var verdict = SessionState.signedOut;
late _Machine machine;
final pool = ChatServerPool(
servers,
web: false,
connect: (server) async {
machine = _Machine(server);
machine.connection = ChatMachineConnection(
gateway: machine.gateway,
endpoint: () => server.endpoints.first,
connected: () => false,
states: machine.states.stream,
close: () async {},
retry: () async {},
);
return machine.connection;
},
probeProfile: ({required id, required endpoints}) async {
probed.add('$id:${endpoints.map((u) => u.host).join(',')}');
return ServerProbeResult(verdict, reason: 'no route');
},
);
try {
await _flush();
expect(probed, ['tank:tank.test']);
expect(pool.status('tank')?.access, MachineAccess.needsPassword);
expect(pool.status('tank')?.detail, 'tank asks for its password.');
verdict = SessionState.unreachable;
await pool.retry('tank');
await _flush();
expect(pool.status('tank')?.access, MachineAccess.unreachable);
expect(pool.status('tank')?.detail, 'no route');
// The editor's own probe uses the same per-machine login, not the pool.
verdict = SessionState.signedIn;
final access = await pool.probe(profile);
expect(access.access, MachineAccess.connected);
expect(probed, hasLength(3));
expect(pool.status('missing'), isNull);
} finally {
pool.dispose();
servers.dispose();
await _flush();
await machine.finish();
}
});
test('a relay that wants a password is not reported as unreachable', () async {
final profile = _server('tank');
final servers = await _servers([profile]);
final pool = ChatServerPool(
servers,
web: true,
connect: (server) async =>
throw const MachineSignInRequired('Sign in to this machine.'),
probeProfile: ({required id, required endpoints}) async =>
fail('browsers never probe the login page directly'),
);
try {
await _flush();
expect(pool.status('tank')?.access, MachineAccess.needsPassword);
expect(pool.status('tank')?.detail, 'Sign in to this machine.');
expect(pool.machines.single.error, 'Sign in to this machine.');
} finally {
pool.dispose();
servers.dispose();
await _flush();
}
});
}
@@ -0,0 +1,104 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/servers/server_probe.dart';
import 'package:pipelines_app/core/session/login_probe.dart';
import 'package:pipelines_app/core/session/server_session.dart';
import 'package:pipelines_app/core/session/server_session_io.dart' as io;
void main() {
final login = Uri.parse('https://mac.tail1.ts.net:8443/login');
test('the login page, a redirect and other answers are told apart', () {
expect(
ServerSession.interpret(
login,
const LoginProbe(status: 200, loginPage: true),
).state,
SessionState.signedOut,
);
expect(
ServerSession.interpret(login, const LoginProbe(status: 302)).state,
SessionState.signedIn,
);
final other = ServerSession.interpret(
login,
const LoginProbe(status: 200, loginPage: false),
);
expect(other.state, SessionState.unreachable);
expect(other.reason, contains('not with the Pipelines sign-in page'));
expect(other.reason, contains('mac.tail1.ts.net:8443'));
final missing = ServerSession.interpret(
login,
const LoginProbe(status: 404),
);
expect(missing.state, SessionState.unreachable);
expect(missing.reason, contains('HTTP 404'));
final failed = ServerSession.interpret(
login,
const LoginProbe(failure: 'Could not reach mac.tail1.ts.net:8443: down.'),
);
expect(failed.state, SessionState.unreachable);
expect(failed.reason, 'Could not reach mac.tail1.ts.net:8443: down.');
expect(
LoginProbe.isPipelinesLogin(
'<form method="post" action="/login"><input name="password"></form>',
),
isTrue,
);
expect(LoginProbe.isPipelinesLogin('<h1>Some other app</h1>'), isFalse);
});
test('TLS against a Tailscale IP explains the name requirement', () {
final byIp = io.describeFailure(
Uri.parse('https://100.85.25.33:8443/login'),
const HandshakeException('alert internal error'),
);
expect(byIp, contains('does not cover an IP address'));
expect(byIp, contains('wss://<name>.ts.net:8443/connect'));
final byName = io.describeFailure(
login,
const HandshakeException('certificate verify failed'),
);
expect(byName, contains('HTTPS connection to mac.tail1.ts.net:8443 failed'));
expect(byName, contains('certificate verify failed'));
expect(
io.describeFailure(
login,
const SocketException('refused', osError: OSError('Connection refused', 61)),
),
'Could not reach mac.tail1.ts.net:8443: Connection refused.',
);
expect(
io.describeFailure(login, TimeoutException('slow')),
contains('no answer within 10 seconds'),
);
});
test('probing several addresses reports the first reason when all fail', () async {
final result = await probeServerAddresses(
[Uri.parse('wss://a.test/connect'), Uri.parse('ws://b.test/connect')],
probe: (uri) async => ServerProbeResult(
SessionState.unreachable,
reason: 'no ${uri.host}',
),
isCurrent: () => true,
);
expect(result.state, SessionState.unreachable);
expect(result.endpoint, Uri.parse('wss://a.test/connect'));
expect(result.reason, 'no a.test');
final reached = await probeServerAddresses(
[Uri.parse('wss://a.test/connect'), Uri.parse('ws://b.test/connect')],
probe: (uri) async => uri.host == 'b.test'
? const ServerProbeResult(SessionState.signedOut)
: const ServerProbeResult(SessionState.unreachable, reason: 'x'),
isCurrent: () => true,
);
expect(reached.endpoint, Uri.parse('ws://b.test/connect'));
expect(reached.state, SessionState.signedOut);
expect(reached.reason, isNull);
final plain = probeFromCheck((_) async => SessionState.signedIn);
expect((await plain(login)).state, SessionState.signedIn);
});
}
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/onboarding/discovery/browser_server_discovery.dart';
import 'package:pipelines_app/features/onboarding/discovery/discovered_server.dart';
void main() {
test(
@@ -57,4 +58,36 @@ void main() {
);
},
);
test('advertised routes are listed; older servers yield the LAN only', () async {
final discovery = BrowserServerDiscovery(
fetch: () async => jsonEncode({
'discovered_servers': [
{
'name': 'box',
'endpoint': 'ws://10.0.0.75:8083/connect',
'auth': 'password',
'addresses': [
{'kind': 'lan', 'endpoint': 'ws://10.0.0.75:8083/connect'},
{'kind': 'tailscale', 'endpoint': 'ws://100.85.25.33:8083/connect'},
{'kind': 'public', 'endpoint': 'wss://box.tail1.ts.net:8443/connect'},
{'kind': 'mystery', 'endpoint': 'ws://1.2.3.4:1/connect'},
{'kind': 'public', 'endpoint': 'http://bad.example'},
],
},
{'name': 'old', 'endpoint': 'ws://10.0.0.100:8082/connect', 'auth': 'password'},
],
}),
);
final servers = await discovery.scan().first;
expect(servers, hasLength(2));
expect(servers.first.endpoints.map((u) => u.toString()), [
'ws://10.0.0.75:8083/connect',
'ws://100.85.25.33:8083/connect',
'wss://box.tail1.ts.net:8443/connect',
]);
expect(servers.first.addresses[2].route, DiscoveredRoute.public);
expect(servers.last.addresses, hasLength(1));
expect(servers.last.addresses.single.route, DiscoveredRoute.lan);
});
}
@@ -65,4 +65,64 @@ void main() {
expect(platformServerDiscovery(web: true), isNotNull);
expect(platformServerDiscovery(web: false), isNotNull);
});
test('TXT ts/public list every route to the same machine', () {
final server = DiscoveredServer.fromRecord(
instance: 'Pipelines-box',
addresses: ['10.0.0.75'],
port: 8083,
attributes: {
'name': 'box',
'path': '/connect',
'tls': '0',
'auth': 'password',
'ts': '100.85.25.33, 10.0.0.9,100.70.1.1',
'public': 'https://box.tail1.ts.net:8443',
},
)!;
expect(server.endpoint, Uri.parse('ws://10.0.0.75:8083/connect'));
expect(server.addresses.map((a) => a.route), [
DiscoveredRoute.lan,
DiscoveredRoute.tailscale,
DiscoveredRoute.tailscale,
DiscoveredRoute.public,
]);
expect(server.endpoints.map((u) => u.toString()), [
'ws://10.0.0.75:8083/connect',
'ws://100.85.25.33:8083/connect',
'ws://100.70.1.1:8083/connect',
'wss://box.tail1.ts.net:8443/connect',
]);
expect(server.addresses.last.label, 'Tailscale name (HTTPS)');
expect(server.addresses[1].label, 'Tailscale IP');
final chosen = server.choosing([server.addresses.last, server.addresses[1]]);
expect(chosen.endpoint, Uri.parse('wss://box.tail1.ts.net:8443/connect'));
expect(chosen.secure, isTrue);
expect(chosen.endpoints, hasLength(2));
expect(chosen.name, 'box');
expect(chosen.passwordRequired, isTrue);
expect(server.choosing(const []), server);
final unsafe = DiscoveredServer.fromRecord(
instance: 'Pipelines-box',
addresses: ['10.0.0.75'],
port: 8083,
attributes: {
'ts': 'evil.example,10.0.0.9',
'public': 'javascript:alert(1)',
},
)!;
expect(unsafe.addresses, hasLength(1));
expect(
DiscoveredServer.publicEndpoint('https://user@box.ts.net/app?x=1'),
isNull,
);
expect(
DiscoveredServer.publicEndpoint('http://10.0.0.5:8083/'),
Uri.parse('ws://10.0.0.5:8083/connect'),
);
expect(DiscoveredServer.isTailscaleIPv4('100.127.0.1'), isTrue);
expect(DiscoveredServer.isTailscaleIPv4('100.128.0.1'), isFalse);
});
}
@@ -169,4 +169,109 @@ void main() {
await tester.pumpWidget(host(const SizedBox()));
expect(discovery.cancelled, 1);
});
testWidgets('a machine with several routes lets the operator choose them', (
tester,
) async {
final lan = Uri.parse('ws://10.0.0.75:8083/connect');
final ts = Uri.parse('ws://100.85.25.33:8083/connect');
final name = Uri.parse('wss://mac.tail1.ts.net:8443/connect');
final mac = DiscoveredServer(
name: 'mac',
host: '10.0.0.75',
port: 8083,
addresses: [
DiscoveredAddress(route: DiscoveredRoute.lan, endpoint: lan),
DiscoveredAddress(route: DiscoveredRoute.tailscale, endpoint: ts),
DiscoveredAddress(route: DiscoveredRoute.public, endpoint: name),
],
);
final machines = <(List<String>, String)>[];
await tester.pumpWidget(
host(
OnboardingFlow(
discovery: discovery,
check: (uri) async {
checked.add(uri);
return SessionState.signedOut;
},
saveMachine: (endpoints, name) async => machines.add((endpoints, name)),
onDone: (_) {},
),
),
);
await tester.tap(find.byKey(const Key('discovery-scan')));
await tester.pump();
discovery.current.add([mac]);
await tester.pump();
expect(find.text('3 addresses · password'), findsOneWidget);
// Tapping a multi-route machine expands its routes instead of choosing one.
await tester.tap(find.byKey(const Key('discovered-10.0.0.75:8083')));
await tester.pumpAndSettle();
expect(find.text('Local network'), findsOneWidget);
expect(find.text('Tailscale IP'), findsOneWidget);
expect(find.text('Tailscale name (HTTPS)'), findsOneWidget);
expect(find.text(name.toString()), findsOneWidget);
await tester.ensureVisible(find.byKey(Key('discovered-route-$name')));
await tester.tap(find.byKey(Key('discovered-route-$name')));
await tester.pump();
await tester.ensureVisible(find.byKey(const Key('discovered-use-10.0.0.75:8083')));
await tester.tap(find.byKey(const Key('discovered-use-10.0.0.75:8083')));
await tester.pumpAndSettle();
expect(
tester.widget<TextField>(find.byKey(const Key('onboarding-server'))).controller!.text,
lan.toString(),
);
expect(find.byKey(const Key('onboarding-routes')), findsOneWidget);
await tester.ensureVisible(find.byKey(const Key('onboarding-next')));
await tester.tap(find.byKey(const Key('onboarding-next')));
await tester.pumpAndSettle();
expect(checked, [lan]);
expect(machines.single.$1, [lan.toString(), name.toString()]);
expect(machines.single.$2, 'mac');
expect(find.byKey(const Key('onboarding-password')), findsOneWidget);
});
testWidgets('a typed address drops the discovered routes', (tester) async {
final lan = Uri.parse('ws://10.0.0.75:8083/connect');
final ts = Uri.parse('ws://100.85.25.33:8083/connect');
final mac = DiscoveredServer(
name: 'mac',
host: '10.0.0.75',
port: 8083,
addresses: [
DiscoveredAddress(route: DiscoveredRoute.lan, endpoint: lan),
DiscoveredAddress(route: DiscoveredRoute.tailscale, endpoint: ts),
],
);
final machines = <(List<String>, String)>[];
await tester.pumpWidget(
host(
OnboardingFlow(
discovery: discovery,
check: (uri) async => SessionState.signedOut,
saveMachine: (endpoints, name) async => machines.add((endpoints, name)),
onDone: (_) {},
),
),
);
await tester.tap(find.byKey(const Key('discovery-scan')));
await tester.pump();
discovery.current.add([mac]);
await tester.pump();
await tester.tap(find.byKey(const Key('discovered-10.0.0.75:8083')));
await tester.pumpAndSettle();
await tester.ensureVisible(find.byKey(const Key('discovered-use-10.0.0.75:8083')));
await tester.tap(find.byKey(const Key('discovered-use-10.0.0.75:8083')));
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('onboarding-server')),
'ws://10.0.0.200:8083/connect',
);
await tester.ensureVisible(find.byKey(const Key('onboarding-next')));
await tester.tap(find.byKey(const Key('onboarding-next')));
await tester.pumpAndSettle();
expect(machines.single.$1, ['ws://10.0.0.200:8083/connect']);
expect(machines.single.$2, 'mac');
});
}
@@ -169,4 +169,36 @@ void main() {
expect(find.byKey(const Key('onboarding-server')), findsNothing);
expect(find.text('Change server'), findsNothing);
});
testWidgets('an unreachable address shows the probe\'s own reason', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: OnboardingFlow(
probe: (uri) async => ServerProbeResult(
SessionState.unreachable,
reason:
'The HTTPS certificate of ${uri.host}:${uri.port} does not '
'cover an IP address.',
),
onDone: (_) {},
),
),
);
await tester.enterText(
find.byKey(const Key('onboarding-server')),
'wss://100.85.25.33:8443/connect',
);
await tester.tap(find.byKey(const Key('onboarding-next')));
await tester.pumpAndSettle();
expect(
find.text(
'The HTTPS certificate of 100.85.25.33:8443 does not cover an IP '
'address.',
),
findsOneWidget,
);
expect(find.byKey(const Key('onboarding-password')), findsNothing);
});
}
@@ -116,7 +116,12 @@ void main() {
find.byKey(const Key('server-profile-name')),
'My Linux',
);
await tester.ensureVisible(find.text('Save server'));
await tester.scrollUntilVisible(
find.text('Save server'),
120,
scrollable: find.byType(Scrollable).last,
);
await tester.pumpAndSettle();
await tester.tap(find.text('Save server'));
await tester.pumpAndSettle();
expect(saved!.name, 'My Linux');
@@ -0,0 +1,280 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/servers/machine_access.dart';
import 'package:pipelines_app/core/servers/server_catalog.dart';
import 'package:pipelines_app/core/servers/server_catalog_store.dart';
import 'package:pipelines_app/features/settings/saved_server_editor.dart';
import 'package:pipelines_app/features/settings/saved_server_row.dart';
import 'package:pipelines_app/features/settings/saved_servers_section.dart';
import 'package:pipelines_app/features/settings/server_connections.dart';
/// A machine authenticator the test scripts: what each probe answers and
/// which password each machine accepts.
class FakeAuthenticator extends ChangeNotifier implements MachineAuthenticator {
final verdicts = <String, MachineAccessResult>{};
final passwords = <String, String>{};
final probes = <String>[];
final signIns = <(String, String)>[];
@override
MachineAccessResult? status(String id) => verdicts[id];
@override
Future<MachineAccessResult> probe(SavedServer server) async {
probes.add(server.id);
return verdicts[server.id] ??
const MachineAccessResult(MachineAccess.connected);
}
@override
Future<String?> authenticate(SavedServer server, String password) async {
signIns.add((server.id, password));
if (passwords[server.id] != password) return 'Wrong password.';
verdicts[server.id] = const MachineAccessResult(MachineAccess.connected);
notifyListeners();
return null;
}
}
Future<void> revealSave(WidgetTester tester) async {
await tester.scrollUntilVisible(
find.text('Save server'),
120,
scrollable: find.byType(Scrollable).last,
);
await tester.pumpAndSettle();
}
Future<void> addServer(
WidgetTester tester, {
required String name,
required String address,
}) async {
await tester.tap(find.text('Add server'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('server-profile-name')), name);
await tester.enterText(
find.byKey(const Key('server-profile-addresses')),
address,
);
await revealSave(tester);
await tester.tap(find.text('Save server'));
await tester.pumpAndSettle();
}
void main() {
for (final cupertino in [false, true]) {
testWidgets('a new machine asks for its own password ($cupertino)', (
tester,
) async {
final connections = ServerConnections(
store: MemoryServerCatalogStore(
catalog: ServerCatalog(
servers: [
SavedServer.validated(
id: 'mac',
name: 'Mac',
endpoints: ['ws://10.0.0.75:8083/connect'],
),
],
selectedId: 'mac',
),
),
onSelected: (_) async {},
);
addTearDown(connections.dispose);
await connections.load();
final auth = FakeAuthenticator()
..verdicts['mac'] = const MachineAccessResult(MachineAccess.connected);
connections.authenticator = auth;
final body = SingleChildScrollView(
child: SavedServersSection(connections: connections),
);
await tester.pumpWidget(
cupertino
? CupertinoApp(
home: CupertinoPageScaffold(child: SafeArea(child: body)),
)
: MaterialApp(home: Scaffold(body: body)),
);
expect(find.text('Connected'), findsOneWidget);
// The new machine is unknown to the authenticator until saved; a
// password verdict arrives for whatever id the editor assigned.
auth.verdicts.addAll({
for (final id in ['pending']) id: const MachineAccessResult(
MachineAccess.needsPassword,
),
});
await tester.tap(find.text('Add server'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('server-profile-name')), 'tank');
await tester.enterText(
find.byKey(const Key('server-profile-addresses')),
'ws://10.0.0.100:8082/connect',
);
// Whatever id the editor chose, that machine wants a password.
connections.addListener(() {
for (final server in connections.catalog.servers) {
auth.verdicts.putIfAbsent(
server.id,
() => const MachineAccessResult(MachineAccess.needsPassword),
);
auth.passwords.putIfAbsent(server.id, () => 'tank-secret');
}
});
await revealSave(tester);
await tester.tap(find.text('Save server'));
await tester.pumpAndSettle();
final tank = connections.catalog.servers.firstWhere((s) => s.name == 'tank');
expect(auth.probes, [tank.id]);
// Saved, and the editor now asks this machine's password; the first
// machine's sign-in is not reused.
expect(find.byKey(const Key('server-profile-password')), findsOneWidget);
expect(find.textContaining('asks for its own password'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('server-profile-password')),
'wrong',
);
await tester.tap(find.byKey(const Key('server-profile-sign-in')));
await tester.pumpAndSettle();
expect(find.text('Wrong password.'), findsOneWidget);
expect(find.byKey(const Key('server-profile-password')), findsOneWidget);
await tester.enterText(
find.byKey(const Key('server-profile-password')),
'tank-secret',
);
await tester.tap(find.byKey(const Key('server-profile-sign-in')));
await tester.pumpAndSettle();
expect(auth.signIns, [(tank.id, 'wrong'), (tank.id, 'tank-secret')]);
// Back on the list: both machines connected, each on its own sign-in.
expect(find.byKey(const Key('server-profile-password')), findsNothing);
expect(find.text('Connected'), findsNWidgets(2));
expect(find.text('Address: ws://10.0.0.100:8082/connect'), findsOneWidget);
expect(connections.catalog.active?.id, 'mac');
});
}
testWidgets('an unreachable machine stays saved with the reason shown', (
tester,
) async {
final connections = ServerConnections(
store: MemoryServerCatalogStore(),
onSelected: (_) async {},
);
addTearDown(connections.dispose);
await connections.load();
final auth = FakeAuthenticator();
connections.authenticator = auth;
connections.addListener(() {
for (final server in connections.catalog.servers) {
auth.verdicts.putIfAbsent(
server.id,
() => const MachineAccessResult(
MachineAccess.unreachable,
detail: 'The HTTPS certificate of 100.85.25.33:8443 does not '
'cover an IP address.',
),
);
}
});
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: SavedServersSection(connections: connections),
),
),
),
);
await addServer(
tester,
name: 'Mac by IP',
address: 'wss://100.85.25.33:8443/connect',
);
expect(find.textContaining('could not be reached'), findsOneWidget);
expect(find.textContaining('does not cover an IP address'), findsOneWidget);
expect(find.byKey(const Key('server-profile-password')), findsNothing);
await tester.tap(find.byKey(const Key('server-sign-in-later')));
await tester.pumpAndSettle();
expect(connections.catalog.servers.single.name, 'Mac by IP');
expect(find.textContaining('Unreachable: The HTTPS certificate'), findsOneWidget);
});
testWidgets('a saved machine that wants a password offers Sign in', (
tester,
) async {
final tank = SavedServer.validated(
id: 'tank',
name: 'tank',
endpoints: ['ws://10.0.0.100:8082/connect'],
);
final connections = ServerConnections(
store: MemoryServerCatalogStore(
catalog: ServerCatalog(servers: [tank], selectedId: 'tank'),
),
onSelected: (_) async {},
);
addTearDown(connections.dispose);
await connections.load();
final auth = FakeAuthenticator()
..verdicts['tank'] = const MachineAccessResult(MachineAccess.needsPassword)
..passwords['tank'] = 'tank-secret';
connections.authenticator = auth;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(body: SavedServersSection(connections: connections)),
),
);
expect(find.text('Sign in required'), findsOneWidget);
await tester.tap(find.byKey(savedServerMenuKey('tank')));
await tester.pumpAndSettle();
await tester.tap(find.text('Sign in to tank'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('machine-password')), 'tank-secret');
await tester.tap(find.byKey(const Key('machine-sign-in')));
await tester.pumpAndSettle();
expect(auth.signIns, [('tank', 'tank-secret')]);
expect(find.text('Connected'), findsOneWidget);
expect(find.text('Sign in required'), findsNothing);
});
testWidgets('editing a name alone does not re-ask the password', (
tester,
) async {
final mac = SavedServer.validated(
id: 'mac',
name: 'Mac',
endpoints: ['ws://10.0.0.75:8083/connect'],
);
final auth = FakeAuthenticator()
..verdicts['mac'] = const MachineAccessResult(MachineAccess.needsPassword);
SavedServer? saved;
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => editSavedServer(
context,
server: mac,
authenticator: auth,
onSave: (value) async => saved = value,
),
child: const Text('Edit'),
),
),
),
),
);
await tester.tap(find.text('Edit'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('server-profile-name')), 'Studio');
await revealSave(tester);
await tester.tap(find.text('Save server'));
await tester.pumpAndSettle();
expect(saved?.name, 'Studio');
expect(auth.probes, isEmpty);
expect(find.text('Edit'), findsOneWidget);
});
}
@@ -11,6 +11,16 @@ import 'saved_server_menu.dart';
SavedServer profile(String id, List<String> urls) =>
SavedServer.validated(id: id, name: id, endpoints: urls);
/// The editor's list builds lazily; scroll its Save button into view.
Future<void> revealSave(WidgetTester tester) async {
await tester.scrollUntilVisible(
find.text('Save server'),
120,
scrollable: find.byType(Scrollable).last,
);
await tester.pumpAndSettle();
}
void main() {
test(
'browser Back aligns active identity with the actual page; failed switch restores selection',
@@ -129,8 +139,7 @@ void main() {
find.byKey(const Key('server-profile-addresses')),
'wss://tail.example/connect\nws://192.168.1.2:8083/connect',
);
await tester.ensureVisible(find.text('Save server'));
await tester.pumpAndSettle();
await revealSave(tester);
await tester.tap(find.text('Save server'));
await tester.pumpAndSettle();
expect(connections.catalog.active?.name, 'Home');
@@ -139,7 +148,7 @@ void main() {
'ws://192.168.1.2:8083/connect',
]);
expect(
find.text('Backup 1: ws://192.168.1.2:8083/connect'),
find.text('Backup address: ws://192.168.1.2:8083/connect'),
findsOneWidget,
);
await openSavedServerMenu(tester);
@@ -149,8 +158,7 @@ void main() {
find.byKey(const Key('server-profile-name')),
'My home',
);
await tester.ensureVisible(find.text('Save server'));
await tester.pumpAndSettle();
await revealSave(tester);
await tester.tap(find.text('Save server'));
await tester.pumpAndSettle();
expect(connections.catalog.active?.name, 'My home');
@@ -183,8 +191,7 @@ void main() {
find.byKey(const Key('server-profile-addresses')),
'not-a-url',
);
await tester.ensureVisible(find.text('Save server'));
await tester.pumpAndSettle();
await revealSave(tester);
await tester.tap(find.text('Save server'));
await tester.pumpAndSettle();
expect(find.byKey(const Key('server-profile-addresses')), findsOneWidget);
@@ -0,0 +1,77 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/servers/server_catalog.dart';
import 'package:pipelines_app/core/servers/server_catalog_store.dart';
import 'package:pipelines_app/features/settings/server_connections.dart';
SavedServer profile(String id) => SavedServer.validated(
id: id,
name: id,
endpoints: ['wss://$id.test/connect'],
);
void main() {
test('a native host hands the primary role to the next machine', () async {
final store = MemoryServerCatalogStore(
catalog: ServerCatalog(
servers: [profile('mac'), profile('tank')],
selectedId: 'mac',
),
);
final activated = <String?>[];
final connections = ServerConnections(
store: store,
onSelected: (server) async => activated.add(server?.id),
replaceRemovedPrimary: true,
);
addTearDown(connections.dispose);
await connections.load();
expect(await connections.remove('mac'), isTrue);
expect(connections.catalog.active?.id, 'tank');
expect(store.catalog?.selectedId, 'tank');
expect(activated, ['tank']);
// Removing the last machine activates "nothing" so the root can recover.
expect(await connections.remove('tank'), isTrue);
expect(connections.catalog.servers, isEmpty);
expect(activated, ['tank', null]);
});
test('removing a non-primary machine keeps the primary', () async {
final store = MemoryServerCatalogStore(
catalog: ServerCatalog(
servers: [profile('mac'), profile('tank')],
selectedId: 'mac',
),
);
final activated = <String?>[];
final connections = ServerConnections(
store: store,
onSelected: (server) async => activated.add(server?.id),
replaceRemovedPrimary: true,
);
addTearDown(connections.dispose);
await connections.load();
expect(await connections.remove('tank'), isTrue);
expect(connections.catalog.active?.id, 'mac');
expect(activated, isEmpty);
});
test('browsers never switch machines when the primary is removed', () async {
final store = MemoryServerCatalogStore(
catalog: ServerCatalog(
servers: [profile('mac'), profile('tank')],
selectedId: 'mac',
),
);
final activated = <String?>[];
final connections = ServerConnections(
store: store,
onSelected: (server) async => activated.add(server?.id),
);
addTearDown(connections.dispose);
await connections.load();
expect(await connections.remove('mac'), isTrue);
expect(connections.catalog.active, isNull);
expect(connections.catalog.servers.map((s) => s.id), ['tank']);
expect(activated, [null]);
});
}
@@ -188,7 +188,7 @@ void main() {
),
findsOneWidget,
);
expect(find.text('Preferred: wss://work.test/connect'), findsOneWidget);
expect(find.text('Address: wss://work.test/connect'), findsOneWidget);
expect(find.byKey(savedServerMenuKey('Home')), findsOneWidget);
expect(find.text('Add server'), findsOneWidget);
// Tapping another server's row uses it.