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:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user