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
+14 -1
View File
@@ -3,6 +3,8 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../core/api_gateway.dart';
import '../core/servers/elevation/elevating_gateway.dart';
import '../core/servers/elevation/machine_elevation.dart';
import '../core/transport/pipelines_client.dart';
/// Whether this connection's send-only `subscribe` was accepted.
@@ -32,8 +34,17 @@ class AppSession extends ChangeNotifier {
_everConnected = knownServer {
_states = _client.states.listen(_onState);
_frames = _client.frames.listen(_onFrame);
_elevation = MachineElevation(
name: endpoint?.host.isNotEmpty == true ? endpoint!.host : 'this server',
gateway: _client,
states: _client.states,
);
_gateway = ElevatingGateway(_client, _elevation);
}
late final MachineElevation _elevation;
late final ElevatingGateway _gateway;
final Uri? _initialEndpoint;
final List<Uri>? _initialAddresses;
final PipelinesClient _client;
@@ -47,7 +58,8 @@ class AppSession extends ChangeNotifier {
String _subscriptionError = '';
String? _subscribeRequest;
ApiGateway get gateway => _client;
/// Feature requests; a step-up refusal asks for the password and retries.
ApiGateway get gateway => _gateway;
/// Settings controls the same transport; it must never create another socket.
PipelinesClient get client => _client;
@@ -180,6 +192,7 @@ class AppSession extends ChangeNotifier {
_disposed = true;
_sendUnsubscribe();
unawaited(_states.cancel());
unawaited(_elevation.dispose());
unawaited(_frames.cancel());
unawaited(_client.dispose());
super.dispose();
+10
View File
@@ -1,5 +1,7 @@
import '../core/servers/chat/chat_server_pool.dart';
import '../core/servers/server_context.dart';
import '../core/servers/elevation/elevation_dialog.dart';
import '../core/servers/elevation/machine_elevation.dart';
import '../ui/adaptive/platform.dart';
import 'dart:async';
@@ -125,6 +127,9 @@ class _PipelinesAppState extends State<PipelinesApp>
with WidgetsBindingObserver {
late final AppSession _session;
late final AppRouterDelegate _delegate;
late final ElevationPrompt _elevationPrompt = elevationDialogPrompt(
() => _delegate.navigatorContext,
);
late final RouteInformationProvider _provider;
late final bool _ownsProvider;
late final RouterConfig<AppRoute> _config;
@@ -221,6 +226,7 @@ class _PipelinesAppState extends State<PipelinesApp>
serverId: widget.serverId,
);
bindServerIdentity(_session.gateway, widget.serverId);
bindServerIdentity(_session.client, widget.serverId);
_terminals = AppTerminals(
pool: widget.chatPool,
connection: _session,
@@ -294,6 +300,7 @@ class _PipelinesAppState extends State<PipelinesApp>
_session.addListener(_attentionSessionChanged);
_session.addListener(_updateEndpointChanged);
_attention.addListener(_attentionChanged);
MachineElevation.defaultPrompt = _elevationPrompt;
_delegate = AppRouterDelegate(
initial: initial,
cupertino: _cupertino,
@@ -436,6 +443,9 @@ class _PipelinesAppState extends State<PipelinesApp>
_notifications.dispose();
_deliveryController.dispose();
_chatQuestionNotices?.dispose();
if (identical(MachineElevation.defaultPrompt, _elevationPrompt)) {
MachineElevation.defaultPrompt = null;
}
_delegate.removeListener(_routeChanged);
_delegate.dispose();
if (_ownsProvider) {
@@ -4,6 +4,8 @@ import '../../session/server_session.dart';
import '../../transport/channel_connect.dart';
import '../../transport/pipelines_client.dart';
import '../server_catalog.dart';
import '../elevation/elevating_gateway.dart';
import '../elevation/machine_elevation.dart';
import 'browser_peer.dart';
/// The machine answered and wants its own password; it is not unreachable.
@@ -55,7 +57,9 @@ Future<ChatMachineConnection> connectChatMachine(
final result = await registerBrowserPeer(server);
if (!result.connected) {
if (result.needsPassword) {
throw MachineSignInRequired(result.error ?? 'Sign in to this machine.');
throw MachineSignInRequired(
result.error ?? 'Sign in to this machine.',
);
}
throw StateError(result.error ?? 'Could not connect to this machine.');
}
@@ -75,13 +79,22 @@ Future<ChatMachineConnection> connectChatMachine(
: (uri) => connectScopedPipelinesChannel(uri, headers!),
);
await client.connectAny(endpoints);
return ChatMachineConnection(
// Each machine confirms its own password through its own connection.
final elevation = MachineElevation(
name: server.name,
gateway: client,
states: client.states,
);
return ChatMachineConnection(
gateway: ElevatingGateway(client, elevation),
headers: headers,
endpoint: () => client.endpoint?.toString() ?? '',
connected: () => client.state.kind == ConnectionKind.connected,
states: client.states,
close: client.dispose,
close: () async {
await elevation.dispose();
await client.dispose();
},
retry: () => client.connectAny(endpoints),
);
}
@@ -3,6 +3,7 @@ import '../../api_gateway.dart';
import '../../transport/pipelines_client.dart';
import '../server_catalog.dart';
import '../server_scope.dart';
import '../elevation/elevating_gateway.dart';
import 'chat_identity.dart';
/// Machine-bound chat protocol adapter. Tool inputs, user answers, message IDs
@@ -10,6 +11,7 @@ import 'chat_identity.dart';
class ChatServerGateway implements ApiGateway, EndpointGateway {
ChatServerGateway(this.server, this.gateway, {this.isCurrent}) {
bindServerIdentity(this, server.id);
bindElevation(this, elevationOf(gateway));
}
SavedServer server;
final ApiGateway gateway;
@@ -0,0 +1,45 @@
import '../../api_gateway.dart';
import '../../transport/pipelines_client.dart';
import 'machine_elevation.dart';
final _elevations = Expando<MachineElevation>('machine elevation');
/// Records that requests through [gateway] elevate with [elevation].
void bindElevation(ApiGateway gateway, MachineElevation? elevation) {
_elevations[gateway] = elevation;
}
/// The elevation of the machine behind [gateway], when it has one.
MachineElevation? elevationOf(ApiGateway gateway) => _elevations[gateway];
/// A machine gateway that answers the server's `elevation_required` refusal
/// by asking for the password once and retrying the request.
///
/// A cancelled prompt rethrows the original refusal; a retried request is
/// never retried again, so a server that keeps refusing reports it.
class ElevatingGateway implements ApiGateway, EndpointGateway {
ElevatingGateway(this.inner, this.elevation) {
bindElevation(this, elevation);
}
final ApiGateway inner;
final MachineElevation elevation;
@override
String get configuredEndpoint => configuredGatewayEndpoint(inner);
@override
Stream<JsonMap> get frames => inner.frames;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
try {
return await inner.call(type, fields);
} catch (error) {
if (type == 'elevate' || !isElevationRequired(error)) rethrow;
elevation.clear();
if (!await elevation.ensure()) rethrow;
return inner.call(type, fields);
}
}
}
@@ -0,0 +1,147 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import 'machine_elevation.dart';
/// The app's elevation prompt: the native password dialog over whatever
/// navigator [context] returns, or a refusal when none is mounted.
ElevationPrompt elevationDialogPrompt(BuildContext? Function() context) =>
(machine) async {
final host = context();
if (host == null || !host.mounted) return false;
return showElevationDialog(host, machine);
};
/// Asks for [machine]'s password before a privileged action. Resolves true
/// once the server confirmed it; the dialog stays open after a wrong
/// password so the operator can retry.
Future<bool> showElevationDialog(
BuildContext context,
MachineElevation machine,
) async {
final dialog = ElevationDialog(name: machine.name, submit: machine.submit);
final result = usesCupertinoHost(context)
? await showCupertinoDialog<bool>(
context: context,
builder: (_) => dialog,
)
: await showDialog<bool>(context: context, builder: (_) => dialog);
return result ?? false;
}
class ElevationDialog extends StatefulWidget {
const ElevationDialog({super.key, required this.name, required this.submit});
final String name;
/// Returns null when the password was accepted, else the sentence to show.
final Future<String?> Function(String password) submit;
@override
State<ElevationDialog> createState() => _ElevationDialogState();
}
class _ElevationDialogState extends State<ElevationDialog> {
final password = TextEditingController();
bool busy = false;
String? error;
@override
void dispose() {
password.dispose();
super.dispose();
}
Future<void> confirm() async {
if (password.text.isEmpty || busy) return;
setState(() {
busy = true;
error = null;
});
final problem = await widget.submit(password.text);
if (!mounted) return;
if (problem == null) {
Navigator.pop(context, true);
return;
}
password.clear();
setState(() {
busy = false;
error = problem;
});
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final field = cupertino
? CupertinoTextField(
key: const Key('elevation-password'),
controller: password,
obscureText: true,
autofocus: true,
placeholder: 'Password',
onSubmitted: busy ? null : (_) => confirm(),
)
: TextField(
key: const Key('elevation-password'),
controller: password,
obscureText: true,
autofocus: true,
decoration: const InputDecoration(labelText: 'Password'),
onSubmitted: busy ? null : (_) => confirm(),
);
final content = Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'Running commands, opening a terminal and changing files on '
'${widget.name} need its password again. This connection stays '
'confirmed for 15 minutes.',
),
const SizedBox(height: 12),
field,
if (error != null) ...[
const SizedBox(height: 8),
Text(error!, key: const Key('elevation-error')),
],
],
);
const title = Text('Confirm password');
final confirmLabel = Text(busy ? 'Confirming…' : 'Confirm');
return cupertino
? CupertinoAlertDialog(
title: title,
content: content,
actions: [
CupertinoDialogAction(
onPressed: busy ? null : () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
CupertinoDialogAction(
key: const Key('elevation-confirm'),
isDefaultAction: true,
onPressed: busy ? null : confirm,
child: confirmLabel,
),
],
)
: AlertDialog(
title: title,
content: content,
actions: [
TextButton(
onPressed: busy ? null : () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
FilledButton(
key: const Key('elevation-confirm'),
onPressed: busy ? null : confirm,
child: confirmLabel,
),
],
);
}
}
@@ -0,0 +1,114 @@
import 'dart:async';
import '../../api_gateway.dart';
import '../../error_reason.dart';
import '../../transport/connection_state.dart';
/// The server refused a request until this connection re-confirms the
/// password (step-up re-authentication).
const elevationRequiredCode = 'elevation_required';
/// Asks the operator to confirm [machine]'s password. Resolves true once
/// [MachineElevation.submit] succeeded, false when the operator cancelled or
/// no dialog can be shown.
typedef ElevationPrompt = Future<bool> Function(MachineElevation machine);
/// Whether [error] is the server's step-up refusal.
bool isElevationRequired(Object error) =>
error is ProtocolError && error.code == elevationRequiredCode;
/// One machine connection's step-up state.
///
/// Elevation belongs to the websocket connection that confirmed the
/// password: it survives navigation, ends when the server's window expires
/// and is forgotten when the connection drops (the server forgets it too).
/// Each machine elevates separately through its own gateway.
class MachineElevation {
MachineElevation({
required this.name,
required this.gateway,
Stream<ConnectionState>? states,
this.prompt,
DateTime Function()? clock,
}) : _clock = clock ?? DateTime.now {
_states = states?.listen((state) {
if (state.kind != ConnectionKind.connected) clear();
});
}
/// The prompt every elevation uses when none is given; the app installs
/// its native password dialog here.
static ElevationPrompt? defaultPrompt;
/// The machine's name as the dialog shows it.
final String name;
/// The raw gateway of this machine's connection (never the elevating one).
final ApiGateway gateway;
final ElevationPrompt? prompt;
final DateTime Function() _clock;
StreamSubscription<ConnectionState>? _states;
String? _token;
DateTime? _expires;
Future<bool>? _pending;
/// The upload token of a live elevation, else null.
String? get token {
final expires = _expires;
final token = _token;
if (token == null || token.isEmpty || expires == null) return null;
return _clock().isBefore(expires) ? token : null;
}
/// Whether the last confirmation is still inside its window.
bool get elevated {
final expires = _expires;
return expires != null && _clock().isBefore(expires);
}
/// Asks for the password once, shared by every concurrent refusal.
Future<bool> ensure() {
final ask = prompt ?? defaultPrompt;
if (ask == null) return Future.value(false);
return _pending ??= ask(
this,
).catchError((Object _) => false).whenComplete(() => _pending = null);
}
/// Sends `elevate`; null on success, otherwise the sentence to show.
Future<String?> submit(String password) async {
try {
final reply = await gateway.call('elevate', {'password': password});
final body = reply['elevation'];
if (reply['type'] != 'elevated' || body is! Map) {
return 'The server did not confirm the password.';
}
// The server's window, measured on this device's clock so a skewed
// clock cannot keep a stale token alive.
final seconds = body['seconds'];
final expiresAt = DateTime.tryParse('${body['expires_at'] ?? ''}');
_expires = seconds is num
? _clock().add(Duration(seconds: seconds.toInt()))
: expiresAt?.toLocal() ?? _clock().add(const Duration(minutes: 15));
final token = body['token'];
_token = token is String ? token : null;
return null;
} catch (error) {
return describeErrorReason(
error,
fallback: 'Could not confirm the password.',
);
}
}
/// Forgets the elevation (the connection dropped or the server refused).
void clear() {
_token = null;
_expires = null;
}
Future<void> dispose() async {
await _states?.cancel();
_states = null;
}
}
+12 -3
View File
@@ -3,6 +3,10 @@ import 'dart:io';
import 'login_probe.dart';
/// The web login's session cookie: `__Host-` prefixed over https, plain over
/// http.
const sessionCookieNames = {'pipelines_session', '__Host-pipelines_session'};
/// Posts the password to the web login and returns its session cookie.
Future<({String? cookie, String? error})> postLogin(
Uri login,
@@ -23,7 +27,7 @@ Future<({String? cookie, String? error})> postLogin(
final response = await request.close();
await response.drain<void>();
for (final cookie in response.cookies) {
if (cookie.name == 'pipelines_session' && cookie.value.isNotEmpty) {
if (sessionCookieNames.contains(cookie.name) && cookie.value.isNotEmpty) {
return (cookie: '${cookie.name}=${cookie.value}', error: null);
}
}
@@ -61,7 +65,10 @@ Future<LoginProbe> probeLogin(Uri login, Map<String, String> headers) async {
return LoginProbe(status: response.statusCode);
}
final body = await _head(response, 65536);
return LoginProbe(status: 200, loginPage: LoginProbe.isPipelinesLogin(body));
return LoginProbe(
status: 200,
loginPage: LoginProbe.isPipelinesLogin(body),
);
} on Exception catch (error) {
return LoginProbe(failure: describeFailure(login, error));
} finally {
@@ -71,7 +78,9 @@ Future<LoginProbe> probeLogin(Uri login, Map<String, String> headers) async {
Future<String> _head(HttpClientResponse response, int limit) async {
final buffer = StringBuffer();
await for (final chunk in response.transform(const SystemEncoding().decoder)) {
await for (final chunk in response.transform(
const SystemEncoding().decoder,
)) {
buffer.write(chunk);
if (buffer.length > limit) break;
}
+4 -1
View File
@@ -14,8 +14,11 @@ class ConnectionState {
}
class ProtocolError implements Exception {
const ProtocolError(this.message);
const ProtocolError(this.message, {this.code = ''});
final String message;
/// The server's machine-readable refusal (`elevation_required`), or blank.
final String code;
@override
String toString() => message;
}
+4 -1
View File
@@ -209,7 +209,10 @@ class PipelinesClient implements ApiGateway {
if (message['type'] == 'error') {
final reason = '${message['error'] ?? ''}'.trim();
pending.completeError(
ProtocolError(reason.isEmpty ? 'server error' : reason),
ProtocolError(
reason.isEmpty ? 'server error' : reason,
code: '${message['code'] ?? ''}',
),
);
} else {
pending.complete(message);
@@ -21,7 +21,14 @@ Future<ChatUploadReply> postChatUpload(
required String name,
required String mime,
required Uint8List bytes,
}) => platform.postChatUpload(uri, name: name, mime: mime, bytes: bytes);
Map<String, String> headers = const {},
}) => platform.postChatUpload(
uri,
name: name,
mime: mime,
bytes: bytes,
headers: headers,
);
/// The header that carries the file name; the server refuses a post without it.
const chatUploadNameHeader = 'X-Pipelines-Upload-Name';
@@ -10,6 +10,7 @@ Future<ChatUploadReply> postChatUpload(
required String name,
required String mime,
required Uint8List bytes,
Map<String, String> headers = const {},
}) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
try {
@@ -21,6 +22,7 @@ Future<ChatUploadReply> postChatUpload(
..set(chatUploadNameHeader, Uri.encodeComponent(name))
..set(HttpHeaders.contentTypeHeader, mime)
..contentLength = bytes.length;
headers.forEach(request.headers.set);
request.add(bytes);
final response = await request.close();
final body = await response.transform(utf8.decoder).join();
@@ -7,4 +7,5 @@ Future<ChatUploadReply> postChatUpload(
required String name,
required String mime,
required Uint8List bytes,
Map<String, String> headers = const {},
}) => throw UnsupportedError('Uploads are not supported on this platform.');
@@ -28,6 +28,7 @@ Future<ChatUploadReply> postChatUpload(
required String name,
required String mime,
required Uint8List bytes,
Map<String, String> headers = const {},
}) async {
final response = await _fetch(
uri.toString().toJS,
@@ -36,6 +37,7 @@ Future<ChatUploadReply> postChatUpload(
headers: {
chatUploadNameHeader: Uri.encodeComponent(name),
'Content-Type': mime,
...headers,
}.jsify()!,
body: bytes.toJS,
credentials: 'same-origin'.toJS,
@@ -1,5 +1,6 @@
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../../../core/servers/elevation/elevating_gateway.dart';
import '../../../core/transport/pipelines_client.dart';
import '../data/directory_listing.dart';
import '../domain/chat_attachment_picker.dart';
@@ -113,7 +114,12 @@ class FilesController extends ChangeNotifier {
final failures = <String>[];
for (final file in files) {
try {
await uploadFileInto(endpoint, directory, file);
await uploadFileInto(
endpoint,
directory,
file,
elevation: elevationOf(gateway),
);
} on FilesUploadException catch (error) {
failures.add(error.message);
} finally {
+46 -12
View File
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'dart:typed_data';
import '../../../core/servers/elevation/machine_elevation.dart';
import '../../../core/transport/server_url.dart';
import '../data/upload/chat_upload.dart';
import '../domain/chat_attachment_picker.dart';
@@ -12,6 +13,7 @@ typedef FilesUploadPost =
required String name,
required String mime,
required Uint8List bytes,
Map<String, String> headers,
});
/// The transport the Files panel uploads with.
@@ -33,11 +35,16 @@ class FilesUploadException implements Exception {
/// the stored path the server reports. Every failure is a
/// [FilesUploadException]; nothing is retried or renamed on the caller's
/// behalf, so an existing file is reported rather than replaced.
///
/// [elevation] is the machine's step-up state: its token rides on the
/// request as [elevationHeader], and a 403 `elevation_required` refusal asks
/// for the password once and retries.
Future<String> uploadFileInto(
String endpoint,
String directory,
ChatPickedFile file,
) async {
ChatPickedFile file, {
MachineElevation? elevation,
}) async {
final name = file.name.trim();
if (name.isEmpty) {
throw const FilesUploadException(
@@ -56,16 +63,25 @@ Future<String> uploadFileInto(
'No server is configured to upload files to.',
);
}
final ChatUploadReply reply;
try {
reply = await postFileUpload(
uri,
name: name,
mime: file.mime.trim().isEmpty ? 'application/octet-stream' : file.mime,
bytes: file.bytes,
);
} catch (error) {
throw FilesUploadException('"$name" could not be uploaded: $error');
Future<ChatUploadReply> post() async {
final token = elevation?.token;
try {
return await postFileUpload(
uri,
name: name,
mime: file.mime.trim().isEmpty ? 'application/octet-stream' : file.mime,
bytes: file.bytes,
headers: {elevationHeader: ?token},
);
} catch (error) {
throw FilesUploadException('"$name" could not be uploaded: $error');
}
}
var reply = await post();
if (elevation != null && refusedForElevation(reply)) {
elevation.clear();
if (await elevation.ensure()) reply = await post();
}
final reason = reply.body.trim();
switch (reply.status) {
@@ -75,6 +91,10 @@ Future<String> uploadFileInto(
throw const FilesUploadException(
'Sign in to upload files (Settings → Sign in).',
);
case 403 when refusedForElevation(reply):
throw FilesUploadException(
'"$name" was not uploaded: confirm the password to change files.',
);
case 409:
throw FilesUploadException('"$name" already exists in this folder.');
case 413:
@@ -97,3 +117,17 @@ Future<String> uploadFileInto(
}
throw FilesUploadException('"$name" upload returned no stored path.');
}
/// The request header carrying a confirmed connection's elevation token.
const elevationHeader = 'X-Pipelines-Elevation';
/// Whether [reply] is the server's 403 step-up refusal.
bool refusedForElevation(ChatUploadReply reply) {
if (reply.status != 403) return false;
try {
final decoded = jsonDecode(reply.body);
return decoded is Map && decoded['code'] == elevationRequiredCode;
} on FormatException {
return false;
}
}
@@ -0,0 +1,114 @@
import 'dart:convert';
import '../../../core/session/session_probe.dart';
import 'session_security_http_stub.dart'
if (dart.library.io) 'session_security_http_io.dart'
if (dart.library.js_interop) 'session_security_http_web.dart'
as platform;
/// One answer from the web proxy's session endpoints.
typedef SecurityReply = ({int status, String body});
/// Sends one request to the web proxy with this device's session: the kept
/// cookie on native, the browser's same-origin cookie on the web.
typedef SecurityRequest =
Future<SecurityReply> Function(String method, Uri uri);
/// The transport the section uses; widget tests swap in a recorder.
SecurityRequest sendSecurityRequest = platform.sendSecurityRequest;
/// Leaves the web app for the sign-in page after every session was revoked.
/// A no-op on native, where the app forgets its kept cookie instead.
void Function() openWebSignIn = platform.openWebSignIn;
/// What the proxy reports about the sign-in itself.
class SessionSecurity {
const SessionSecurity({required this.weakPassword, required this.rule});
/// The current password predates the strength rule.
final bool weakPassword;
/// The rule for new passwords, in the proxy's words.
final String rule;
}
/// Why the session endpoints could not be used, in words Settings shows.
class SessionSecurityException implements Exception {
const SessionSecurityException(this.message);
final String message;
@override
String toString() => message;
}
/// The proxy path [path] beside the websocket [endpoint].
Uri? securityUri(String endpoint, String path) {
final parsed = Uri.tryParse(endpoint.trim());
if (parsed == null) return null;
return loginUriFor(parsed)?.replace(path: path);
}
/// Reads GET /api/session.
Future<SessionSecurity> loadSessionSecurity(String endpoint) async {
final uri = securityUri(endpoint, '/api/session');
if (uri == null) {
throw const SessionSecurityException('Set the server address first.');
}
final reply = await _send('GET', uri);
if (reply.status == 401) {
throw const SessionSecurityException(
'Sign in to see this server\'s sign-in security.',
);
}
if (reply.status == 404) {
throw const SessionSecurityException(
'This server\'s web login does not report sign-in security.',
);
}
final decoded = _decode(reply);
return SessionSecurity(
weakPassword: decoded['weak_password'] == true,
rule: '${decoded['password_rule'] ?? ''}'.trim(),
);
}
/// Sends POST /api/sessions/revoke-all: every device signs in again.
Future<void> revokeAllSessions(String endpoint) async {
final uri = securityUri(endpoint, '/api/sessions/revoke-all');
if (uri == null) {
throw const SessionSecurityException('Set the server address first.');
}
final reply = await _send('POST', uri);
if (reply.status == 401) {
throw const SessionSecurityException('Already signed out.');
}
if (_decode(reply)['revoked'] != true) {
throw const SessionSecurityException(
'The server did not confirm the sign-out.',
);
}
}
Future<SecurityReply> _send(String method, Uri uri) async {
try {
return await sendSecurityRequest(method, uri);
} catch (error) {
throw SessionSecurityException('Could not reach the web login: $error');
}
}
Map<String, dynamic> _decode(SecurityReply reply) {
if (reply.status != 200) {
throw SessionSecurityException(
'The web login answered HTTP ${reply.status}.',
);
}
try {
final decoded = jsonDecode(reply.body);
if (decoded is Map<String, dynamic>) return decoded;
} on FormatException {
// Reported below.
}
throw const SessionSecurityException(
'The web login sent an unreadable reply.',
);
}
@@ -0,0 +1,22 @@
import 'dart:convert';
import 'dart:io';
import '../../../core/session/server_session.dart';
import 'session_security_api.dart';
/// Native: the kept session cookie, only for the selected server's origin.
Future<SecurityReply> sendSecurityRequest(String method, Uri uri) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 10);
try {
final request = await client.openUrl(method, uri);
request.followRedirects = false;
ServerSession.headersFor(uri).forEach(request.headers.set);
final response = await request.close().timeout(const Duration(seconds: 15));
final body = await response.transform(utf8.decoder).join();
return (status: response.statusCode, body: body);
} finally {
client.close(force: true);
}
}
void openWebSignIn() {}
@@ -0,0 +1,6 @@
import 'session_security_api.dart';
Future<SecurityReply> sendSecurityRequest(String method, Uri uri) =>
throw UnsupportedError('Not supported on this platform.');
void openWebSignIn() {}
@@ -0,0 +1,23 @@
import 'dart:js_interop';
import 'package:web/web.dart' as web;
import 'session_security_api.dart';
/// Web: the browser sends the sign-in cookie to the page's own origin only.
Future<SecurityReply> sendSecurityRequest(String method, Uri uri) async {
final response = await web.window
.fetch(
uri.toString().toJS,
web.RequestInit(
method: method,
credentials: 'same-origin',
redirect: 'manual',
),
)
.toDart;
final body = (await response.text().toDart).toDart;
return (status: response.status, body: body);
}
void openWebSignIn() => web.window.location.assign('/login');
@@ -0,0 +1,185 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../../core/session/server_session.dart';
import '../../../ui/adaptive/host.dart';
import 'session_security_api.dart';
/// The server's sign-in security: a warning when its password predates the
/// strength rule, and "Sign out everywhere", which revokes every session of
/// this server's web login (this device included).
class SettingsSecuritySection extends StatefulWidget {
const SettingsSecuritySection({
super.key,
required this.endpoint,
required this.onSignedOut,
this.web = kIsWeb,
});
/// The server's websocket address; the proxy endpoints sit beside it.
final String endpoint;
/// Reconnects once this device's session was revoked (native).
final VoidCallback onSignedOut;
/// The web app leaves for the sign-in page instead.
final bool web;
@override
State<SettingsSecuritySection> createState() =>
_SettingsSecuritySectionState();
}
class _SettingsSecuritySectionState extends State<SettingsSecuritySection> {
SessionSecurity? _security;
String? _message;
bool _busy = false;
@override
void initState() {
super.initState();
_load();
}
@override
void didUpdateWidget(SettingsSecuritySection oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.endpoint != widget.endpoint) _load();
}
Future<void> _load() async {
final endpoint = widget.endpoint;
try {
final security = await loadSessionSecurity(endpoint);
if (!mounted || endpoint != widget.endpoint) return;
setState(() {
_security = security;
_message = null;
});
} on SessionSecurityException catch (error) {
if (!mounted || endpoint != widget.endpoint) return;
setState(() {
_security = null;
_message = error.message;
});
}
}
Future<bool> _confirm() async {
const title = Text('Sign out everywhere?');
const body = Text(
'Every browser and device signed in to this server, this one '
'included, must sign in again. Open connections close now.',
);
if (usesCupertinoHost(context)) {
return await showCupertinoDialog<bool>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: title,
content: body,
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
CupertinoDialogAction(
key: const Key('settings-revoke-all-confirm'),
isDestructiveAction: true,
onPressed: () => Navigator.pop(context, true),
child: const Text('Sign out everywhere'),
),
],
),
) ??
false;
}
return await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: title,
content: body,
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
FilledButton(
key: const Key('settings-revoke-all-confirm'),
onPressed: () => Navigator.pop(context, true),
child: const Text('Sign out everywhere'),
),
],
),
) ??
false;
}
Future<void> _revokeAll() async {
if (!await _confirm() || !mounted) return;
setState(() {
_busy = true;
_message = null;
});
try {
await revokeAllSessions(widget.endpoint);
} on SessionSecurityException catch (error) {
if (mounted) {
setState(() {
_busy = false;
_message = error.message;
});
}
return;
}
if (widget.web) {
openWebSignIn();
return;
}
await ServerSession.signOut();
if (!mounted) return;
setState(() {
_busy = false;
_message = 'Signed out everywhere. Sign in again to reconnect.';
});
widget.onSignedOut();
}
@override
Widget build(BuildContext context) {
final security = _security;
final button = usesCupertinoHost(context)
? CupertinoButton(
key: const Key('settings-revoke-all'),
onPressed: _busy ? null : _revokeAll,
child: const Text('Sign out everywhere'),
)
: OutlinedButton(
key: const Key('settings-revoke-all'),
onPressed: _busy ? null : _revokeAll,
child: const Text('Sign out everywhere'),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (security != null && security.weakPassword)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
key: const Key('settings-weak-password'),
'This server\'s sign-in password is weak. '
'${security.rule.isEmpty ? '' : '${security.rule} '}'
'Run ./password on the server to choose a stronger one.',
),
),
const Text(
'Signing out everywhere ends every session of this server\'s web '
'login. Changing the password with ./password does the same.',
),
Align(alignment: AlignmentDirectional.centerStart, child: button),
if (_message != null)
Semantics(liveRegion: true, child: Text(_message!)),
],
);
}
}
@@ -2,6 +2,7 @@ import '../terminal/terminal_layout.dart';
import 'settings_terminal_section.dart';
import '../../ui/adaptive/segmented_bar.dart';
import 'dart:async';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
@@ -31,6 +32,7 @@ import 'settings_android_download_section.dart';
import 'settings_schedules_section.dart';
import 'settings_sections.dart';
import 'settings_sign_in_section.dart';
import 'security/settings_security_section.dart';
import 'settings_updates_section.dart';
import '../updates/app_updates.dart';
import 'settings_store.dart';
@@ -40,6 +40,14 @@ extension _SettingsTopicPages on _SettingsScreenState {
onChanged: _reconnectAfterSignIn,
),
),
if (widget.showSignIn || kIsWeb)
_single(
'Sign-in security',
SettingsSecuritySection(
endpoint: _endpoint,
onSignedOut: _reconnectAfterSignIn,
),
),
SettingsWorkspaceSection(
controller: _controller,
workspaceField: _workspaceField,
@@ -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);
});
}