Ask for the password once and retry when a machine requires elevation

Carry the protocol error code, wrap each machine's gateway so an
elevation_required refusal shows one native password dialog, elevates that
connection and retries; send the upload token with file uploads; add a Settings
sign-in security section with the weak-password warning and sign out
everywhere; accept the __Host- session cookie.
This commit is contained in:
2026-11-10 01:21:28 +00:00
parent e43f9fa50c
commit 9702d68d2d
30 changed files with 1464 additions and 31 deletions
@@ -0,0 +1,221 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/elevation/elevating_gateway.dart';
import 'package:pipelines_app/core/servers/elevation/machine_elevation.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import '../../transport/pipelines_client_test.dart' show FakeChannel;
/// A machine that refuses gated requests until `elevate` gets [password].
class FakeMachine implements ApiGateway {
FakeMachine({this.password = 'right'});
final String password;
final calls = <String>[];
bool elevated = false;
int refuseAlways = 0;
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(type);
if (type == 'elevate') {
if (fields['password'] != password) {
throw const ProtocolError('Wrong password.', code: 'elevation_failed');
}
elevated = true;
return {
'type': 'elevated',
'elevation': {
'expires_at': '2026-11-10T12:15:00Z',
'seconds': 900,
'token': 'tok-1',
},
};
}
if (!elevated || refuseAlways > 0) {
if (refuseAlways > 0) refuseAlways--;
throw const ProtocolError(
'Confirm your password to continue.',
code: elevationRequiredCode,
);
}
return {'type': '${type}_ok'};
}
}
void main() {
test('a refusal prompts, elevates on the same machine and retries', () async {
final machine = FakeMachine();
var prompts = 0;
late MachineElevation elevation;
elevation = MachineElevation(
name: 'laptop',
gateway: machine,
prompt: (m) async {
prompts++;
expect(identical(m, elevation), isTrue);
return await m.submit('right') == null;
},
);
final gateway = ElevatingGateway(machine, elevation);
final reply = await gateway.call('chat_shell_run', {'command': 'ls'});
expect(reply['type'], 'chat_shell_run_ok');
expect(machine.calls, ['chat_shell_run', 'elevate', 'chat_shell_run']);
expect(prompts, 1);
expect(elevation.token, 'tok-1');
expect(elevationOf(gateway), same(elevation));
});
test('cancel rethrows the original refusal without retrying', () async {
final machine = FakeMachine();
final gateway = ElevatingGateway(
machine,
MachineElevation(
name: 'laptop',
gateway: machine,
prompt: (_) async => false,
),
);
await expectLater(
gateway.call('terminal_open'),
throwsA(
isA<ProtocolError>().having(
(e) => e.code,
'code',
'elevation_required',
),
),
);
expect(machine.calls, ['terminal_open']);
});
test('other errors pass through untouched and never prompt', () async {
var prompts = 0;
final failing = _Failing();
final gateway = ElevatingGateway(
failing,
MachineElevation(
name: 'x',
gateway: failing,
prompt: (_) async {
prompts++;
return true;
},
),
);
await expectLater(gateway.call('list_runs'), throwsA(isA<ProtocolError>()));
expect(prompts, 0);
});
test('concurrent refusals share one prompt', () async {
final machine = FakeMachine();
final release = Completer<void>();
var prompts = 0;
final elevation = MachineElevation(
name: 'laptop',
gateway: machine,
prompt: (m) async {
prompts++;
await release.future;
return await m.submit('right') == null;
},
);
final gateway = ElevatingGateway(machine, elevation);
final a = gateway.call('rename_path');
final b = gateway.call('delete_path');
await Future<void>.delayed(Duration.zero);
release.complete();
expect((await a)['type'], 'rename_path_ok');
expect((await b)['type'], 'delete_path_ok');
expect(prompts, 1);
});
test('a retried request that is refused again is reported', () async {
final machine = FakeMachine()..refuseAlways = 2;
final gateway = ElevatingGateway(
machine,
MachineElevation(
name: 'laptop',
gateway: machine,
prompt: (m) async => await m.submit('right') == null,
),
);
await expectLater(
gateway.call('chat_shell_input'),
throwsA(isA<ProtocolError>()),
);
expect(machine.calls, ['chat_shell_input', 'elevate', 'chat_shell_input']);
});
test('submit reports a wrong password and keeps no token', () async {
final machine = FakeMachine();
final elevation = MachineElevation(name: 'm', gateway: machine);
expect(await elevation.submit('wrong'), 'Wrong password.');
expect(elevation.token, isNull);
expect(await elevation.submit('right'), isNull);
expect(elevation.token, 'tok-1');
});
test('the token expires with the window and on disconnect', () async {
final machine = FakeMachine();
var now = DateTime(2026, 11, 10, 12);
final states = StreamController<ConnectionState>.broadcast();
final elevation = MachineElevation(
name: 'm',
gateway: machine,
states: states.stream,
clock: () => now,
);
await elevation.submit('right');
now = now.add(const Duration(minutes: 14));
expect(elevation.token, 'tok-1');
now = now.add(const Duration(minutes: 2));
expect(elevation.token, isNull);
now = now.subtract(const Duration(minutes: 16));
await elevation.submit('right');
states.add(const ConnectionState(ConnectionKind.disconnected));
await Future<void>.delayed(Duration.zero);
expect(elevation.token, isNull);
await elevation.dispose();
await states.close();
});
test('the client carries the server error code', () async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
await client.connect(Uri.parse('ws://example.test'));
final call = client.call('terminal_open');
await Future<void>.delayed(Duration.zero);
final id = (jsonDecode(channel.outgoing.single as String) as Map)['id'];
channel.incoming.add(
jsonEncode({
'id': id,
'type': 'error',
'code': 'elevation_required',
'error': 'Confirm your password.',
}),
);
await expectLater(
call,
throwsA(
isA<ProtocolError>()
.having((e) => e.code, 'code', 'elevation_required')
.having((e) => e.message, 'message', 'Confirm your password.'),
),
);
await client.dispose();
});
}
class _Failing implements ApiGateway {
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async =>
throw const ProtocolError('nope');
}
@@ -0,0 +1,131 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/elevation/elevating_gateway.dart';
import 'package:pipelines_app/core/servers/elevation/elevation_dialog.dart';
import 'package:pipelines_app/core/servers/elevation/machine_elevation.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'elevating_gateway_test.dart' show FakeMachine;
void main() {
late FakeMachine machine;
late ElevatingGateway gateway;
final navigator = GlobalKey<NavigatorState>();
Future<JsonMap>? pending;
Future<void> pump(WidgetTester tester, {bool cupertino = false}) async {
machine = FakeMachine();
gateway = ElevatingGateway(
machine,
MachineElevation(
name: 'laptop',
gateway: machine,
prompt: elevationDialogPrompt(() => navigator.currentContext),
),
);
pending = null;
final home = Builder(
builder: (context) => Center(
child: TextButton(
onPressed: () => pending = gateway.call('chat_shell_run'),
child: const Text('Run'),
),
),
);
await tester.pumpWidget(
cupertino
? CupertinoApp(navigatorKey: navigator, home: home)
: MaterialApp(
navigatorKey: navigator,
home: Scaffold(body: home),
),
);
await tester.tap(find.text('Run'));
await tester.pumpAndSettle();
}
testWidgets('a refused command asks once, then retries', (tester) async {
await pump(tester);
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.textContaining('laptop'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('elevation-password')),
'right',
);
await tester.tap(find.byKey(const Key('elevation-confirm')));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect((await pending!)['type'], 'chat_shell_run_ok');
expect(machine.calls, ['chat_shell_run', 'elevate', 'chat_shell_run']);
});
testWidgets('a wrong password keeps the dialog open with the error', (
tester,
) async {
await pump(tester);
await tester.enterText(find.byKey(const Key('elevation-password')), 'nope');
await tester.tap(find.byKey(const Key('elevation-confirm')));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text('Wrong password.'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('elevation-password')),
'right',
);
await tester.tap(find.byKey(const Key('elevation-confirm')));
await tester.pumpAndSettle();
expect((await pending!)['type'], 'chat_shell_run_ok');
});
testWidgets('cancel reports the refusal and sends nothing more', (
tester,
) async {
await pump(tester);
final result = expectLater(
pending!,
throwsA(
isA<ProtocolError>().having(
(e) => e.code,
'code',
'elevation_required',
),
),
);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
await result;
expect(machine.calls, ['chat_shell_run']);
});
testWidgets('a Cupertino host gets the Cupertino dialog', (tester) async {
await pump(tester, cupertino: true);
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
await tester.enterText(
find.byKey(const Key('elevation-password')),
'right',
);
await tester.tap(find.byKey(const Key('elevation-confirm')));
await tester.pumpAndSettle();
expect((await pending!)['type'], 'chat_shell_run_ok');
});
testWidgets('without a mounted navigator the refusal is reported', (
tester,
) async {
final machine = FakeMachine();
final gateway = ElevatingGateway(
machine,
MachineElevation(
name: 'laptop',
gateway: machine,
prompt: elevationDialogPrompt(() => null),
),
);
await expectLater(
gateway.call('terminal_open'),
throwsA(isA<ProtocolError>()),
);
});
}
@@ -0,0 +1,39 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/session/server_session_io.dart';
void main() {
late HttpServer server;
late String setCookie;
setUp(() async {
server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen((request) async {
await request.drain<void>();
request.response
..statusCode = 303
..headers.set('Location', '/')
..headers.add('Set-Cookie', setCookie);
await request.response.close();
});
});
tearDown(() => server.close(force: true));
Uri login() => Uri.parse('http://127.0.0.1:${server.port}/login');
for (final name in ['pipelines_session', '__Host-pipelines_session']) {
test('keeps the $name session cookie', () async {
setCookie = '$name=signed.token; Path=/; HttpOnly; SameSite=Lax';
final result = await postLogin(login(), 'password');
expect(result.error, isNull);
expect(result.cookie, '$name=signed.token');
});
}
test('ignores an unrelated cookie', () async {
setCookie = 'other=value; Path=/';
final result = await postLogin(login(), 'password');
expect(result.cookie, isNull);
});
}
@@ -56,7 +56,13 @@ void main() {
reply = (status: 200, body: '{"path":"/home/demo/new.txt"}');
gate = null;
postFileUpload =
(uri, {required name, required mime, required bytes}) async {
(
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) async {
posted.add((uri: uri, name: name, mime: mime, size: bytes.length));
if (gate != null) await gate!.future;
return reply;
@@ -187,7 +193,13 @@ void main() {
) async {
var calls = 0;
postFileUpload =
(uri, {required name, required mime, required bytes}) async {
(
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) async {
calls += 1;
return name == 'kept.txt'
? (status: 409, body: 'exists')
@@ -0,0 +1,123 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/servers/elevation/machine_elevation.dart';
import 'package:pipelines_app/features/chat/domain/chat_attachment_picker.dart';
import 'package:pipelines_app/features/chat/files/files_upload.dart';
import '../../../core/servers/elevation/elevating_gateway_test.dart'
show FakeMachine;
void main() {
late FilesUploadPost original;
setUp(() => original = postFileUpload);
tearDown(() => postFileUpload = original);
final file = ChatPickedFile(
name: 'notes.txt',
mime: 'text/plain',
bytes: Uint8List.fromList([1, 2, 3]),
);
const refusal = (
status: 403,
body: '{"code":"elevation_required","error":"Confirm your password."}',
);
const stored = (status: 200, body: '{"path":"/home/demo/notes.txt"}');
test(
'a refused upload elevates its machine and retries with the token',
() async {
final machine = FakeMachine();
var prompts = 0;
final elevation = MachineElevation(
name: 'laptop',
gateway: machine,
prompt: (m) async {
prompts++;
return await m.submit('right') == null;
},
);
final sent = <Map<String, String>>[];
postFileUpload =
(
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) async {
sent.add(headers);
return headers['X-Pipelines-Elevation'] == 'tok-1'
? stored
: refusal;
};
final path = await uploadFileInto(
'ws://example.test/connect',
'/home/demo',
file,
elevation: elevation,
);
expect(path, '/home/demo/notes.txt');
expect(prompts, 1);
expect(sent, [
<String, String>{},
{'X-Pipelines-Elevation': 'tok-1'},
]);
// A live elevation rides on the next upload without asking again.
await uploadFileInto(
'ws://example.test/connect',
'/home/demo',
file,
elevation: elevation,
);
expect(prompts, 1);
expect(sent.last, {'X-Pipelines-Elevation': 'tok-1'});
},
);
test('a cancelled confirmation reports the refusal', () async {
final machine = FakeMachine();
final elevation = MachineElevation(
name: 'laptop',
gateway: machine,
prompt: (_) async => false,
);
var posts = 0;
postFileUpload =
(
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) async {
posts++;
return refusal;
};
await expectLater(
uploadFileInto(
'ws://example.test/connect',
'/home/demo',
file,
elevation: elevation,
),
throwsA(
isA<FilesUploadException>().having(
(e) => e.message,
'message',
contains('confirm the password'),
),
),
);
expect(posts, 1);
});
test('refusal detection needs the typed code', () {
expect(refusedForElevation(refusal), isTrue);
expect(
refusedForElevation((status: 403, body: 'folder access denied')),
isFalse,
);
expect(refusedForElevation((status: 200, body: refusal.body)), isFalse);
});
}
@@ -22,7 +22,13 @@ void main() {
String? postedName;
String? postedMime;
postFileUpload =
(uri, {required name, required mime, required bytes}) async {
(
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) async {
posted = uri;
postedName = name;
postedMime = mime;
@@ -49,7 +55,13 @@ void main() {
test('a relay endpoint posts through its peer prefix', () async {
Uri? posted;
postFileUpload =
(uri, {required name, required mime, required bytes}) async {
(
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) async {
posted = uri;
return (status: 200, body: '{"path":"/home/x/notes.txt"}');
};
@@ -64,8 +76,13 @@ void main() {
test('server refusals become plain messages', () async {
Future<String> message(int status, String body) async {
postFileUpload =
(uri, {required name, required mime, required bytes}) async =>
(status: status, body: body);
(
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) async => (status: status, body: body);
try {
await uploadFileInto('ws://example.test/connect', '/home/demo', file);
} on FilesUploadException catch (error) {
@@ -103,8 +120,14 @@ void main() {
test(
'transport failures and blank names are reported, not swallowed',
() async {
postFileUpload = (uri, {required name, required mime, required bytes}) =>
throw StateError('socket closed');
postFileUpload =
(
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) => throw StateError('socket closed');
await expectLater(
uploadFileInto('ws://example.test/connect', '/home/demo', file),
throwsA(
@@ -0,0 +1,113 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/session/server_session.dart';
import 'package:pipelines_app/features/settings/security/session_security_api.dart';
import 'package:pipelines_app/features/settings/security/settings_security_section.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
late SecurityRequest originalSend;
late void Function() originalOpen;
final requests = <String>[];
var weak = true;
setUp(() async {
originalSend = sendSecurityRequest;
originalOpen = openWebSignIn;
requests.clear();
weak = true;
SharedPreferences.setMockInitialValues({});
await ServerSession.load();
sendSecurityRequest = (method, uri) async {
requests.add('$method $uri');
if (uri.path == '/api/session') {
return (
status: 200,
body:
'{"weak_password":$weak,"password_rule":"Use 16 or more characters."}',
);
}
return (status: 200, body: '{"revoked":true}');
};
});
tearDown(() {
sendSecurityRequest = originalSend;
openWebSignIn = originalOpen;
});
Future<void> pump(
WidgetTester tester, {
bool web = false,
VoidCallback? onSignedOut,
}) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SettingsSecuritySection(
endpoint: 'wss://box.ts.net:8443/connect',
onSignedOut: onSignedOut ?? () {},
web: web,
),
),
),
);
await tester.pumpAndSettle();
}
testWidgets('warns about a weak password with the rule', (tester) async {
await pump(tester);
expect(requests, ['GET https://box.ts.net:8443/api/session']);
final warning = find.byKey(const Key('settings-weak-password'));
expect(warning, findsOneWidget);
expect(
tester.widget<Text>(warning).data,
contains('Use 16 or more characters. Run ./password on the server'),
);
});
testWidgets('a strong password shows no warning', (tester) async {
weak = false;
await pump(tester);
expect(find.byKey(const Key('settings-weak-password')), findsNothing);
});
testWidgets('sign out everywhere confirms, revokes and signs out', (
tester,
) async {
var signedOut = 0;
await pump(tester, onSignedOut: () => signedOut++);
await tester.tap(find.byKey(const Key('settings-revoke-all')));
await tester.pumpAndSettle();
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(requests, hasLength(1));
await tester.tap(find.byKey(const Key('settings-revoke-all')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('settings-revoke-all-confirm')));
await tester.pumpAndSettle();
expect(
requests.last,
'POST https://box.ts.net:8443/api/sessions/revoke-all',
);
expect(signedOut, 1);
expect(ServerSession.cookie, isNull);
expect(find.textContaining('Signed out everywhere'), findsOneWidget);
});
testWidgets('the web app leaves for the sign-in page', (tester) async {
var opened = 0;
openWebSignIn = () => opened++;
await pump(tester, web: true);
await tester.tap(find.byKey(const Key('settings-revoke-all')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('settings-revoke-all-confirm')));
await tester.pumpAndSettle();
expect(opened, 1);
});
testWidgets('a signed-out device says so', (tester) async {
sendSecurityRequest = (method, uri) async => (status: 401, body: '');
await pump(tester);
expect(find.textContaining('Sign in to see'), findsOneWidget);
});
}