Merge branch 'worktree-agent-a7f96a1eb9a56587d'

# Conflicts:
#	cmd/pipelines-server/main.go
#	internal/server/websocket.go
#	scripts/manage.py
#	scripts/setup-native.py
#	web/serve.mjs
#	web/src/peerRelay.js
This commit is contained in:
2026-11-10 01:25:04 +00:00
60 changed files with 3994 additions and 157 deletions
+14 -1
View File
@@ -3,6 +3,8 @@ import 'dart:async';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import '../core/api_gateway.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'; import '../core/transport/pipelines_client.dart';
/// Whether this connection's send-only `subscribe` was accepted. /// Whether this connection's send-only `subscribe` was accepted.
@@ -32,8 +34,17 @@ class AppSession extends ChangeNotifier {
_everConnected = knownServer { _everConnected = knownServer {
_states = _client.states.listen(_onState); _states = _client.states.listen(_onState);
_frames = _client.frames.listen(_onFrame); _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 Uri? _initialEndpoint;
final List<Uri>? _initialAddresses; final List<Uri>? _initialAddresses;
final PipelinesClient _client; final PipelinesClient _client;
@@ -47,7 +58,8 @@ class AppSession extends ChangeNotifier {
String _subscriptionError = ''; String _subscriptionError = '';
String? _subscribeRequest; 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. /// Settings controls the same transport; it must never create another socket.
PipelinesClient get client => _client; PipelinesClient get client => _client;
@@ -180,6 +192,7 @@ class AppSession extends ChangeNotifier {
_disposed = true; _disposed = true;
_sendUnsubscribe(); _sendUnsubscribe();
unawaited(_states.cancel()); unawaited(_states.cancel());
unawaited(_elevation.dispose());
unawaited(_frames.cancel()); unawaited(_frames.cancel());
unawaited(_client.dispose()); unawaited(_client.dispose());
super.dispose(); super.dispose();
+10
View File
@@ -1,5 +1,7 @@
import '../core/servers/chat/chat_server_pool.dart'; import '../core/servers/chat/chat_server_pool.dart';
import '../core/servers/server_context.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 '../ui/adaptive/platform.dart';
import 'dart:async'; import 'dart:async';
@@ -125,6 +127,9 @@ class _PipelinesAppState extends State<PipelinesApp>
with WidgetsBindingObserver { with WidgetsBindingObserver {
late final AppSession _session; late final AppSession _session;
late final AppRouterDelegate _delegate; late final AppRouterDelegate _delegate;
late final ElevationPrompt _elevationPrompt = elevationDialogPrompt(
() => _delegate.navigatorContext,
);
late final RouteInformationProvider _provider; late final RouteInformationProvider _provider;
late final bool _ownsProvider; late final bool _ownsProvider;
late final RouterConfig<AppRoute> _config; late final RouterConfig<AppRoute> _config;
@@ -221,6 +226,7 @@ class _PipelinesAppState extends State<PipelinesApp>
serverId: widget.serverId, serverId: widget.serverId,
); );
bindServerIdentity(_session.gateway, widget.serverId); bindServerIdentity(_session.gateway, widget.serverId);
bindServerIdentity(_session.client, widget.serverId);
_terminals = AppTerminals( _terminals = AppTerminals(
pool: widget.chatPool, pool: widget.chatPool,
connection: _session, connection: _session,
@@ -294,6 +300,7 @@ class _PipelinesAppState extends State<PipelinesApp>
_session.addListener(_attentionSessionChanged); _session.addListener(_attentionSessionChanged);
_session.addListener(_updateEndpointChanged); _session.addListener(_updateEndpointChanged);
_attention.addListener(_attentionChanged); _attention.addListener(_attentionChanged);
MachineElevation.defaultPrompt = _elevationPrompt;
_delegate = AppRouterDelegate( _delegate = AppRouterDelegate(
initial: initial, initial: initial,
cupertino: _cupertino, cupertino: _cupertino,
@@ -436,6 +443,9 @@ class _PipelinesAppState extends State<PipelinesApp>
_notifications.dispose(); _notifications.dispose();
_deliveryController.dispose(); _deliveryController.dispose();
_chatQuestionNotices?.dispose(); _chatQuestionNotices?.dispose();
if (identical(MachineElevation.defaultPrompt, _elevationPrompt)) {
MachineElevation.defaultPrompt = null;
}
_delegate.removeListener(_routeChanged); _delegate.removeListener(_routeChanged);
_delegate.dispose(); _delegate.dispose();
if (_ownsProvider) { if (_ownsProvider) {
@@ -4,6 +4,8 @@ import '../../session/server_session.dart';
import '../../transport/channel_connect.dart'; import '../../transport/channel_connect.dart';
import '../../transport/pipelines_client.dart'; import '../../transport/pipelines_client.dart';
import '../server_catalog.dart'; import '../server_catalog.dart';
import '../elevation/elevating_gateway.dart';
import '../elevation/machine_elevation.dart';
import 'browser_peer.dart'; import 'browser_peer.dart';
/// The machine answered and wants its own password; it is not unreachable. /// The machine answered and wants its own password; it is not unreachable.
@@ -55,7 +57,9 @@ Future<ChatMachineConnection> connectChatMachine(
final result = await registerBrowserPeer(server); final result = await registerBrowserPeer(server);
if (!result.connected) { if (!result.connected) {
if (result.needsPassword) { 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.'); throw StateError(result.error ?? 'Could not connect to this machine.');
} }
@@ -75,13 +79,22 @@ Future<ChatMachineConnection> connectChatMachine(
: (uri) => connectScopedPipelinesChannel(uri, headers!), : (uri) => connectScopedPipelinesChannel(uri, headers!),
); );
await client.connectAny(endpoints); await client.connectAny(endpoints);
return ChatMachineConnection( // Each machine confirms its own password through its own connection.
final elevation = MachineElevation(
name: server.name,
gateway: client, gateway: client,
states: client.states,
);
return ChatMachineConnection(
gateway: ElevatingGateway(client, elevation),
headers: headers, headers: headers,
endpoint: () => client.endpoint?.toString() ?? '', endpoint: () => client.endpoint?.toString() ?? '',
connected: () => client.state.kind == ConnectionKind.connected, connected: () => client.state.kind == ConnectionKind.connected,
states: client.states, states: client.states,
close: client.dispose, close: () async {
await elevation.dispose();
await client.dispose();
},
retry: () => client.connectAny(endpoints), retry: () => client.connectAny(endpoints),
); );
} }
@@ -3,6 +3,7 @@ import '../../api_gateway.dart';
import '../../transport/pipelines_client.dart'; import '../../transport/pipelines_client.dart';
import '../server_catalog.dart'; import '../server_catalog.dart';
import '../server_scope.dart'; import '../server_scope.dart';
import '../elevation/elevating_gateway.dart';
import 'chat_identity.dart'; import 'chat_identity.dart';
/// Machine-bound chat protocol adapter. Tool inputs, user answers, message IDs /// Machine-bound chat protocol adapter. Tool inputs, user answers, message IDs
@@ -10,6 +11,7 @@ import 'chat_identity.dart';
class ChatServerGateway implements ApiGateway, EndpointGateway { class ChatServerGateway implements ApiGateway, EndpointGateway {
ChatServerGateway(this.server, this.gateway, {this.isCurrent}) { ChatServerGateway(this.server, this.gateway, {this.isCurrent}) {
bindServerIdentity(this, server.id); bindServerIdentity(this, server.id);
bindElevation(this, elevationOf(gateway));
} }
SavedServer server; SavedServer server;
final ApiGateway gateway; 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'; 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. /// Posts the password to the web login and returns its session cookie.
Future<({String? cookie, String? error})> postLogin( Future<({String? cookie, String? error})> postLogin(
Uri login, Uri login,
@@ -23,7 +27,7 @@ Future<({String? cookie, String? error})> postLogin(
final response = await request.close(); final response = await request.close();
await response.drain<void>(); await response.drain<void>();
for (final cookie in response.cookies) { 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); 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); return LoginProbe(status: response.statusCode);
} }
final body = await _head(response, 65536); 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) { } on Exception catch (error) {
return LoginProbe(failure: describeFailure(login, error)); return LoginProbe(failure: describeFailure(login, error));
} finally { } finally {
@@ -71,7 +78,9 @@ Future<LoginProbe> probeLogin(Uri login, Map<String, String> headers) async {
Future<String> _head(HttpClientResponse response, int limit) async { Future<String> _head(HttpClientResponse response, int limit) async {
final buffer = StringBuffer(); 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); buffer.write(chunk);
if (buffer.length > limit) break; if (buffer.length > limit) break;
} }
+4 -1
View File
@@ -14,8 +14,11 @@ class ConnectionState {
} }
class ProtocolError implements Exception { class ProtocolError implements Exception {
const ProtocolError(this.message); const ProtocolError(this.message, {this.code = ''});
final String message; final String message;
/// The server's machine-readable refusal (`elevation_required`), or blank.
final String code;
@override @override
String toString() => message; String toString() => message;
} }
+4 -1
View File
@@ -209,7 +209,10 @@ class PipelinesClient implements ApiGateway {
if (message['type'] == 'error') { if (message['type'] == 'error') {
final reason = '${message['error'] ?? ''}'.trim(); final reason = '${message['error'] ?? ''}'.trim();
pending.completeError( pending.completeError(
ProtocolError(reason.isEmpty ? 'server error' : reason), ProtocolError(
reason.isEmpty ? 'server error' : reason,
code: '${message['code'] ?? ''}',
),
); );
} else { } else {
pending.complete(message); pending.complete(message);
@@ -21,7 +21,14 @@ Future<ChatUploadReply> postChatUpload(
required String name, required String name,
required String mime, required String mime,
required Uint8List bytes, 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. /// The header that carries the file name; the server refuses a post without it.
const chatUploadNameHeader = 'X-Pipelines-Upload-Name'; const chatUploadNameHeader = 'X-Pipelines-Upload-Name';
@@ -10,6 +10,7 @@ Future<ChatUploadReply> postChatUpload(
required String name, required String name,
required String mime, required String mime,
required Uint8List bytes, required Uint8List bytes,
Map<String, String> headers = const {},
}) async { }) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15); final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
try { try {
@@ -21,6 +22,7 @@ Future<ChatUploadReply> postChatUpload(
..set(chatUploadNameHeader, Uri.encodeComponent(name)) ..set(chatUploadNameHeader, Uri.encodeComponent(name))
..set(HttpHeaders.contentTypeHeader, mime) ..set(HttpHeaders.contentTypeHeader, mime)
..contentLength = bytes.length; ..contentLength = bytes.length;
headers.forEach(request.headers.set);
request.add(bytes); request.add(bytes);
final response = await request.close(); final response = await request.close();
final body = await response.transform(utf8.decoder).join(); final body = await response.transform(utf8.decoder).join();
@@ -7,4 +7,5 @@ Future<ChatUploadReply> postChatUpload(
required String name, required String name,
required String mime, required String mime,
required Uint8List bytes, required Uint8List bytes,
Map<String, String> headers = const {},
}) => throw UnsupportedError('Uploads are not supported on this platform.'); }) => throw UnsupportedError('Uploads are not supported on this platform.');
@@ -28,6 +28,7 @@ Future<ChatUploadReply> postChatUpload(
required String name, required String name,
required String mime, required String mime,
required Uint8List bytes, required Uint8List bytes,
Map<String, String> headers = const {},
}) async { }) async {
final response = await _fetch( final response = await _fetch(
uri.toString().toJS, uri.toString().toJS,
@@ -36,6 +37,7 @@ Future<ChatUploadReply> postChatUpload(
headers: { headers: {
chatUploadNameHeader: Uri.encodeComponent(name), chatUploadNameHeader: Uri.encodeComponent(name),
'Content-Type': mime, 'Content-Type': mime,
...headers,
}.jsify()!, }.jsify()!,
body: bytes.toJS, body: bytes.toJS,
credentials: 'same-origin'.toJS, credentials: 'same-origin'.toJS,
@@ -1,5 +1,6 @@
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import '../../../core/servers/elevation/elevating_gateway.dart';
import '../../../core/transport/pipelines_client.dart'; import '../../../core/transport/pipelines_client.dart';
import '../data/directory_listing.dart'; import '../data/directory_listing.dart';
import '../domain/chat_attachment_picker.dart'; import '../domain/chat_attachment_picker.dart';
@@ -113,7 +114,12 @@ class FilesController extends ChangeNotifier {
final failures = <String>[]; final failures = <String>[];
for (final file in files) { for (final file in files) {
try { try {
await uploadFileInto(endpoint, directory, file); await uploadFileInto(
endpoint,
directory,
file,
elevation: elevationOf(gateway),
);
} on FilesUploadException catch (error) { } on FilesUploadException catch (error) {
failures.add(error.message); failures.add(error.message);
} finally { } finally {
+38 -4
View File
@@ -1,6 +1,7 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:typed_data'; import 'dart:typed_data';
import '../../../core/servers/elevation/machine_elevation.dart';
import '../../../core/transport/server_url.dart'; import '../../../core/transport/server_url.dart';
import '../data/upload/chat_upload.dart'; import '../data/upload/chat_upload.dart';
import '../domain/chat_attachment_picker.dart'; import '../domain/chat_attachment_picker.dart';
@@ -12,6 +13,7 @@ typedef FilesUploadPost =
required String name, required String name,
required String mime, required String mime,
required Uint8List bytes, required Uint8List bytes,
Map<String, String> headers,
}); });
/// The transport the Files panel uploads with. /// 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 /// the stored path the server reports. Every failure is a
/// [FilesUploadException]; nothing is retried or renamed on the caller's /// [FilesUploadException]; nothing is retried or renamed on the caller's
/// behalf, so an existing file is reported rather than replaced. /// 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( Future<String> uploadFileInto(
String endpoint, String endpoint,
String directory, String directory,
ChatPickedFile file, ChatPickedFile file, {
) async { MachineElevation? elevation,
}) async {
final name = file.name.trim(); final name = file.name.trim();
if (name.isEmpty) { if (name.isEmpty) {
throw const FilesUploadException( throw const FilesUploadException(
@@ -56,17 +63,26 @@ Future<String> uploadFileInto(
'No server is configured to upload files to.', 'No server is configured to upload files to.',
); );
} }
final ChatUploadReply reply; Future<ChatUploadReply> post() async {
final token = elevation?.token;
try { try {
reply = await postFileUpload( return await postFileUpload(
uri, uri,
name: name, name: name,
mime: file.mime.trim().isEmpty ? 'application/octet-stream' : file.mime, mime: file.mime.trim().isEmpty ? 'application/octet-stream' : file.mime,
bytes: file.bytes, bytes: file.bytes,
headers: {elevationHeader: ?token},
); );
} catch (error) { } catch (error) {
throw FilesUploadException('"$name" could not be uploaded: $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(); final reason = reply.body.trim();
switch (reply.status) { switch (reply.status) {
case 200: case 200:
@@ -75,6 +91,10 @@ Future<String> uploadFileInto(
throw const FilesUploadException( throw const FilesUploadException(
'Sign in to upload files (Settings → Sign in).', '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: case 409:
throw FilesUploadException('"$name" already exists in this folder.'); throw FilesUploadException('"$name" already exists in this folder.');
case 413: case 413:
@@ -97,3 +117,17 @@ Future<String> uploadFileInto(
} }
throw FilesUploadException('"$name" upload returned no stored path.'); 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 'settings_terminal_section.dart';
import '../../ui/adaptive/segmented_bar.dart'; import '../../ui/adaptive/segmented_bar.dart';
import 'dart:async'; import 'dart:async';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -31,6 +32,7 @@ import 'settings_android_download_section.dart';
import 'settings_schedules_section.dart'; import 'settings_schedules_section.dart';
import 'settings_sections.dart'; import 'settings_sections.dart';
import 'settings_sign_in_section.dart'; import 'settings_sign_in_section.dart';
import 'security/settings_security_section.dart';
import 'settings_updates_section.dart'; import 'settings_updates_section.dart';
import '../updates/app_updates.dart'; import '../updates/app_updates.dart';
import 'settings_store.dart'; import 'settings_store.dart';
@@ -40,6 +40,14 @@ extension _SettingsTopicPages on _SettingsScreenState {
onChanged: _reconnectAfterSignIn, onChanged: _reconnectAfterSignIn,
), ),
), ),
if (widget.showSignIn || kIsWeb)
_single(
'Sign-in security',
SettingsSecuritySection(
endpoint: _endpoint,
onSignedOut: _reconnectAfterSignIn,
),
),
SettingsWorkspaceSection( SettingsWorkspaceSection(
controller: _controller, controller: _controller,
workspaceField: _workspaceField, 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"}'); reply = (status: 200, body: '{"path":"/home/demo/new.txt"}');
gate = null; gate = null;
postFileUpload = 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)); posted.add((uri: uri, name: name, mime: mime, size: bytes.length));
if (gate != null) await gate!.future; if (gate != null) await gate!.future;
return reply; return reply;
@@ -187,7 +193,13 @@ void main() {
) async { ) async {
var calls = 0; var calls = 0;
postFileUpload = postFileUpload =
(uri, {required name, required mime, required bytes}) async { (
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) async {
calls += 1; calls += 1;
return name == 'kept.txt' return name == 'kept.txt'
? (status: 409, body: 'exists') ? (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? postedName;
String? postedMime; String? postedMime;
postFileUpload = postFileUpload =
(uri, {required name, required mime, required bytes}) async { (
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) async {
posted = uri; posted = uri;
postedName = name; postedName = name;
postedMime = mime; postedMime = mime;
@@ -49,7 +55,13 @@ void main() {
test('a relay endpoint posts through its peer prefix', () async { test('a relay endpoint posts through its peer prefix', () async {
Uri? posted; Uri? posted;
postFileUpload = postFileUpload =
(uri, {required name, required mime, required bytes}) async { (
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) async {
posted = uri; posted = uri;
return (status: 200, body: '{"path":"/home/x/notes.txt"}'); return (status: 200, body: '{"path":"/home/x/notes.txt"}');
}; };
@@ -64,8 +76,13 @@ void main() {
test('server refusals become plain messages', () async { test('server refusals become plain messages', () async {
Future<String> message(int status, String body) async { Future<String> message(int status, String body) async {
postFileUpload = 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 { try {
await uploadFileInto('ws://example.test/connect', '/home/demo', file); await uploadFileInto('ws://example.test/connect', '/home/demo', file);
} on FilesUploadException catch (error) { } on FilesUploadException catch (error) {
@@ -103,8 +120,14 @@ void main() {
test( test(
'transport failures and blank names are reported, not swallowed', 'transport failures and blank names are reported, not swallowed',
() async { () async {
postFileUpload = (uri, {required name, required mime, required bytes}) => postFileUpload =
throw StateError('socket closed'); (
uri, {
required name,
required mime,
required bytes,
headers = const {},
}) => throw StateError('socket closed');
await expectLater( await expectLater(
uploadFileInto('ws://example.test/connect', '/home/demo', file), uploadFileInto('ws://example.test/connect', '/home/demo', file),
throwsA( 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);
});
}
+5
View File
@@ -98,6 +98,11 @@ func main() {
// harness; the summariser falls back to the prompt's first line, so title // harness; the summariser falls back to the prompt's first line, so title
// generation never blocks or fails run creation. // generation never blocks or fails run creation.
options := server.Options{AllowAuthoring: *allowAuthoring, ArtifactsRoot: artifactsRoot, RunTitles: summarise.GenerateTitle, StepVerdicts: summarise.GenerateVerdictReason, VerificationFixtures: server.VerificationFixturesFromEnvironment(os.Getenv), DetachSessions: detach, AccessToken: accessToken} options := server.Options{AllowAuthoring: *allowAuthoring, ArtifactsRoot: artifactsRoot, RunTitles: summarise.GenerateTitle, StepVerdicts: summarise.GenerateVerdictReason, VerificationFixtures: server.VerificationFixturesFromEnvironment(os.Getenv), DetachSessions: detach, AccessToken: accessToken}
// Shell commands, terminals and file changes need a recent confirmation of
// the web sign-in password on the same connection (step-up
// re-authentication). PIPELINES_ELEVATION_MINUTES overrides 15 minutes.
options.WebAuthFile = server.DefaultWebAuthFile()
options.ElevationTTL = server.ElevationTTLFromEnvironment(os.Getenv)
recorded := "" recorded := ""
if value, err := store.OpenCodeEndpoint(ctx); err != nil { if value, err := store.OpenCodeEndpoint(ctx); err != nil {
log.Printf("OpenCode endpoint setting unreadable: %v", err) log.Printf("OpenCode endpoint setting unreadable: %v", err)
+214
View File
@@ -0,0 +1,214 @@
# Web sign-in and session hardening (2026-11-10)
This change covers the sign-in, session, password and step-up code: `web/serve.mjs`,
`web/src/{authStore,loginLimiter,passwordPolicy,sessionSockets,webSecurity}.js`,
`scripts/password.py`, `internal/server/{elevation,webauth_*}.go`,
`internal/protocol/elevation.go`, plus the app's `lib/core/servers/elevation/`
and `lib/features/settings/security/`. The server trust boundary, network
binding, update signing and the `su -l` terminal belong to other changes.
## Behaviour
**Password storage.** `web-auth.json` (0600) now holds
`password_hash: "scrypt$N$r$p$<salt>$<key>"` (unpadded base64url, N=32768, r=8,
p=1, 32-byte key), `password_weak`, `secret` and `generation`. Node
(`crypto.scrypt`), Python (`hashlib.scrypt`) and Go (a small RFC 7914
implementation checked against the RFC vectors) all verify the same hash. Every
comparison is constant time. The first time the proxy loads a file that still
holds a plaintext `password`, it rewrites the file atomically with the hash. The
password itself does not change. A plaintext written over a running proxy's file
counts as a password change and signs everyone out.
**Sessions.** A token is `v2.<generation>.<issued ms>.<expires s>.<id>.<HMAC>`.
It is valid only when all of these hold:
- the signature checks out;
- `generation` matches the file;
- it has not expired;
- it was issued after `not_before`;
- its id is not on the signed-out list.
Changes that end sessions:
- **`./password`**: stores a new hash, rotates `secret` and bumps `generation`.
Every device is signed out.
- **`./password --revoke-all`**: same rotation, but keeps the password.
- **Settings → Sign-in security → Sign out everywhere**: calls
`POST /api/sessions/revoke-all`, which sets `not_before` in
`<auth file>.sessions.json` (0600, written only by the proxy).
- **Logout**: now `POST /logout`, same-origin only. It adds the token id to the
signed-out list, which is kept until the token expires. The list holds at most
10000 entries; when full, the soonest-expiring entries are dropped first.
`GET /logout` only shows a Sign out button.
Every upgraded socket (`/connect` and relayed peer sockets) remembers its token.
The proxy closes it on logout or revocation, when the file changes, and on a
5-second sweep (`PIPELINES_WEB_SWEEP_MS`), so expired sessions are cut too. Tokens
from before this change are no longer accepted.
**New passwords** (`./password`, first install) must be either:
- 16 or more characters, or
- 4 or more distinct random words, separated by spaces or dashes, 15 characters
or more in all.
Common words, keyboard runs and repeated characters do not count towards the
length. The rule lives in `scripts/password.py` and `web/src/passwordPolicy.js`.
An existing password that fails the rule still works:
- the file records `password_weak: true`;
- Settings shows a warning;
- `./password` prints a one-time warning before its prompts.
**Brute force.**
- **Per client**: 5 free failures, then the wait doubles from 1 s up to 15 min.
- **Server-wide**: a sliding window of 50 failures per 5 min blocks every client.
- **Bounds**: at most 1024 tracked clients, least recent evicted first; idle
entries expire after 1 h.
- **Concurrency**: at most 4 scrypt checks run at once; the rest get 429.
A login is charged to its socket address. The one exception is a request that
arrives from loopback and carries `Tailscale-*` headers (that is, `tailscale
serve`). That request is charged to `Tailscale-User-Login`, or failing that to
the first `X-Forwarded-For` address. These headers are trusted only in that
case. A local process could forge them, but it already runs on the machine, and
the server-wide window still applies.
**Form hygiene and headers.**
- **Login CSRF**: `POST /login`, `POST /logout` and the revoke-all endpoint
refuse a foreign `Origin`, `Origin: null`, or a cross-site `Sec-Fetch-Site`.
Native clients send no Origin and are accepted.
- **Redirect target**: `next` must be a single `/` followed by a character other
than `/` or `\`, with no backslash or control characters anywhere. Anything
else becomes `/`.
- **Every response**: `X-Content-Type-Options: nosniff`,
`Referrer-Policy: same-origin`, `X-Frame-Options: SAMEORIGIN` and
`CSP frame-ancestors 'self'`. The app's own HTML previews are sandboxed
`srcdoc` iframes, so they keep working.
- **Sign-in and sign-out pages**: `X-Frame-Options: DENY` and a CSP of
`default-src 'none'; img-src 'self'; style-src 'unsafe-inline';
form-action 'self'; frame-ancestors 'none'; base-uri 'none'`.
- **HSTS** only when `x-forwarded-proto` is `https`.
- **Cookie**: over https it is `__Host-pipelines_session` with `Secure`; over
plain http it is still `pipelines_session`. The proxy, the peer relay and the
native app accept both names.
**Step-up re-authentication.** A session alone can no longer run a shell. The
following now need a password confirmation on the same websocket connection
within the last 15 minutes (`PIPELINES_ELEVATION_MINUTES`, 1–720):
- `chat_shell_run`, `chat_shell_input`;
- `rename_path`, `move_path`, `delete_path`;
- `terminal_open`, `terminal_input`;
- `POST /files`.
The flow:
- The client sends `{"type":"elevate","password":…}`. The Go server reads the
auth file read-only: it must be a regular file, owned by the user, mode 0600.
- On success the reply is `elevated` with `{expires_at, seconds, token}`.
- A refused request gets `{"type":"error","code":"elevation_required"}`.
- A wrong password gets `elevation_failed`. Each wrong password doubles that
connection's wait (1 s, up to 1 min). 10 failures per 5 min across the server
block all attempts. Only one scrypt check runs at a time.
Uploads travel outside the websocket. They carry the token in
`X-Pipelines-Elevation`. The token lives only in memory and dies when its
connection closes or expires. A refused upload gets 403
`{"code":"elevation_required"}`. The peer relay forwards the header, so each
machine elevates through its own gateway with its own password.
When does the gate apply?
- **Auth file exists**: the gate is on.
- **No auth file** (a bare server without the web proxy, or tests): nothing is
gated, and `elevate` answers `elevation_unavailable`.
- **Auth file exists but is unusable**: the gate stays closed (fail closed).
In the app, one native dialog per machine (Material, or Cupertino on Apple
platforms) asks for the password once. The app then retries the refused request.
Concurrent refusals share one dialog. The elevation is forgotten when the
connection drops.
## What the operator must do on the live install
1. Install the updated app builds (APK, desktop) together with or before the
proxy. Over https, older app builds only recognise the old cookie name and
cannot sign in.
2. Deploy as usual (`./install`, then restart when no run or chat is active).
- The proxy migrates `~/.config/pipelines/web-auth.json` to a hash on its
first start. The password stays the same.
- Old-format session cookies are refused, so each browser, phone and peer
machine signs in once.
- The server needs the restart too, to start gating. `manage.py` now passes
`PIPELINES_WEB_AUTH_FILE` to it.
3. If Settings or `./password` reports the password as weak, run `./password`
on the server (in a terminal) and choose one that meets the rule. This signs
every device out.
4. After a lost device, run `./password --revoke-all`, or use Settings → Sign
out everywhere.
5. Repeat on each machine; each one keeps its own password and its own
elevation.
The installer accepts both the hashed and the plaintext format. It writes only
hashes for new installs and applies the strength rule to a newly chosen
password. The ntfy `phone-reader` account keeps its own password. On a reinstall
with a hashed file, an existing ntfy account is preserved and a new one is asked
for on the terminal.
## Not covered / residual
- `terminal_output` (attaching to and reading an existing terminal) is not
gated. Typing into one (`terminal_input`) is.
- `/chat-uploads` (chat attachments into the chat's upload area) is not gated.
- The server-wide login window can lock the real operator out during an attack.
That is the trade-off that bounds guessing.
- The peer relay's `/api/peers` POST was not reviewed here. It belongs to the
trust-boundary change.
## Verification (2026-11-10)
- `cd web && node --test test/`: tests 34, pass 34, fail 0.
- New: `test/authStore.test.mjs`, `test/authProxy.test.mjs`.
- Updated: `authReload.test.mjs` (a changed password now signs the old cookie
out).
- `python3 -m unittest scripts.test_password`: Ran 16 tests, OK.
- `python3 -m unittest scripts.test_setup_native scripts.test_uninstall`: Ran 70
tests, OK.
- `umask 022 && go test ./internal/protocol ./cmd/pipelines-server ./internal/server`:
all ok (`internal/server` 70.5 s).
- New: `elevation_test.go`, `webauth_scrypt_test.go` (RFC 7914 vectors and
Node/Python hashes).
- `cd app && tool/analyze.sh`: `analyze: clean`.
- `tool/memwatch/full.sh 'test/core/servers/elevation test/features/chat/files test/features/settings/security test/core/session/post_login_cookie_test.dart test/core/transport'`:
PASS, 93 passed, 0 failed.
- The wider `test/core test/features/chat test/features/terminal test/features/settings`
run: PASS, 1495 passed.
- `test/application`: 51 failures. An untouched HEAD fails the same 51
(pending launch-update timer).
Scratch end-to-end used:
- an isolated `HOME` with its own plaintext weak auth file;
- a scratch DB, OS-chosen ports, `PIPELINES_MDNS=off`;
- a tagged operator session inserted into the scratch DB.
Output:
```
auth file keys after proxy start: ['password_hash', 'password_weak', 'secret'] weak= True
login with the existing (migrated) password: 303 pipelines_session
/api/session weak_password: true
chat_shell_run before elevate: {"type":"error","code":"elevation_required",...}
elevate wrong password: {"type":"error","code":"elevation_failed","error":"wrong password"}
elevate right password: {"type":"elevated","elevation":{"seconds":900,"token":"<redacted>"}}
chat_shell_run after elevate: {"type":"chat_shell_run","run":{"status":"running","command":"echo elevated-shell-ok"}}
chat_shell_runs: [{"command":"echo elevated-shell-ok","status":"exited","exit_code":0,"output":"elevated-shell-ok"}]
--- changing the password with scripts/password.py
auth file keys after change: ['generation', 'password_hash', 'password_weak', 'secret'] generation= 1
websocket closed after the password change: true 47 ms
old cookie still signed in: false
old password login: 401
new password login: 303
/api/session weak_password: false
new connection is not elevated: {"type":"error","code":"elevation_required",...}
elevate with the new password: {"type":"elevated",...}
logout: 303
websocket closed after logout: true
logged-out cookie still signed in: false
--- ./password --revoke-all
Every browser and device was signed out; sign in again with the same password.
password occurrences in server.log / web.log: 0 / 0
```
+39
View File
@@ -0,0 +1,39 @@
package protocol
// Step-up re-authentication. A signed-in web session can read everything, but
// running shell commands, typing into a shell, changing or uploading files and
// opening a terminal additionally need a recent password confirmation on the
// same connection. The server verifies the password against the web sign-in
// password file; the elevation lasts for a bounded time (15 minutes by
// default) and ends with the connection.
const (
// Elevate confirms the sign-in password (Message.Password). The reply is
// Elevated, or Error with Code ErrorElevationFailed or
// ErrorElevationUnavailable.
Elevate = "elevate"
// Elevated carries Elevation: when it ends and the upload token.
Elevated = "elevated"
// ErrorElevationRequired types the refusal of a gated request on a
// connection that is not (or no longer) elevated. Clients confirm the
// password with Elevate and retry.
ErrorElevationRequired = "elevation_required"
// ErrorElevationFailed types a wrong password or a rate-limited attempt.
ErrorElevationFailed = "elevation_failed"
// ErrorElevationUnavailable types an elevate on a server without a web
// sign-in password file (nothing is gated there).
ErrorElevationUnavailable = "elevation_unavailable"
// ElevationHeader carries Elevation.Token on POST /files. A refused upload
// answers 403 with a JSON body {"code":"elevation_required","error":...}.
ElevationHeader = "X-Pipelines-Elevation"
)
// Elevation is the elevated reply body.
type Elevation struct {
// ExpiresAt is RFC 3339 UTC; Seconds is the remaining lifetime, for
// clients whose clock differs from the server's.
ExpiresAt string `json:"expires_at"`
Seconds int `json:"seconds"`
// Token authorises HTTP uploads for as long as this connection stays
// elevated. It is random, held only in memory and never logged.
Token string `json:"token,omitempty"`
}
+6
View File
@@ -302,6 +302,12 @@ type Message struct {
MovePath *MovePathRequest `json:"move_path,omitempty"` MovePath *MovePathRequest `json:"move_path,omitempty"`
DeletePath *DeletePathRequest `json:"delete_path,omitempty"` DeletePath *DeletePathRequest `json:"delete_path,omitempty"`
PathMutated *PathMutatedResult `json:"path_mutated,omitempty"` PathMutated *PathMutatedResult `json:"path_mutated,omitempty"`
// Step-up re-authentication (see elevation.go): Code types an error,
// Password is the elevate body (never logged or echoed) and Elevation the
// elevated reply.
Code string `json:"code,omitempty"`
Password string `json:"password,omitempty"`
Elevation *Elevation `json:"elevation,omitempty"`
// ChatAttachmentImageRequest is the chat_attachment_image body and // ChatAttachmentImageRequest is the chat_attachment_image body and
// ChatAttachmentImage its reply. // ChatAttachmentImage its reply.
ChatAttachmentImageRequest *ChatAttachmentImageRequest `json:"chat_attachment_image_request,omitempty"` ChatAttachmentImageRequest *ChatAttachmentImageRequest `json:"chat_attachment_image_request,omitempty"`
+292
View File
@@ -0,0 +1,292 @@
package server
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"log"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Step-up re-authentication (see internal/protocol/elevation.go). A web
// session is enough to read, but the requests below act as the operator's
// shell, so each connection must also confirm the sign-in password recently.
// The gate is on whenever the web sign-in password file exists; a server run
// without the web proxy (tests, a bare loopback server) has nothing to verify
// against and keeps its previous behaviour. A file that exists but cannot be
// read safely keeps the gate on and every elevate fails (fail closed).
// DefaultElevationTTL is how long one confirmation lasts on a connection.
const DefaultElevationTTL = 15 * time.Minute
// Elevation attempt limits: a connection waits elevationBackoffBase doubled
// for each consecutive wrong password (at most elevationBackoffMax), and the
// whole server refuses attempts after elevationGlobalFailures wrong passwords
// within elevationGlobalWindow.
const (
elevationBackoffBase = time.Second
elevationBackoffMax = time.Minute
elevationGlobalFailures = 10
elevationGlobalWindow = 5 * time.Minute
elevationTokenLimit = 256
)
var elevationGated = map[string]bool{
protocol.ChatShellRun: true,
protocol.ChatShellInput: true,
protocol.RenamePath: true,
protocol.MovePath: true,
protocol.DeletePath: true,
protocol.TerminalOpen: true,
protocol.TerminalInput: true,
}
type elevationGate struct {
authFile string
ttl time.Duration
now func() time.Time
// verify serializes scrypt work: one 32 MiB derivation at a time.
verify sync.Mutex
mu sync.Mutex
until map[string]time.Time // client -> elevation end
tokens map[string]elevationToken
failures map[string]elevationFailures
recent []time.Time // wrong passwords, server-wide, oldest first
reported bool
}
type elevationToken struct {
client string
until time.Time
}
type elevationFailures struct {
count int
until time.Time
}
func newElevationGate(authFile string, ttl time.Duration) *elevationGate {
if ttl <= 0 {
ttl = DefaultElevationTTL
}
return &elevationGate{
authFile: authFile,
ttl: ttl,
now: time.Now,
until: map[string]time.Time{},
tokens: map[string]elevationToken{},
failures: map[string]elevationFailures{},
}
}
// enabled reports whether gated requests need elevation.
func (g *elevationGate) enabled() bool {
if g == nil || g.authFile == "" {
return false
}
_, err := readWebAuth(g.authFile)
if errors.Is(err, errWebAuthMissing) {
return false
}
if err != nil {
g.mu.Lock()
if !g.reported {
log.Printf("elevation: web sign-in password file unusable, every elevate fails: %v", err)
g.reported = true
}
g.mu.Unlock()
}
return true
}
func (g *elevationGate) elevated(client string) bool {
g.mu.Lock()
defer g.mu.Unlock()
until, ok := g.until[client]
if ok && !g.now().Before(until) {
g.dropLocked(client)
return false
}
return ok
}
// allows reports whether client may perform a gated request now.
func (g *elevationGate) allows(client string) bool {
return g.elevated(client) || !g.enabled()
}
// refuse answers a gated request on a connection that is not elevated with a
// typed error and reports true; any other request passes (false).
func (g *elevationGate) refuse(request protocol.Message, client string, write func(protocol.Message) error) bool {
if !elevationGated[request.Type] || g.allows(client) {
return false
}
_ = write(protocol.Message{
Type: protocol.Error,
ID: request.ID,
Code: protocol.ErrorElevationRequired,
Error: "Confirm your password to run commands, change files or use a terminal on this machine.",
})
return true
}
// handle answers an elevate request and reports true; other requests pass.
func (g *elevationGate) handle(request protocol.Message, client string, write func(protocol.Message) error) bool {
if request.Type != protocol.Elevate {
return false
}
reply, err := g.elevate(client, request.Password)
if err != nil {
code := protocol.ErrorElevationFailed
if errors.Is(err, errWebAuthMissing) {
code = protocol.ErrorElevationUnavailable
}
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Code: code, Error: err.Error()})
return true
}
_ = write(protocol.Message{Type: protocol.Elevated, ID: request.ID, Elevation: reply})
return true
}
func (g *elevationGate) elevate(client, password string) (*protocol.Elevation, error) {
if g == nil || g.authFile == "" {
return nil, fmt.Errorf("this server has no web sign-in password to confirm: %w", errWebAuthMissing)
}
if wait := g.blocked(client); wait > 0 {
return nil, fmt.Errorf("too many wrong passwords; try again in %d seconds", int((wait+time.Second-1)/time.Second))
}
verifier, err := readWebAuth(g.authFile)
if errors.Is(err, errWebAuthMissing) {
return nil, fmt.Errorf("this server has no web sign-in password to confirm: %w", err)
}
if err != nil {
log.Printf("elevation: web sign-in password file unusable: %v", err)
return nil, errors.New("the server's sign-in password file is unusable; see the server log")
}
g.verify.Lock()
ok, err := verifier.verify(password)
g.verify.Unlock()
if err != nil {
log.Printf("elevation: verify: %v", err)
return nil, errors.New("the password could not be checked; see the server log")
}
if !ok {
g.noteFailure(client)
return nil, errors.New("wrong password")
}
return g.grant(client)
}
func (g *elevationGate) blocked(client string) time.Duration {
g.mu.Lock()
defer g.mu.Unlock()
now := g.now()
g.pruneLocked(now)
if len(g.recent) >= elevationGlobalFailures {
return g.recent[0].Add(elevationGlobalWindow).Sub(now)
}
if entry, ok := g.failures[client]; ok && now.Before(entry.until) {
return entry.until.Sub(now)
}
return 0
}
func (g *elevationGate) pruneLocked(now time.Time) {
keep := 0
for keep < len(g.recent) && !now.Before(g.recent[keep].Add(elevationGlobalWindow)) {
keep++
}
g.recent = g.recent[keep:]
}
func (g *elevationGate) noteFailure(client string) {
g.mu.Lock()
defer g.mu.Unlock()
now := g.now()
g.recent = append(g.recent, now)
entry := g.failures[client]
entry.count++
delay := elevationBackoffBase << min(entry.count-1, 6)
entry.until = now.Add(min(delay, elevationBackoffMax))
g.failures[client] = entry
}
func (g *elevationGate) grant(client string) (*protocol.Elevation, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return nil, err
}
token := base64.RawURLEncoding.EncodeToString(raw)
g.mu.Lock()
defer g.mu.Unlock()
now := g.now()
until := now.Add(g.ttl)
g.dropLocked(client)
delete(g.failures, client)
for key, entry := range g.tokens {
if !now.Before(entry.until) {
delete(g.tokens, key)
}
}
if len(g.tokens) >= elevationTokenLimit {
return nil, errors.New("too many elevated connections on this server")
}
g.until[client] = until
g.tokens[tokenKey(token)] = elevationToken{client: client, until: until}
return &protocol.Elevation{
ExpiresAt: until.UTC().Format(time.RFC3339),
Seconds: int(g.ttl / time.Second),
Token: token,
}, nil
}
func tokenKey(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// dropLocked ends client's elevation and its upload token.
func (g *elevationGate) dropLocked(client string) {
delete(g.until, client)
for key, entry := range g.tokens {
if entry.client == client {
delete(g.tokens, key)
}
}
}
// forget ends a closed connection's elevation and attempt history.
func (g *elevationGate) forget(client string) {
if g == nil {
return
}
g.mu.Lock()
defer g.mu.Unlock()
g.dropLocked(client)
delete(g.failures, client)
}
// tokenValid reports whether token belongs to a still elevated connection.
func (g *elevationGate) tokenValid(token string) bool {
if token == "" {
return false
}
g.mu.Lock()
defer g.mu.Unlock()
entry, ok := g.tokens[tokenKey(token)]
if !ok {
return false
}
if !g.now().Before(entry.until) {
g.dropLocked(entry.client)
return false
}
return true
}
+40
View File
@@ -0,0 +1,40 @@
package server
import (
"encoding/json"
"net/http"
"strconv"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// requireElevationHTTP guards an HTTP route that changes the operator's files.
// The upload travels outside the websocket, so the elevated connection's token
// (protocol.ElevationHeader) authorises it; it is valid only while that
// connection stays open and elevated.
func (g *elevationGate) requireElevationHTTP(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if g.tokenValid(r.Header.Get(protocol.ElevationHeader)) || !g.enabled() {
next(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusForbidden)
_ = json.NewEncoder(w).Encode(map[string]string{
"code": protocol.ErrorElevationRequired,
"error": "Confirm your password to upload files to this machine.",
})
}
}
// ElevationTTLFromEnvironment reads PIPELINES_ELEVATION_MINUTES (1 to 720);
// anything else keeps DefaultElevationTTL.
func ElevationTTLFromEnvironment(getenv func(string) string) time.Duration {
minutes, err := strconv.Atoi(getenv("PIPELINES_ELEVATION_MINUTES"))
if err != nil || minutes < 1 || minutes > 720 {
return DefaultElevationTTL
}
return time.Duration(minutes) * time.Minute
}
+243
View File
@@ -0,0 +1,243 @@
package server
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// writeTestWebAuth writes a private auth file with a cheap scrypt hash.
func writeTestWebAuth(t *testing.T, password string) string {
t.Helper()
salt := []byte("0123456789abcdef")
key, err := scryptKey([]byte(password), salt, 1024, 8, 1, 32)
if err != nil {
t.Fatal(err)
}
hash := fmt.Sprintf("scrypt$1024$8$1$%s$%s", base64.RawURLEncoding.EncodeToString(salt), base64.RawURLEncoding.EncodeToString(key))
return writeTestAuthJSON(t, map[string]any{"password_hash": hash, "secret": strings.Repeat("s", 40), "generation": 1})
}
func writeTestAuthJSON(t *testing.T, value map[string]any) string {
t.Helper()
path := filepath.Join(t.TempDir(), "web-auth.json")
body, _ := json.Marshal(value)
if err := os.WriteFile(path, body, 0o600); err != nil {
t.Fatal(err)
}
return path
}
func TestWebAuthVerifierHashPlaintextAndUnsafeFiles(t *testing.T) {
verifier, err := readWebAuth(writeTestWebAuth(t, "correct horse battery staple"))
if err != nil {
t.Fatal(err)
}
for candidate, want := range map[string]bool{"correct horse battery staple": true, "correct horse battery stapl": false, "": false} {
if got, err := verifier.verify(candidate); err != nil || got != want {
t.Fatalf("verify(%q) = %v, %v", candidate, got, err)
}
}
legacy, err := readWebAuth(writeTestAuthJSON(t, map[string]any{"password": "legacy-password", "secret": strings.Repeat("s", 40)}))
if err != nil {
t.Fatal(err)
}
if ok, _ := legacy.verify("legacy-password"); !ok {
t.Fatal("legacy plaintext password not accepted")
}
if ok, _ := legacy.verify("legacy-passwore"); ok {
t.Fatal("wrong legacy password accepted")
}
public := writeTestWebAuth(t, "x")
if err := os.Chmod(public, 0o644); err != nil {
t.Fatal(err)
}
if _, err := readWebAuth(public); err == nil || !strings.Contains(err.Error(), "private") {
t.Fatalf("public file accepted: %v", err)
}
if _, err := readWebAuth(writeTestAuthJSON(t, map[string]any{"password_hash": "scrypt$1000$8$1$AAAA$BBBB"})); err == nil {
t.Fatal("malformed hash accepted")
}
if _, err := readWebAuth(filepath.Join(t.TempDir(), "absent.json")); err != errWebAuthMissing {
t.Fatalf("missing file: %v", err)
}
}
func TestElevationBackoffGlobalCapAndExpiry(t *testing.T) {
gate := newElevationGate(writeTestWebAuth(t, "right password here"), time.Minute)
now := time.Unix(1_800_000_000, 0)
gate.now = func() time.Time { return now }
if _, err := gate.elevate("a", "wrong"); err == nil || err.Error() != "wrong password" {
t.Fatalf("wrong password: %v", err)
}
// The connection now waits before its next attempt, even a right one.
if _, err := gate.elevate("a", "right password here"); err == nil || !strings.Contains(err.Error(), "too many") {
t.Fatalf("backoff not applied: %v", err)
}
now = now.Add(2 * time.Second)
reply, err := gate.elevate("a", "right password here")
if err != nil || reply.Seconds != 60 || reply.Token == "" {
t.Fatalf("elevate: %+v %v", reply, err)
}
if !gate.elevated("a") || !gate.tokenValid(reply.Token) || gate.elevated("b") {
t.Fatal("elevation state wrong after success")
}
now = now.Add(time.Minute)
if gate.elevated("a") || gate.tokenValid(reply.Token) {
t.Fatal("elevation outlived its lifetime")
}
// Ten wrong passwords from separate connections close the gate for all.
for i := range elevationGlobalFailures {
if _, err := gate.elevate(fmt.Sprintf("c%d", i), "wrong"); err == nil {
t.Fatal("wrong password accepted")
}
}
if _, err := gate.elevate("fresh", "right password here"); err == nil || !strings.Contains(err.Error(), "too many") {
t.Fatalf("global cap not applied: %v", err)
}
now = now.Add(elevationGlobalWindow)
if _, err := gate.elevate("fresh", "right password here"); err != nil {
t.Fatalf("global window did not drain: %v", err)
}
gate.forget("fresh")
if gate.elevated("fresh") {
t.Fatal("closed connection stayed elevated")
}
}
func elevationRequest(t *testing.T, ctx context.Context, conn *websocket.Conn, message protocol.Message) protocol.Message {
t.Helper()
if err := wsjson.Write(ctx, conn, message); err != nil {
t.Fatal(err)
}
for {
var reply protocol.Message
if err := wsjson.Read(ctx, conn, &reply); err != nil {
t.Fatal(err)
}
if reply.ID == message.ID {
return reply
}
}
}
func TestGatedRequestsNeedElevationOnTheSameConnection(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
t.Setenv("HOME", t.TempDir()) // the gated handlers never touch the real home
auth := writeTestWebAuth(t, "right password here")
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{WebAuthFile: auth}))
defer srv.Close()
dial := func() *websocket.Conn {
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.CloseNow() })
return conn
}
conn := dial()
gated := []protocol.Message{
{Type: protocol.ChatShellRun, ID: "run"},
{Type: protocol.ChatShellInput, ID: "input"},
{Type: protocol.DeletePath, ID: "delete", DeletePath: &protocol.DeletePathRequest{Path: "~/absent-elevation-test"}},
{Type: protocol.RenamePath, ID: "rename"},
{Type: protocol.MovePath, ID: "move"},
{Type: protocol.TerminalOpen, ID: "terminal"},
{Type: protocol.TerminalInput, ID: "terminal-input"},
}
for _, request := range gated {
reply := elevationRequest(t, ctx, conn, request)
if reply.Type != protocol.Error || reply.Code != protocol.ErrorElevationRequired {
t.Fatalf("%s not refused: %+v", request.Type, reply)
}
}
// Reads are not gated.
if reply := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Ping, ID: "ping"}); reply.Type != protocol.Pong {
t.Fatalf("ping refused: %+v", reply)
}
upload := func(token string) *http.Response {
request, _ := http.NewRequest(http.MethodPost, srv.URL+"/files?path=~/absent-elevation-folder", strings.NewReader("x"))
request.Header.Set(chatUploadHeader, "elevation-test.txt")
if token != "" {
request.Header.Set(protocol.ElevationHeader, token)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatal(err)
}
response.Body.Close()
return response
}
if response := upload(""); response.StatusCode != http.StatusForbidden {
t.Fatalf("upload without elevation: %d", response.StatusCode)
}
wrong := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Elevate, ID: "wrong", Password: "nope"})
if wrong.Type != protocol.Error || wrong.Code != protocol.ErrorElevationFailed || strings.Contains(wrong.Error, "nope") {
t.Fatalf("wrong password reply: %+v", wrong)
}
time.Sleep(elevationBackoffBase + 100*time.Millisecond)
elevated := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Elevate, ID: "right", Password: "right password here"})
if elevated.Type != protocol.Elevated || elevated.Elevation == nil || elevated.Elevation.Token == "" || elevated.Password != "" {
t.Fatalf("elevate reply: %+v", elevated)
}
// The gate now lets the request through to its own handler.
if reply := elevationRequest(t, ctx, conn, gated[2]); reply.Code == protocol.ErrorElevationRequired {
t.Fatalf("elevated delete still refused: %+v", reply)
}
// Another connection is not elevated by this one.
other := dial()
if reply := elevationRequest(t, ctx, other, gated[2]); reply.Code != protocol.ErrorElevationRequired {
t.Fatalf("second connection inherited elevation: %+v", reply)
}
if response := upload(elevated.Elevation.Token); response.StatusCode == http.StatusForbidden {
t.Fatal("upload with a live elevation token refused")
}
if response := upload("forged"); response.StatusCode != http.StatusForbidden {
t.Fatal("forged elevation token accepted")
}
conn.Close(websocket.StatusNormalClosure, "")
deadline := time.Now().Add(5 * time.Second)
for upload(elevated.Elevation.Token).StatusCode != http.StatusForbidden {
if time.Now().After(deadline) {
t.Fatal("upload token outlived its connection")
}
time.Sleep(50 * time.Millisecond)
}
}
func TestElevationGateOffWithoutWebAuthFile(t *testing.T) {
gate := newElevationGate(filepath.Join(t.TempDir(), "absent.json"), 0)
var wrote []protocol.Message
write := func(m protocol.Message) error { wrote = append(wrote, m); return nil }
if gate.refuse(protocol.Message{Type: protocol.ChatShellRun}, "a", write) || len(wrote) != 0 {
t.Fatal("gate refused without a password file")
}
gate.handle(protocol.Message{Type: protocol.Elevate, Password: "x"}, "a", write)
if len(wrote) != 1 || wrote[0].Code != protocol.ErrorElevationUnavailable {
t.Fatalf("elevate without a password file: %+v", wrote)
}
// A present but unusable file keeps the gate closed.
broken := writeTestAuthJSON(t, map[string]any{"secret": "x"})
closed := newElevationGate(broken, 0)
if !closed.refuse(protocol.Message{Type: protocol.TerminalOpen}, "a", write) {
t.Fatal("unusable password file opened the gate")
}
if ElevationTTLFromEnvironment(func(string) string { return "30" }) != 30*time.Minute ||
ElevationTTLFromEnvironment(func(string) string { return "0" }) != DefaultElevationTTL {
t.Fatal("PIPELINES_ELEVATION_MINUTES not honoured")
}
}
+148
View File
@@ -0,0 +1,148 @@
package server
import (
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
)
// The web sign-in password file (web-auth.json) is written by the installer,
// ./password and the web proxy. This server only reads it, to verify step-up
// re-authentication against the same password the operator signs in with.
//
// password_hash is "scrypt$N$r$p$<salt>$<key>" with unpadded base64url salt and
// key; a file not yet migrated by the proxy still holds a plaintext
// "password", which is compared in constant time through SHA-256 digests.
// webAuthMaxBytes bounds the file read; real files are a few hundred bytes.
const webAuthMaxBytes = 64 << 10
// DefaultWebAuthFile is where the installer keeps the web sign-in password.
func DefaultWebAuthFile() string {
if explicit := os.Getenv("PIPELINES_WEB_AUTH_FILE"); explicit != "" {
return explicit
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".config", "pipelines", "web-auth.json")
}
type webAuthVerifier struct {
hash string
password string
}
var errWebAuthMissing = errors.New("no web sign-in password file")
// readWebAuth loads the verifier from path. A missing file is
// errWebAuthMissing; anything unsafe or malformed is another error, and the
// caller then fails closed.
func readWebAuth(path string) (webAuthVerifier, error) {
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
return webAuthVerifier{}, errWebAuthMissing
}
if err != nil {
return webAuthVerifier{}, err
}
if !info.Mode().IsRegular() {
return webAuthVerifier{}, errors.New("web sign-in password file is not a regular file")
}
if info.Mode().Perm()&0o077 != 0 {
return webAuthVerifier{}, errors.New("web sign-in password file is not private (chmod 600)")
}
if !ownedByCurrentUser(info) {
return webAuthVerifier{}, errors.New("web sign-in password file belongs to another user")
}
file, err := os.Open(path)
if err != nil {
return webAuthVerifier{}, err
}
defer file.Close()
body, err := io.ReadAll(io.LimitReader(file, webAuthMaxBytes+1))
if err != nil {
return webAuthVerifier{}, err
}
if len(body) > webAuthMaxBytes {
return webAuthVerifier{}, errors.New("web sign-in password file is too large")
}
var parsed struct {
PasswordHash string `json:"password_hash"`
Password string `json:"password"`
}
if err := json.Unmarshal(body, &parsed); err != nil {
return webAuthVerifier{}, errors.New("web sign-in password file is malformed")
}
if parsed.PasswordHash != "" {
if _, err := parseScryptHash(parsed.PasswordHash); err != nil {
return webAuthVerifier{}, err
}
return webAuthVerifier{hash: parsed.PasswordHash}, nil
}
if len(parsed.Password) >= 8 {
return webAuthVerifier{password: parsed.Password}, nil
}
return webAuthVerifier{}, errors.New("web sign-in password file has no password")
}
type scryptHash struct {
n, r, p int
salt, key []byte
}
func parseScryptHash(value string) (scryptHash, error) {
invalid := errors.New("web sign-in password hash is malformed")
parts := strings.Split(value, "$")
if len(parts) != 6 || parts[0] != "scrypt" {
return scryptHash{}, invalid
}
var numbers [3]int
for i, limit := range [3]int{1 << 20, 32, 16} {
number, err := strconv.Atoi(parts[i+1])
if err != nil || number < 1 || number > limit {
return scryptHash{}, invalid
}
numbers[i] = number
}
salt, err := base64.RawURLEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 8 {
return scryptHash{}, invalid
}
key, err := base64.RawURLEncoding.DecodeString(parts[5])
if err != nil || len(key) < 16 || len(key) > 64 {
return scryptHash{}, invalid
}
if numbers[0] < 2 || numbers[0]&(numbers[0]-1) != 0 {
return scryptHash{}, invalid
}
return scryptHash{n: numbers[0], r: numbers[1], p: numbers[2], salt: salt, key: key}, nil
}
// verify reports whether candidate is the stored password, in constant time
// with respect to the candidate's content.
func (v webAuthVerifier) verify(candidate string) (bool, error) {
if v.hash == "" {
given := sha256.Sum256([]byte(candidate))
want := sha256.Sum256([]byte(v.password))
return subtle.ConstantTimeCompare(given[:], want[:]) == 1 && v.password != "", nil
}
parsed, err := parseScryptHash(v.hash)
if err != nil {
return false, err
}
derived, err := scryptKey([]byte(candidate), parsed.salt, parsed.n, parsed.r, parsed.p, len(parsed.key))
if err != nil {
return false, fmt.Errorf("verify password: %w", err)
}
return subtle.ConstantTimeCompare(derived, parsed.key) == 1, nil
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !(darwin || linux)
package server
import "os"
func ownedByCurrentUser(os.FileInfo) bool { return true }
+13
View File
@@ -0,0 +1,13 @@
//go:build darwin || linux
package server
import (
"os"
"syscall"
)
func ownedByCurrentUser(info os.FileInfo) bool {
stat, ok := info.Sys().(*syscall.Stat_t)
return ok && int(stat.Uid) == os.Getuid()
}
+112
View File
@@ -0,0 +1,112 @@
package server
import (
"crypto/pbkdf2"
"crypto/sha256"
"encoding/binary"
"errors"
"math/bits"
)
// scryptKey derives an RFC 7914 scrypt key. It is the same function Node's
// crypto.scrypt and Python's hashlib.scrypt compute, so the web proxy, the
// ./password script and this server verify one stored hash. The standard
// library has PBKDF2 but no scrypt, and this small implementation avoids a
// new module dependency.
func scryptKey(password, salt []byte, n, r, p, keyLen int) ([]byte, error) {
if n <= 1 || n&(n-1) != 0 {
return nil, errors.New("scrypt: N must be a power of two greater than 1")
}
if r <= 0 || p <= 0 || keyLen <= 0 || r*p >= 1<<30 || r > (1<<31-1)/128/p || n > (1<<31-1)/128/r {
return nil, errors.New("scrypt: parameters out of range")
}
b, err := pbkdf2.Key(sha256.New, string(password), salt, 1, p*128*r)
if err != nil {
return nil, err
}
xy := make([]uint32, 64*r)
v := make([]uint32, 32*n*r)
for i := 0; i < p; i++ {
scryptROMix(b[i*128*r:], r, n, v, xy)
}
return pbkdf2.Key(sha256.New, string(password), b, 1, keyLen)
}
func scryptROMix(b []byte, r, n int, v, xy []uint32) {
words := 32 * r
x, y := xy[:words], xy[words:]
for i := range x {
x[i] = binary.LittleEndian.Uint32(b[i*4:])
}
for i := 0; i < n; i++ {
copy(v[i*words:], x)
scryptBlockMix(x, y, r)
}
for i := 0; i < n; i++ {
j := int(x[(2*r-1)*16] & uint32(n-1))
for k := range x {
x[k] ^= v[j*words+k]
}
scryptBlockMix(x, y, r)
}
for i := range x {
binary.LittleEndian.PutUint32(b[i*4:], x[i])
}
}
// scryptBlockMix computes BlockMix_salsa20/8 of b in place, using y as scratch.
func scryptBlockMix(b, y []uint32, r int) {
var x [16]uint32
copy(x[:], b[(2*r-1)*16:])
for i := 0; i < 2*r; i++ {
for k := range x {
x[k] ^= b[i*16+k]
}
salsa208(&x)
// Even blocks go to the first half of the output, odd to the second.
copy(y[(i/2+(i%2)*r)*16:], x[:])
}
copy(b, y[:32*r])
}
func salsa208(b *[16]uint32) {
x := *b
rotl := bits.RotateLeft32
for i := 0; i < 8; i += 2 {
x[4] ^= rotl(x[0]+x[12], 7)
x[8] ^= rotl(x[4]+x[0], 9)
x[12] ^= rotl(x[8]+x[4], 13)
x[0] ^= rotl(x[12]+x[8], 18)
x[9] ^= rotl(x[5]+x[1], 7)
x[13] ^= rotl(x[9]+x[5], 9)
x[1] ^= rotl(x[13]+x[9], 13)
x[5] ^= rotl(x[1]+x[13], 18)
x[14] ^= rotl(x[10]+x[6], 7)
x[2] ^= rotl(x[14]+x[10], 9)
x[6] ^= rotl(x[2]+x[14], 13)
x[10] ^= rotl(x[6]+x[2], 18)
x[3] ^= rotl(x[15]+x[11], 7)
x[7] ^= rotl(x[3]+x[15], 9)
x[11] ^= rotl(x[7]+x[3], 13)
x[15] ^= rotl(x[11]+x[7], 18)
x[1] ^= rotl(x[0]+x[3], 7)
x[2] ^= rotl(x[1]+x[0], 9)
x[3] ^= rotl(x[2]+x[1], 13)
x[0] ^= rotl(x[3]+x[2], 18)
x[6] ^= rotl(x[5]+x[4], 7)
x[7] ^= rotl(x[6]+x[5], 9)
x[4] ^= rotl(x[7]+x[6], 13)
x[5] ^= rotl(x[4]+x[7], 18)
x[11] ^= rotl(x[10]+x[9], 7)
x[8] ^= rotl(x[11]+x[10], 9)
x[9] ^= rotl(x[8]+x[11], 13)
x[10] ^= rotl(x[9]+x[8], 18)
x[12] ^= rotl(x[15]+x[14], 7)
x[13] ^= rotl(x[12]+x[15], 9)
x[14] ^= rotl(x[13]+x[12], 13)
x[15] ^= rotl(x[14]+x[13], 18)
}
for i := range b {
b[i] += x[i]
}
}
+47
View File
@@ -0,0 +1,47 @@
package server
import (
"encoding/hex"
"testing"
)
// RFC 7914 section 12 test vectors (the 1 GiB N=1048576 vector is omitted).
func TestScryptKeyMatchesRFC7914(t *testing.T) {
cases := []struct {
password, salt string
n, r, p int
want string
}{
{"", "", 16, 1, 1, "77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906"},
{"password", "NaCl", 1024, 8, 16, "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640"},
{"pleaseletmein", "SodiumChloride", 16384, 8, 1, "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887"},
}
for _, c := range cases {
got, err := scryptKey([]byte(c.password), []byte(c.salt), c.n, c.r, c.p, 64)
if err != nil {
t.Fatal(err)
}
if hex.EncodeToString(got) != c.want {
t.Fatalf("scrypt(%q,%q,%d,%d,%d) = %x", c.password, c.salt, c.n, c.r, c.p, got)
}
}
if _, err := scryptKey([]byte("x"), nil, 1000, 8, 1, 32); err == nil {
t.Fatal("non power-of-two N accepted")
}
}
// Hashes written by web/src/authStore.js (Node) and scripts/password.py.
func TestWebAuthVerifiesNodeAndPythonHashes(t *testing.T) {
for _, hash := range []string{
"scrypt$1024$8$1$MR3k3NXe_hsd4UA6ipwLCQ$4sbSBzIXD8kVwJxwdg85f7wSvF6yzn3E0V480Z2ktG8",
"scrypt$1024$8$1$ulLLNZltxuQsW2fYURfjkw$8LptNPQf8ABG7GBih5ZH924wfqf1eDnZOhhdVIA7z2U",
} {
verifier := webAuthVerifier{hash: hash}
if ok, err := verifier.verify("tulip orbit canyon ember"); !ok || err != nil {
t.Fatalf("%s: %v %v", hash, ok, err)
}
if ok, _ := verifier.verify("tulip orbit canyon embers"); ok {
t.Fatalf("%s accepted a wrong password", hash)
}
}
}
+11 -1
View File
@@ -69,6 +69,11 @@ type Options struct {
// AccessToken, when set, is required on every request (servertoken.Header) // AccessToken, when set, is required on every request (servertoken.Header)
// except the chat-tools MCP endpoint and /healthz (request_boundary.go). // except the chat-tools MCP endpoint and /healthz (request_boundary.go).
AccessToken string AccessToken string
// WebAuthFile is the web sign-in password file step-up re-authentication
// verifies against (see elevation.go); empty disables the gate.
// ElevationTTL is how long one confirmation lasts (default 15 minutes).
WebAuthFile string
ElevationTTL time.Duration
} }
// Handler serves the persistent connection with default options. Canceling ctx // Handler serves the persistent connection with default options. Canceling ctx
@@ -182,7 +187,8 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
} }
mux.HandleFunc("GET /discovery", serveServerDiscovery) mux.HandleFunc("GET /discovery", serveServerDiscovery)
mux.HandleFunc("GET /files", serveHomeFile) mux.HandleFunc("GET /files", serveHomeFile)
mux.HandleFunc("POST /files", serveHomeFileUpload) elevation := newElevationGate(options.WebAuthFile, options.ElevationTTL)
mux.HandleFunc("POST /files", elevation.requireElevationHTTP(serveHomeFileUpload))
mux.HandleFunc("POST /chat-uploads", serveChatUpload) mux.HandleFunc("POST /chat-uploads", serveChatUpload)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
@@ -227,6 +233,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
// clientID is this connection's identity for chat session claims: a // clientID is this connection's identity for chat session claims: a
// second client is refused a session another connection holds. // second client is refused a session another connection holds.
clientID := chatClientToken() clientID := chatClientToken()
defer elevation.forget(clientID)
// Drop every run subscription this connection holds when the read loop // Drop every run subscription this connection holds when the read loop
// returns, so no subscriber, goroutine or timer outlives the connection. // returns, so no subscriber, goroutine or timer outlives the connection.
defer events.unsubscribeClient(clientID) defer events.unsubscribeClient(clientID)
@@ -277,6 +284,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "pipeline authoring is disabled on this execution server; ask the operator to publish through an explicitly enabled authoring server"}) _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "pipeline authoring is disabled on this execution server; ask the operator to publish through an explicitly enabled authoring server"})
continue continue
} }
if elevation.handle(request, clientID, write) || elevation.refuse(request, clientID, write) {
continue
}
if isChatSearch(request) { if isChatSearch(request) {
cancelChatSearch() cancelChatSearch()
searchCtx, cancel := context.WithCancel(connCtx) searchCtx, cancel := context.WithCancel(connCtx)
+4
View File
@@ -439,6 +439,10 @@ def supervise(config):
# The server requires, and the proxy and every child CLI send, the # The server requires, and the proxy and every child CLI send, the
# shared token in this file (installs from before it have none). # shared token in this file (installs from before it have none).
env.update(server_token_env(config)) env.update(server_token_env(config))
if config.get("web"):
# The server verifies step-up re-authentication against the
# web sign-in password file (read-only).
env["PIPELINES_WEB_AUTH_FILE"] = config["web"]["auth_file"]
server_command = [str(root / "bin/pipelines-server"), "-addr", server_command = [str(root / "bin/pipelines-server"), "-addr",
server_address(config), "-db", str(root / "data/pipelines.db")] server_address(config), "-db", str(root / "data/pipelines.db")]
if config.get("allow_authoring") is True: if config.get("allow_authoring") is True:
+164 -12
View File
@@ -1,15 +1,119 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Change the local Pipelines web sign-in password without restarting services.""" """Change the local Pipelines web sign-in password, or sign out every device.
The password is stored only as a scrypt hash. Every change (and --revoke-all)
rotates the cookie secret and the session generation, so each signed-in
browser and device must sign in again; open connections are closed within a
few seconds. No service restart is needed.
"""
import argparse import argparse
import base64
import fcntl import fcntl
import getpass import getpass
import hashlib
import hmac
import json import json
import os import os
from pathlib import Path from pathlib import Path
import re
import secrets
import stat import stat
import sys import sys
import tempfile import tempfile
# scrypt cost: 32 MiB and roughly a tenth of a second per check. The hash
# records its parameters, so they can be raised later without a migration.
SCRYPT_N, SCRYPT_R, SCRYPT_P, SCRYPT_KEY = 1 << 15, 8, 1, 32
SCRYPT_MAXMEM = 64 * 1024 * 1024
PASSWORD_RULE = ("Use at least 16 characters, or a passphrase of 4 or more random words "
"separated by spaces or dashes (15 characters or more in all). Common words, "
"keyboard runs and repeated characters do not count towards the length.")
# Kept in step with web/src/passwordPolicy.js.
COMMON = ("password", "passwort", "pipelines", "pipeline", "qwerty", "azerty", "letmein",
"welcome", "admin", "administrator", "iloveyou", "monkey", "dragon", "master",
"secret", "login", "changeme", "default", "football", "baseball", "sunshine",
"princess", "shadow", "trustno", "superman", "hello", "test", "guest", "root")
SEPARATORS = re.compile(r"[\s\-_.,;:+/]+")
def _runs(text):
"""Remove runs of 3+ repeated characters and 4+ consecutive characters."""
out, i = [], 0
while i < len(text):
j = i + 1
while j < len(text) and text[j] == text[i]:
j += 1
if j - i >= 3:
i = j
continue
for step in (1, -1):
j = i + 1
while j < len(text) and ord(text[j]) - ord(text[j - 1]) == step:
j += 1
if j - i >= 4:
break
else:
out.append(text[i])
i += 1
continue
i = j
return "".join(out)
def _substance(password):
"""The characters left once common words, runs and separators are removed."""
text = password.lower()
for word in sorted(COMMON, key=len, reverse=True):
text = text.replace(word, "")
for row in ("qwertyuiop", "asdfghjkl", "zxcvbnm", "1234567890"):
for size in range(len(row), 3, -1):
for start in range(len(row) - size + 1):
text = text.replace(row[start:start + size], "")
return SEPARATORS.sub("", _runs(text))
def password_problem(password):
"""Why a new password is too weak, or None. See PASSWORD_RULE."""
if len(password) > 1024:
return "Choose a password of at most 1024 characters."
words = [word.lower() for word in SEPARATORS.split(password) if word]
passphrase = (len(words) >= 4 and len(set(words)) >= 4 and all(len(word) >= 3 for word in words)
and len(password) >= 15 and len(_substance(password)) >= 12)
if passphrase:
return None
if len(password) < 16:
return "Too short. " + PASSWORD_RULE
if len(set(password)) < 8 or len(_substance(password)) < 12:
return "Too predictable. " + PASSWORD_RULE
return None
def _b64(raw):
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
def hash_password(password, *, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P):
salt = secrets.token_bytes(16)
key = hashlib.scrypt(password.encode(), salt=salt, n=n, r=r, p=p, maxmem=SCRYPT_MAXMEM, dklen=SCRYPT_KEY)
return f"scrypt${n}${r}${p}${_b64(salt)}${_b64(key)}"
def verify_password(stored, candidate):
"""Constant-time check of candidate against a stored scrypt hash."""
try:
scheme, n, r, p, salt, key = stored.split("$")
if scheme != "scrypt":
return False
pad = lambda value: base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
expected = pad(key)
derived = hashlib.scrypt(candidate.encode(), salt=pad(salt), n=int(n), r=int(r), p=int(p),
maxmem=SCRYPT_MAXMEM, dklen=len(expected))
except (ValueError, TypeError):
return False
return hmac.compare_digest(derived, expected)
def auth_path(*, prefix=None, home=None, environ=None): def auth_path(*, prefix=None, home=None, environ=None):
home = Path(home or Path.home()) home = Path(home or Path.home())
@@ -31,6 +135,17 @@ def auth_path(*, prefix=None, home=None, environ=None):
return home / ".config/pipelines/web-auth.json" return home / ".config/pipelines/web-auth.json"
def valid_auth(data):
"""Whether data is a usable web auth file: a scrypt hash (or a legacy
plaintext password the proxy has not migrated yet) and a cookie secret."""
if not isinstance(data, dict) or not isinstance(data.get("secret"), str) or len(data["secret"]) < 32:
return False
stored = data.get("password_hash")
if isinstance(stored, str):
return stored.startswith("scrypt$") and stored.count("$") == 5
return isinstance(data.get("password"), str) and len(data["password"]) >= 8
def read_auth(path): def read_auth(path):
path = Path(path) path = Path(path)
info = path.lstat() info = path.lstat()
@@ -39,21 +154,27 @@ def read_auth(path):
if info.st_mode & 0o077: if info.st_mode & 0o077:
raise ValueError(f"Password file must be private: chmod 600 '{path}'") raise ValueError(f"Password file must be private: chmod 600 '{path}'")
data = json.loads(path.read_text()) data = json.loads(path.read_text())
if not isinstance(data, dict) or not isinstance(data.get("password"), str) or len(data["password"]) < 8 or not isinstance(data.get("secret"), str) or len(data["secret"]) < 32: if not valid_auth(data):
raise ValueError("Invalid Pipelines password file; it was retained unchanged") raise ValueError("Invalid Pipelines password file; it was retained unchanged")
return data, info return data, info
def change_password(path, password): def _rotate(data):
if len(password) < 8: """Invalidate every session: a new cookie secret and session generation."""
raise ValueError("Choose a password of at least 8 characters") generation = data.get("generation")
data["generation"] = (generation if isinstance(generation, int) and generation >= 0 else 0) + 1
data["secret"] = secrets.token_urlsafe(48)
def update_auth(path, mutate):
"""Apply mutate to the auth file atomically, under a directory lock."""
path = Path(path) path = Path(path)
# Lock the directory inode, which remains stable across atomic file replaces. # Lock the directory inode, which remains stable across atomic file replaces.
directory = os.open(path.parent, os.O_RDONLY) directory = os.open(path.parent, os.O_RDONLY)
try: try:
fcntl.flock(directory, fcntl.LOCK_EX) fcntl.flock(directory, fcntl.LOCK_EX)
data, original = read_auth(path) data, original = read_auth(path)
data["password"] = password mutate(data)
descriptor, temporary = tempfile.mkstemp(prefix=".pipelines-password-", dir=path.parent) descriptor, temporary = tempfile.mkstemp(prefix=".pipelines-password-", dir=path.parent)
try: try:
with os.fdopen(descriptor, "w") as output: with os.fdopen(descriptor, "w") as output:
@@ -72,26 +193,57 @@ def change_password(path, password):
os.close(directory) os.close(directory)
def change_password(path, password):
problem = password_problem(password)
if problem:
raise ValueError(problem)
stored = hash_password(password)
def mutate(data):
data.pop("password", None)
data["password_hash"] = stored
data["password_weak"] = False
_rotate(data)
update_auth(path, mutate)
def revoke_all(path):
update_auth(path, _rotate)
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--prefix", type=Path, help="Installation prefix (or PIPELINES_PREFIX)") parser.add_argument("--prefix", type=Path, help="Installation prefix (or PIPELINES_PREFIX)")
parser.add_argument("--revoke-all", action="store_true",
help="Sign out every browser and device without changing the password")
args = parser.parse_args() args = parser.parse_args()
path = auth_path(prefix=args.prefix) path = auth_path(prefix=args.prefix)
read_auth(path) data, _ = read_auth(path)
if args.revoke_all:
revoke_all(path)
print("Every browser and device was signed out; sign in again with the same password.")
return
if not sys.stdin.isatty(): if not sys.stdin.isatty():
raise ValueError("Run ./password in an interactive terminal (SSH with a TTY is supported)") raise ValueError("Run ./password in an interactive terminal (SSH with a TTY is supported)")
if data.get("password_weak") is True:
print("Warning: the current web password is weak. " + PASSWORD_RULE, file=sys.stderr)
print(PASSWORD_RULE)
while True: while True:
password = getpass.getpass("New Pipelines password: ") password = getpass.getpass("New Pipelines password: ")
problem = password_problem(password)
if problem:
print(problem, file=sys.stderr)
continue
confirmation = getpass.getpass("Confirm new password: ") confirmation = getpass.getpass("Confirm new password: ")
if len(password) < 8: if password != confirmation:
print("Choose a password of at least 8 characters.", file=sys.stderr)
elif password != confirmation:
print("Passwords do not match. Try again.", file=sys.stderr) print("Passwords do not match. Try again.", file=sys.stderr)
else: else:
break break
change_password(path, password) change_password(path, password)
print("Web sign-in password changed. No service restart is needed.") print("Web sign-in password changed. No service restart is needed.")
print("Existing sessions remain signed in. The notification password is unchanged.") print("Every browser and device was signed out and must sign in with the new password.")
print("The notification password is unchanged.")
if __name__ == "__main__": if __name__ == "__main__":
+27 -11
View File
@@ -45,6 +45,7 @@ release_lookup = module("resolve_releases", "resolve-releases.py")
tokens = module("save_ntfy_token", "save-ntfy-token.py") tokens = module("save_ntfy_token", "save-ntfy-token.py")
app_build = module("app_build", "app_build.py") app_build = module("app_build", "app_build.py")
web_access = module("web_access", "web_access.py") web_access = module("web_access", "web_access.py")
web_password = module("pipelines_password", "password.py")
DEFAULT_PREFIX = Path.home() / ".local/share/pipelines" DEFAULT_PREFIX = Path.home() / ".local/share/pipelines"
MARKER = "pipelines-install.json" MARKER = "pipelines-install.json"
@@ -351,16 +352,17 @@ class Setup:
or Path.home() / ".config/pipelines/web-auth.json").expanduser().resolve() or Path.home() / ".config/pipelines/web-auth.json").expanduser().resolve()
if auth.exists(): if auth.exists():
data = json.loads(auth.read_text()) data = json.loads(auth.read_text())
if (not isinstance(data, dict) or not isinstance(data.get("password"), str) if not web_password.valid_auth(data):
or len(data["password"]) < 8 or not isinstance(data.get("secret"), str)
or len(data["secret"]) < 32):
raise ValueError(f"Invalid existing web auth file; retained unchanged: {auth}") raise ValueError(f"Invalid existing web auth file; retained unchanged: {auth}")
if auth.stat().st_mode & 0o077: if auth.stat().st_mode & 0o077:
raise ValueError(f"Web auth file must be private (chmod 600): {auth}") raise ValueError(f"Web auth file must be private (chmod 600): {auth}")
else: else:
password = self.choose_password() password = self.choose_password()
self.chosen_web_password = password
auth.parent.mkdir(mode=0o700, parents=True, exist_ok=True) auth.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
self._write_atomic(auth, (json.dumps({"password": password, # Only a scrypt hash is stored (see scripts/password.py).
self._write_atomic(auth, (json.dumps({"password_hash": web_password.hash_password(password),
"password_weak": False, "generation": 0,
"secret": secrets.token_urlsafe(48)}) + "\n").encode(), 0o600) "secret": secrets.token_urlsafe(48)}) + "\n").encode(), 0o600)
server_token = self.ensure_server_token(auth.parent / "server-token") server_token = self.ensure_server_token(auth.parent / "server-token")
target = prefix / "lib/web" target = prefix / "lib/web"
@@ -395,17 +397,20 @@ class Setup:
PIPELINES_WEB_PASSWORD answers it without a terminal (automation).""" PIPELINES_WEB_PASSWORD answers it without a terminal (automation)."""
given = self.environ.get("PIPELINES_WEB_PASSWORD") given = self.environ.get("PIPELINES_WEB_PASSWORD")
if given is not None: if given is not None:
if len(given) < 8: problem = web_password.password_problem(given)
raise ValueError("PIPELINES_WEB_PASSWORD must be at least 8 characters") if problem:
raise ValueError(f"PIPELINES_WEB_PASSWORD is too weak. {problem}")
return given return given
if not sys.stdin.isatty(): if not sys.stdin.isatty():
raise ValueError("Choose the web sign-in password: rerun ./install in a terminal, " raise ValueError("Choose the web sign-in password: rerun ./install in a terminal, "
"or set PIPELINES_WEB_PASSWORD (at least 8 characters)") "or set PIPELINES_WEB_PASSWORD. " + web_password.PASSWORD_RULE)
print("This computer has no web sign-in yet. Choose the password for the web app and phone.") print("This computer has no web sign-in yet. Choose the password for the web app and phone.")
print(web_password.PASSWORD_RULE)
while True: while True:
first = getpass.getpass("Web password (at least 8 characters): ") first = getpass.getpass("Web password: ")
if len(first) < 8: problem = web_password.password_problem(first)
print("Too short; use at least 8 characters.") if problem:
print(problem)
continue continue
if getpass.getpass("Repeat the password: ") != first: if getpass.getpass("Repeat the password: ") != first:
print("The passwords did not match; try again.") print("The passwords did not match; try again.")
@@ -695,6 +700,17 @@ class Setup:
process.kill() process.kill()
process.wait() process.wait()
def reader_password(self, web):
"""The phone's ntfy password, which matches the web password: the one
chosen during this install, else a not yet migrated plaintext file. A
hashed file has no plaintext; an existing ntfy account keeps its own
password and a new one is asked for on the terminal."""
chosen = getattr(self, "chosen_web_password", None)
if chosen is not None:
return chosen
legacy = json.loads(Path(web["auth_file"]).read_text()).get("password")
return legacy if isinstance(legacy, str) else None
def bootstrap_ntfy(self, prefix, config_path, reader_password=None): def bootstrap_ntfy(self, prefix, config_path, reader_password=None):
def run_ntfy(args, capture=False, interactive=False, password=None): def run_ntfy(args, capture=False, interactive=False, password=None):
return self.ntfy(prefix, config_path, list(args), capture=capture, password=password) return self.ntfy(prefix, config_path, list(args), capture=capture, password=password)
@@ -880,7 +896,7 @@ class Setup:
else: else:
self.migrate_docker(prefix, args.replace_data) self.migrate_docker(prefix, args.replace_data)
self.bootstrap_ntfy(prefix, config_path, self.bootstrap_ntfy(prefix, config_path,
reader_password=json.loads(Path(web["auth_file"]).read_text())["password"]) reader_password=self.reader_password(web))
timezone = args.timezone timezone = args.timezone
if not timezone: if not timezone:
try: try:
+80 -12
View File
@@ -12,6 +12,9 @@ password = importlib.util.module_from_spec(spec)
spec.loader.exec_module(password) spec.loader.exec_module(password)
NEW = "tulip orbit canyon ember"
class PasswordTests(unittest.TestCase): class PasswordTests(unittest.TestCase):
def setUp(self): def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="pipelines-password-test-") self.temporary = tempfile.TemporaryDirectory(prefix="pipelines-password-test-")
@@ -36,12 +39,61 @@ class PasswordTests(unittest.TestCase):
self.assertEqual(password.auth_path(home=self.home, prefix=prefix, self.assertEqual(password.auth_path(home=self.home, prefix=prefix,
environ={"PIPELINES_WEB_AUTH_FILE": str(self.auth)}), self.auth) environ={"PIPELINES_WEB_AUTH_FILE": str(self.auth)}), self.auth)
def test_change_preserves_cookie_secret_metadata_and_private_permissions(self): def test_change_stores_a_hash_rotates_sessions_and_keeps_metadata(self):
password.change_password(self.auth, "new password") password.change_password(self.auth, NEW)
result = json.loads(self.auth.read_text()) result = json.loads(self.auth.read_text())
self.assertEqual(result, dict(self.original, password="new password")) self.assertNotIn("password", result)
self.assertNotIn(NEW, self.auth.read_text())
self.assertTrue(result["password_hash"].startswith("scrypt$32768$8$1$"))
self.assertTrue(password.verify_password(result["password_hash"], NEW))
self.assertFalse(password.verify_password(result["password_hash"], "old password"))
self.assertIs(result["password_weak"], False)
self.assertNotEqual(result["secret"], self.original["secret"])
self.assertGreaterEqual(len(result["secret"]), 32)
self.assertEqual(result["generation"], 1)
self.assertEqual(result["other"], "preserve")
self.assertEqual(self.auth.stat().st_mode & 0o777, 0o600) self.assertEqual(self.auth.stat().st_mode & 0o777, 0o600)
self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), []) self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), [])
password.change_password(self.auth, "k7#Rv9!qLm2@Xz4s")
self.assertEqual(json.loads(self.auth.read_text())["generation"], 2)
def test_revoke_all_rotates_secret_and_generation_but_keeps_password(self):
password.change_password(self.auth, NEW)
before = json.loads(self.auth.read_text())
password.revoke_all(self.auth)
after = json.loads(self.auth.read_text())
self.assertEqual(after["password_hash"], before["password_hash"])
self.assertEqual(after["generation"], before["generation"] + 1)
self.assertNotEqual(after["secret"], before["secret"])
def test_revoke_all_cli_needs_no_terminal_and_prints_no_secret(self):
output = io.StringIO()
with patch.object(password.sys, "argv", ["password", "--revoke-all"]), \
patch.object(password, "auth_path", return_value=self.auth), \
patch.object(password.sys.stdin, "isatty", return_value=False), \
patch.object(password.sys, "stdout", output):
password.main()
result = json.loads(self.auth.read_text())
self.assertEqual(result["generation"], 1)
self.assertEqual(result["password"], "old password") # unchanged, still the proxy's to migrate
self.assertIn("signed out", output.getvalue())
for value in ("old password", result["secret"], self.original["secret"]):
self.assertNotIn(value, output.getvalue())
def test_strength_rule(self):
for strong in (NEW, "correct horse battery staple", "k7#Rv9!qLm2@Xz4s", "cat dog sun red"):
self.assertIsNone(password.password_problem(strong), strong)
for weak in ("short", "old password", "J8m!x2Lq0#vR9tZ", "password password password",
"a" * 20, "Password12345678!", "qwertyuiop1234567890", "password welcome admin letmein",
"dog dog dog dog dog"):
self.assertIsNotNone(password.password_problem(weak), weak)
def test_hash_matches_rfc7914_scrypt_and_rejects_garbage(self):
stored = password.hash_password("pleaseletmein", n=16384)
self.assertTrue(password.verify_password(stored, "pleaseletmein"))
self.assertFalse(password.verify_password(stored, "pleaseletmeim"))
self.assertFalse(password.verify_password("scrypt$x", "pleaseletmein"))
self.assertFalse(password.verify_password("plain$1$1$1$a$b", "pleaseletmein"))
def test_short_password_does_not_modify_auth(self): def test_short_password_does_not_modify_auth(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
@@ -52,25 +104,25 @@ class PasswordTests(unittest.TestCase):
link = self.home / "link.json" link = self.home / "link.json"
link.symlink_to(self.auth) link.symlink_to(self.auth)
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
password.change_password(link, "new password") password.change_password(link, NEW)
self.assertEqual(json.loads(self.auth.read_text()), self.original) self.assertEqual(json.loads(self.auth.read_text()), self.original)
self.assertTrue(link.is_symlink()) self.assertTrue(link.is_symlink())
def test_public_or_malformed_auth_is_not_replaced(self): def test_public_or_malformed_auth_is_not_replaced(self):
self.auth.chmod(0o644) self.auth.chmod(0o644)
with self.assertRaisesRegex(ValueError, "private"): with self.assertRaisesRegex(ValueError, "private"):
password.change_password(self.auth, "new password") password.change_password(self.auth, NEW)
self.auth.chmod(0o600) self.auth.chmod(0o600)
self.auth.write_text("{broken") self.auth.write_text("{broken")
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
password.change_password(self.auth, "new password") password.change_password(self.auth, NEW)
self.assertEqual(self.auth.read_text(), "{broken") self.assertEqual(self.auth.read_text(), "{broken")
def test_replacement_failure_preserves_original_and_cleans_staging(self): def test_replacement_failure_preserves_original_and_cleans_staging(self):
before = self.auth.read_bytes() before = self.auth.read_bytes()
with patch.object(password.os, "replace", side_effect=OSError("fixture failure")): with patch.object(password.os, "replace", side_effect=OSError("fixture failure")):
with self.assertRaises(OSError): with self.assertRaises(OSError):
password.change_password(self.auth, "new password") password.change_password(self.auth, NEW)
self.assertEqual(self.auth.read_bytes(), before) self.assertEqual(self.auth.read_bytes(), before)
self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), []) self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), [])
@@ -82,7 +134,7 @@ class PasswordTests(unittest.TestCase):
self.assertEqual(Path(source).parent, self.auth.parent) self.assertEqual(Path(source).parent, self.auth.parent)
return replace(source, target) return replace(source, target)
with patch.object(password.os, "replace", side_effect=checked_replace): with patch.object(password.os, "replace", side_effect=checked_replace):
password.change_password(self.auth, "new password") password.change_password(self.auth, NEW)
self.assertEqual(len(calls), 1) self.assertEqual(len(calls), 1)
def test_file_changed_during_update_is_not_overwritten(self): def test_file_changed_during_update_is_not_overwritten(self):
@@ -92,10 +144,24 @@ class PasswordTests(unittest.TestCase):
return replace(descriptor) return replace(descriptor)
with patch.object(password.os, "fsync", side_effect=external_update): with patch.object(password.os, "fsync", side_effect=external_update):
with self.assertRaisesRegex(ValueError, "changed during"): with self.assertRaisesRegex(ValueError, "changed during"):
password.change_password(self.auth, "new password") password.change_password(self.auth, NEW)
self.assertEqual(json.loads(self.auth.read_text())["password"], "changed elsewhere") self.assertEqual(json.loads(self.auth.read_text())["password"], "changed elsewhere")
self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), []) self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), [])
def test_cli_warns_once_about_a_weak_current_password(self):
self.auth.write_text(json.dumps(dict(self.original, password_weak=True)))
errors = io.StringIO()
with patch.object(password.sys, "argv", ["password"]), \
patch.object(password, "auth_path", return_value=self.auth), \
patch.object(password.sys.stdin, "isatty", return_value=True), \
patch.object(password.getpass, "getpass", side_effect=[NEW, NEW]), \
patch.object(password.sys, "stdout", io.StringIO()), \
patch.object(password.sys, "stderr", errors):
password.main()
self.assertEqual(errors.getvalue().count("weak"), 1)
self.assertIs(json.loads(self.auth.read_text())["password_weak"], False)
self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), [])
def test_cli_retries_mismatch_and_does_not_print_password(self): def test_cli_retries_mismatch_and_does_not_print_password(self):
output = io.StringIO() output = io.StringIO()
errors = io.StringIO() errors = io.StringIO()
@@ -103,14 +169,16 @@ class PasswordTests(unittest.TestCase):
patch.object(password, "auth_path", return_value=self.auth), \ patch.object(password, "auth_path", return_value=self.auth), \
patch.object(password.sys.stdin, "isatty", return_value=True), \ patch.object(password.sys.stdin, "isatty", return_value=True), \
patch.object(password.getpass, "getpass", side_effect=[ patch.object(password.getpass, "getpass", side_effect=[
"first password", "wrong confirmation", "new password", "new password"]), \ "tiny9", "first strong password here", "wrong confirmation", NEW, NEW]), \
patch.object(password.sys, "stdout", output), \ patch.object(password.sys, "stdout", output), \
patch.object(password.sys, "stderr", errors): patch.object(password.sys, "stderr", errors):
password.main() password.main()
self.assertEqual(json.loads(self.auth.read_text())["password"], "new password") self.assertTrue(password.verify_password(json.loads(self.auth.read_text())["password_hash"], NEW))
self.assertIn("do not match", errors.getvalue()) self.assertIn("do not match", errors.getvalue())
self.assertIn("Too short", errors.getvalue())
self.assertIn("No service restart", output.getvalue()) self.assertIn("No service restart", output.getvalue())
for value in ("first password", "wrong confirmation", "new password", "old password"): self.assertIn("signed out", output.getvalue())
for value in ("tiny9", "first strong password here", "wrong confirmation", NEW, "old password"):
self.assertNotIn(value, output.getvalue() + errors.getvalue()) self.assertNotIn(value, output.getvalue() + errors.getvalue())
def test_cli_refuses_non_tty_before_prompting(self): def test_cli_refuses_non_tty_before_prompting(self):
+10 -6
View File
@@ -140,7 +140,7 @@ class SetupNativeTests(unittest.TestCase):
return setup_native.Setup(directory, prefix=Path(directory) / "prefix", runner=recorder, return setup_native.Setup(directory, prefix=Path(directory) / "prefix", runner=recorder,
resolver=resolution, popen=fake_ntfy_serve, resolver=resolution, popen=fake_ntfy_serve,
environ={"XDG_CONFIG_HOME": str(Path(directory) / "config"), environ={"XDG_CONFIG_HOME": str(Path(directory) / "config"),
"PIPELINES_WEB_PASSWORD": "chosen-password"}) "PIPELINES_WEB_PASSWORD": "chosen tulip orbit canyon"})
@staticmethod @staticmethod
def which_all(opencode="/usr/bin/opencode", pi=None, cc="/usr/bin/cc"): def which_all(opencode="/usr/bin/opencode", pi=None, cc="/usr/bin/cc"):
@@ -247,7 +247,10 @@ class SetupNativeTests(unittest.TestCase):
installer.configure_web(prefix, setup_native.arguments([])) installer.configure_web(prefix, setup_native.arguments([]))
self.assertEqual(auth.read_bytes(), before) self.assertEqual(auth.read_bytes(), before)
self.assertEqual(auth.stat().st_mode & 0o777, 0o600) self.assertEqual(auth.stat().st_mode & 0o777, 0o600)
self.assertEqual(json.loads(before)["password"], "chosen-password") stored = json.loads(before)
self.assertNotIn("password", stored)
self.assertNotIn(b"chosen tulip", before)
self.assertTrue(setup_native.web_password.verify_password(stored["password_hash"], "chosen tulip orbit canyon"))
self.assertTrue(Path(web["script"]).is_file()) self.assertTrue(Path(web["script"]).is_file())
# The web app is built in Docker once and installed for the proxy. # The web app is built in Docker once and installed for the proxy.
self.assertTrue(installer.runner.has("docker", "run", "pipelines-app-build", "web")) self.assertTrue(installer.runner.has("docker", "run", "pipelines-app-build", "web"))
@@ -287,16 +290,17 @@ class SetupNativeTests(unittest.TestCase):
installer.configure_web(prefix, setup_native.arguments([])) installer.configure_web(prefix, setup_native.arguments([]))
installer.environ["PIPELINES_WEB_PASSWORD"] = "short" installer.environ["PIPELINES_WEB_PASSWORD"] = "short"
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()): with patch.object(setup_native.shutil, "which", side_effect=self.which_all()):
with self.assertRaisesRegex(ValueError, "at least 8"): with self.assertRaisesRegex(ValueError, "too weak"):
installer.configure_web(prefix, setup_native.arguments([])) installer.configure_web(prefix, setup_native.arguments([]))
installer.environ.pop("PIPELINES_WEB_PASSWORD") installer.environ.pop("PIPELINES_WEB_PASSWORD")
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \ with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \
patch.object(setup_native.sys.stdin, "isatty", return_value=True), \ patch.object(setup_native.sys.stdin, "isatty", return_value=True), \
patch.object(setup_native.getpass, "getpass", patch.object(setup_native.getpass, "getpass",
side_effect=["short", "typed-password", "other-password", side_effect=["short", "typed tulip orbit canyon", "other tulip orbit canyon",
"typed-password", "typed-password"]): "typed tulip orbit canyon", "typed tulip orbit canyon"]):
web = installer.configure_web(prefix, setup_native.arguments([])) web = installer.configure_web(prefix, setup_native.arguments([]))
self.assertEqual(json.loads(Path(web["auth_file"]).read_text())["password"], "typed-password") stored = json.loads(Path(web["auth_file"]).read_text())["password_hash"]
self.assertTrue(setup_native.web_password.verify_password(stored, "typed tulip orbit canyon"))
def test_fresh_install_skips_docker_migration(self): def test_fresh_install_skips_docker_migration(self):
args = setup_native.arguments(["--fresh"]) args = setup_native.arguments(["--fresh"])
+4 -1
View File
@@ -73,9 +73,12 @@ class Uninstall:
# A custom credential file must actually be a Pipelines login store. # A custom credential file must actually be a Pipelines login store.
if path.exists(): if path.exists():
data = json.loads(path.read_text()) data = json.loads(path.read_text())
if not isinstance(data, dict) or not isinstance(data.get("password"), str) or not isinstance(data.get("secret"), str): if not isinstance(data, dict) or not isinstance(data.get("password", data.get("password_hash")), str) \
or not isinstance(data.get("secret"), str):
raise ValueError("Custom web credentials are not a Pipelines password file") raise ValueError("Custom web credentials are not a Pipelines password file")
roots.add(path) roots.add(path)
# The proxy's signed-out session list beside it (web/serve.mjs).
roots.add(self.safe(path.with_name(path.name + ".sessions.json")))
return {self.safe(path) for path in roots} return {self.safe(path) for path in roots}
def preflight(self): def preflight(self):
+187 -79
View File
@@ -20,8 +20,7 @@
// //
// The default host is 127.0.0.1. Use --host 0.0.0.0 only on a trusted LAN/VPN. // The default host is 127.0.0.1. Use --host 0.0.0.0 only on a trusted LAN/VPN.
import { createServer, request } from "node:http"; import { createServer, request } from "node:http";
import { createHmac, timingSafeEqual, randomBytes } from "node:crypto"; import { createReadStream } from "node:fs";
import { createReadStream, readFileSync } from "node:fs";
import { homedir } from "node:os"; import { homedir } from "node:os";
import { readFile, stat } from "node:fs/promises"; import { readFile, stat } from "node:fs/promises";
import { extname, join, normalize, resolve, sep } from "node:path"; import { extname, join, normalize, resolve, sep } from "node:path";
@@ -29,6 +28,20 @@ import { fileURLToPath } from "node:url";
import net from "node:net"; import net from "node:net";
import { sameOriginUpgrade } from "./src/proxySecurity.js"; import { sameOriginUpgrade } from "./src/proxySecurity.js";
import { withServerToken } from "./src/serverToken.js"; import { withServerToken } from "./src/serverToken.js";
import { AuthStore, verifyPassword } from "./src/authStore.js";
import { LoginLimiter, clientKey } from "./src/loginLimiter.js";
import { PASSWORD_RULE } from "./src/passwordPolicy.js";
import { SessionSockets } from "./src/sessionSockets.js";
import {
HOST_SESSION_COOKIE,
SESSION_COOKIE,
applySecurityHeaders,
isHttps,
pageHeaders,
safeNext,
sameOriginRequest,
sessionCookieName,
} from "./src/webSecurity.js";
import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js"; import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js";
import { accessPolicy, PLAIN_LAN_REFUSAL } from "./src/listenPolicy.js"; import { accessPolicy, PLAIN_LAN_REFUSAL } from "./src/listenPolicy.js";
@@ -52,20 +65,12 @@ const UPDATES = flag(process.argv, "--updates", "") ? resolve(flag(process.argv,
const AUTH_DISABLED = process.env.PIPELINES_WEB_AUTH === "disabled"; const AUTH_DISABLED = process.env.PIPELINES_WEB_AUTH === "disabled";
const AUTH_FILE = const AUTH_FILE =
process.env.PIPELINES_WEB_AUTH_FILE ?? join(homedir(), ".config", "pipelines", "web-auth.json"); process.env.PIPELINES_WEB_AUTH_FILE ?? join(homedir(), ".config", "pipelines", "web-auth.json");
const SESSION_COOKIE = "pipelines_session"; const store = AUTH_DISABLED ? null : new AuthStore(AUTH_FILE);
function loadAuth(fatal = true) { function loadAuth(fatal = true) {
if (AUTH_DISABLED) return null; if (AUTH_DISABLED) return null;
try { try {
const parsed = JSON.parse(readFileSync(AUTH_FILE, "utf8")); return store.load();
if (
typeof parsed.password === "string" &&
parsed.password.length >= 8 &&
typeof parsed.secret === "string" &&
parsed.secret.length >= 32
) {
return { password: parsed.password, secret: parsed.secret };
}
} catch { } catch {
// Fall through to the refusal below. // Fall through to the refusal below.
} }
@@ -75,7 +80,41 @@ function loadAuth(fatal = true) {
} }
let auth = loadAuth(); let auth = loadAuth();
function refreshAuth() { auth = loadAuth(false); } // Every upgraded browser socket remembers its session token, so a sign-out,
// a password change or an expiry closes it (on the event, and on a timer).
const sockets = new SessionSockets();
function sweepSockets() {
sockets.sweep((token) => {
try {
return store.check(token) !== null;
} catch {
return false;
}
});
}
/** Reloads the credential; a new password or secret closes every socket. */
function refreshAuth() {
const previous = auth;
try {
auth = loadAuth(false);
} catch (error) {
// Fail closed: an unusable credential file ends every open connection.
sockets.sweep(() => false);
throw error;
}
if (previous && auth && (previous.secret !== auth.secret || previous.generation !== auth.generation)) sweepSockets();
}
const SWEEP_MS = Math.max(200, Number(process.env.PIPELINES_WEB_SWEEP_MS) || 5000);
if (!AUTH_DISABLED) {
setInterval(() => {
try {
refreshAuth();
sweepSockets();
} catch {}
}, SWEEP_MS).unref();
}
function cookieValue(req, name) { function cookieValue(req, name) {
for (const part of String(req.headers.cookie ?? "").split(";")) { for (const part of String(req.headers.cookie ?? "").split(";")) {
@@ -92,47 +131,44 @@ function cookieValue(req, name) {
return ""; return "";
} }
function signSession(expires) { /** The request's session token (the https cookie name first). */
const payload = `${expires}.${randomBytes(18).toString("base64url")}`; function sessionValue(req) {
return `${payload}.${createHmac("sha256", auth.secret).update(payload).digest("base64url")}`; return cookieValue(req, HOST_SESSION_COOKIE) || cookieValue(req, SESSION_COOKIE);
} }
const SESSION_LONG_SECONDS = 30 * 24 * 60 * 60; const SESSION_LONG_SECONDS = 30 * 24 * 60 * 60;
const SESSION_SHORT_SECONDS = 12 * 60 * 60; const SESSION_SHORT_SECONDS = 12 * 60 * 60;
function sessionToken(remember = false) { /** The request's live session, or null. */
const ttl = remember ? SESSION_LONG_SECONDS : SESSION_SHORT_SECONDS; function session(req) {
return signSession(Math.floor(Date.now() / 1000) + ttl); if (!auth) return null;
}
function validSession(value) {
if (!auth || typeof value !== "string") return false;
const parts = value.split(".");
if (parts.length !== 2 && parts.length !== 3) return false;
const expires = parts[0], signature = parts.at(-1);
if (!/^\d+$/.test(expires) || !signature) return false;
const expected = createHmac("sha256", auth.secret).update(parts.slice(0, -1).join(".")).digest();
let given;
try { try {
given = Buffer.from(signature, "base64url"); return store.check(sessionValue(req));
} catch { } catch {
return false; return null;
} }
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return false;
return Number(expires) > Math.floor(Date.now() / 1000);
} }
function isAuthed(req) { function isAuthed(req) {
return !auth || validSession(cookieValue(req, SESSION_COOKIE)); return !auth || session(req) !== null;
} }
const peerRelay = new PeerRelay((req) => AUTH_DISABLED ? "test-auth-disabled" : cookieValue(req, SESSION_COOKIE)); const peerRelay = new PeerRelay((req) => AUTH_DISABLED ? "test-auth-disabled" : sessionValue(req));
function passwordOk(candidate) { // Password checks are scrypt (32 MiB each); a few run at once and the rest
// are answered 429 rather than queued without bound.
const VERIFY_LIMIT = 4;
let verifying = 0;
async function passwordOk(candidate) {
if (!auth) return true; if (!auth) return true;
const given = Buffer.from(String(candidate ?? "")); const value = String(candidate ?? "");
const expected = Buffer.from(auth.password); if (value.length > 4096) return false;
return given.length === expected.length && timingSafeEqual(given, expected); verifying++;
try {
return await verifyPassword(auth.hash, value);
} finally {
verifying--;
}
} }
function sessionCookie(req, remember = false) { function sessionCookie(req, remember = false) {
@@ -140,40 +176,65 @@ function sessionCookie(req, remember = false) {
// a top-level navigation, and a Strict cookie is withheld on that first // a top-level navigation, and a Strict cookie is withheld on that first
// request, which made a remembered session look forgotten. Lax still keeps // request, which made a remembered session look forgotten. Lax still keeps
// the cookie off cross-site subresource and POST requests. // the cookie off cross-site subresource and POST requests.
const bits = [`${SESSION_COOKIE}=${sessionToken(remember)}`, "Path=/", "HttpOnly", "SameSite=Lax"]; const { token } = store.issue(remember ? SESSION_LONG_SECONDS : SESSION_SHORT_SECONDS);
const bits = [`${sessionCookieName(req)}=${token}`, "Path=/", "HttpOnly", "SameSite=Lax"];
// Remember me persists the cookie; otherwise it is a browser-session cookie // Remember me persists the cookie; otherwise it is a browser-session cookie
// (and the signed token itself expires after 12 hours). // (and the signed token itself expires after 12 hours).
if (remember) { if (remember) {
const expires = new Date(Date.now() + SESSION_LONG_SECONDS * 1000).toUTCString(); const expires = new Date(Date.now() + SESSION_LONG_SECONDS * 1000).toUTCString();
bits.push(`Max-Age=${SESSION_LONG_SECONDS}`, `Expires=${expires}`); bits.push(`Max-Age=${SESSION_LONG_SECONDS}`, `Expires=${expires}`);
} }
// Tailscale terminates TLS and usually forwards the scheme; when it does, the // Tailscale terminates TLS and forwards the scheme; then the cookie is
// cookie is Secure. A direct plain-http LAN visit still works without it. // Secure and host-locked (__Host-). A plain-http LAN visit keeps the plain name.
const forwarded = String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim(); if (isHttps(req)) bits.push("Secure");
if (forwarded === "https") bits.push("Secure");
return bits.join("; "); return bits.join("; ");
} }
/** Small per-address brake on password guessing. */ /** Set-Cookie values that clear both session cookie names. */
const loginFailures = new Map(); function clearedCookies(req) {
function loginBlocked(address) { const cleared = [`${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`];
const entry = loginFailures.get(address); if (isHttps(req)) cleared.push(`${HOST_SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Secure; Max-Age=0`);
return Boolean(entry && entry.until > Date.now()); return cleared;
}
function noteLoginFailure(address) {
const now = Date.now();
const entry = loginFailures.get(address) ?? { count: 0, until: 0 };
entry.count += 1;
if (entry.count >= 8) {
entry.count = 0;
entry.until = now + 30_000;
}
loginFailures.set(address, entry);
} }
function safeNext(value) { /** Ends one session: server-side revocation, its relayed peers and sockets. */
const next = String(value ?? ""); function signOut(req) {
return next.startsWith("/") && !next.startsWith("//") ? next : "/"; const token = sessionValue(req);
peerRelay.forget(req);
try {
store.revoke(token);
} catch {}
sweepSockets();
}
const limiter = new LoginLimiter();
function logoutPage() {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex" />
<title>Pipelines · sign out</title>
<style>
:root { color-scheme: dark; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center;
background: #101013; color: #e8e8ea; font: 14px/1.5 ui-sans-serif, -apple-system, "Segoe UI", sans-serif; }
main { width: min(360px, calc(100vw - 32px)); padding: 24px; background: #17171b;
border: 1px solid #2a2a31; border-radius: 16px; }
button { width: 100%; margin-top: 14px; padding: 11px 12px; border: 0; border-radius: 9px;
background: #8fa8c8; color: #101013; font: inherit; font-weight: 650; cursor: pointer; }
</style>
</head>
<body>
<main>
<h1>Sign out</h1>
<p>Sign this browser out of Pipelines.</p>
<form method="post" action="/logout"><button type="submit">Sign out</button></form>
</main>
</body>
</html>`;
} }
function loginPage({ next = "/", error = "" } = {}) { function loginPage({ next = "/", error = "" } = {}) {
@@ -218,7 +279,7 @@ function loginPage({ next = "/", error = "" } = {}) {
<h1>Pipelines</h1> <h1>Pipelines</h1>
<p>Sign in to reach this server.</p> <p>Sign in to reach this server.</p>
<form method="post" action="/login"> <form method="post" action="/login">
<input type="hidden" name="next" value="${next.replace(/"/g, "&quot;")}" /> <input type="hidden" name="next" value="${next.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;")}" />
<label for="password">Password</label> <label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" autofocus required /> <input id="password" name="password" type="password" autocomplete="current-password" autofocus required />
<label class="remember"><input type="checkbox" name="remember" checked /> Remember me on this device</label> <label class="remember"><input type="checkbox" name="remember" checked /> Remember me on this device</label>
@@ -406,6 +467,7 @@ function proxyArtifact(req, res) {
} }
const server = createServer(async (req, res) => { const server = createServer(async (req, res) => {
applySecurityHeaders(req, res);
try { refreshAuth(); } catch { try { refreshAuth(); } catch {
res.writeHead(503, { "Content-Type": "text/plain", "Cache-Control": "no-store" }).end("Web authentication unavailable"); res.writeHead(503, { "Content-Type": "text/plain", "Cache-Control": "no-store" }).end("Web authentication unavailable");
return; return;
@@ -428,6 +490,10 @@ const server = createServer(async (req, res) => {
res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" }).end(PLAIN_LAN_REFUSAL); res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" }).end(PLAIN_LAN_REFUSAL);
return; return;
} }
if (!auth && (pathname === "/api/session" || pathname === "/api/sessions/revoke-all")) {
res.writeHead(404, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end('{"error":"sign-in is disabled"}');
return;
}
if (auth) { if (auth) {
if (pathname === "/login" && req.method === "GET") { if (pathname === "/login" && req.method === "GET") {
if (isAuthed(req)) { if (isAuthed(req)) {
@@ -435,36 +501,54 @@ const server = createServer(async (req, res) => {
return; return;
} }
const next = new URL(req.url ?? "/login", "http://localhost").searchParams.get("next") ?? "/"; const next = new URL(req.url ?? "/login", "http://localhost").searchParams.get("next") ?? "/";
res res.writeHead(200, pageHeaders()).end(loginPage({ next: safeNext(next) }));
.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" })
.end(loginPage({ next: safeNext(next) }));
return; return;
} else if (pathname === "/login" && req.method === "POST") { } else if (pathname === "/login" && req.method === "POST") {
const body = await readRequestBody(req).catch(() => ""); // Login CSRF: a cross-site form must not sign the browser in to this server.
const fields = new URLSearchParams(body); if (!sameOriginRequest(req)) {
const address = req.socket.remoteAddress ?? ""; req.resume();
if (loginBlocked(address)) { res.writeHead(403, pageHeaders()).end(loginPage({ error: "Sign-in refused: the form came from another site." }));
res
.writeHead(429, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" })
.end(loginPage({ error: "Too many attempts. Wait 30 seconds." }));
return; return;
} }
if (!passwordOk(fields.get("password"))) { const body = await readRequestBody(req).catch(() => "");
noteLoginFailure(address); const fields = new URLSearchParams(body);
const key = clientKey(req);
const wait = limiter.blocked(key);
if (wait > 0 || verifying >= VERIFY_LIMIT) {
const seconds = Math.max(1, Math.ceil(wait / 1000));
res res
.writeHead(401, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }) .writeHead(429, pageHeaders({ "Retry-After": String(seconds) }))
.end(loginPage({ next: safeNext(fields.get("next")), error: `Too many attempts. Wait ${seconds} seconds.` }));
return;
}
if (!(await passwordOk(fields.get("password")))) {
limiter.fail(key);
res
.writeHead(401, pageHeaders())
.end(loginPage({ next: safeNext(fields.get("next")), error: "Wrong password." })); .end(loginPage({ next: safeNext(fields.get("next")), error: "Wrong password." }));
return; return;
} }
limiter.succeed(key);
const remember = fields.get("remember") === "on"; const remember = fields.get("remember") === "on";
res.setHeader("Set-Cookie", sessionCookie(req, remember)); res.setHeader("Set-Cookie", sessionCookie(req, remember));
res.writeHead(303, { Location: safeNext(fields.get("next")) }).end(); res.writeHead(303, { Location: safeNext(fields.get("next")) }).end();
return; return;
} else if (pathname === "/logout") { } else if (pathname === "/logout" && req.method === "POST") {
peerRelay.forget(req); // Signing out is state-changing: POST from this origin only.
res.setHeader("Set-Cookie", `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`); if (!sameOriginRequest(req)) {
req.resume();
res.writeHead(403, pageHeaders()).end(logoutPage());
return;
}
req.resume();
signOut(req);
res.setHeader("Set-Cookie", clearedCookies(req));
res.writeHead(303, { Location: "/login" }).end(); res.writeHead(303, { Location: "/login" }).end();
return; return;
} else if (pathname === "/logout") {
// A link (or a cross-site page) only reaches a confirmation button.
res.writeHead(200, pageHeaders()).end(logoutPage());
return;
} else if (!isAuthed(req)) { } else if (!isAuthed(req)) {
const wantsHtml = String(req.headers.accept ?? "").includes("text/html"); const wantsHtml = String(req.headers.accept ?? "").includes("text/html");
if (req.method === "GET" && wantsHtml && !pathname.startsWith("/api/") && !pathname.startsWith("/peers/")) { if (req.method === "GET" && wantsHtml && !pathname.startsWith("/api/") && !pathname.startsWith("/peers/")) {
@@ -475,6 +559,28 @@ const server = createServer(async (req, res) => {
.writeHead(401, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" }) .writeHead(401, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" })
.end("Sign in required\n"); .end("Sign in required\n");
return; return;
} else if (pathname === "/api/session" && req.method === "GET") {
const current = session(req);
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end(
JSON.stringify({
weak_password: auth.weak === true,
password_rule: PASSWORD_RULE,
expires_at: new Date(current.expires * 1000).toISOString(),
}),
);
return;
} else if (pathname === "/api/sessions/revoke-all" && req.method === "POST") {
req.resume();
if (!sameOriginRequest(req)) {
res.writeHead(403, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end('{"error":"cross-site request refused"}');
return;
}
peerRelay.forget(req);
store.revokeAll();
sweepSockets();
res.setHeader("Set-Cookie", clearedCookies(req));
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end('{"revoked":true}');
return;
} }
} }
if (pathname === "/api/discovery" && req.method === "GET") { if (pathname === "/api/discovery" && req.method === "GET") {
@@ -598,6 +704,8 @@ server.on("upgrade", (req, clientSocket, clientHead) => {
clientSocket.destroy(); clientSocket.destroy();
return; return;
} }
// Closed again when this session is signed out, revoked or expires.
if (auth) sockets.track(clientSocket, sessionValue(req));
if (peerRelay.upgrade(req, clientSocket, clientHead)) return; if (peerRelay.upgrade(req, clientSocket, clientHead)) return;
if (pathname !== "/connect") { if (pathname !== "/connect") {
clientSocket.destroy(); clientSocket.destroy();
+233
View File
@@ -0,0 +1,233 @@
// The web sign-in credential and its sessions.
//
// web-auth.json (0600, outside the repository) holds:
// password_hash "scrypt$N$r$p$<salt>$<key>" (unpadded base64url); the same
// hash scripts/password.py writes and the Go server verifies
// for step-up re-authentication
// password_weak true when the stored password predates the strength rule
// secret the cookie HMAC key
// generation bumped (with a new secret) by every password change and by
// `./password --revoke-all`
// A file still holding a plaintext "password" is migrated to a hash the first
// time it is loaded; the password itself does not change.
//
// Sessions are signed tokens "v2.<generation>.<issued ms>.<expires s>.<id>.<mac>".
// <auth file>.sessions.json (0600, written only by this proxy) records signed
// out token ids until they expire and a "not_before" time for "sign out
// everywhere" from Settings.
import { createHmac, randomBytes, scrypt, scryptSync, timingSafeEqual } from "node:crypto";
import { closeSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import { passwordProblem } from "./passwordPolicy.js";
export const SCRYPT = { N: 1 << 15, r: 8, p: 1, keyLength: 32 };
const MAXMEM = 64 * 1024 * 1024;
/** Signed-out token ids kept until they expire; the soonest to expire go first. */
export const REVOKED_LIMIT = 10000;
const b64 = (buffer) => Buffer.from(buffer).toString("base64url");
export function hashPassword(password, { N, r, p, keyLength } = SCRYPT) {
const salt = randomBytes(16);
const key = scryptSync(String(password), salt, keyLength, { N, r, p, maxmem: MAXMEM });
return `scrypt$${N}$${r}$${p}$${b64(salt)}$${b64(key)}`;
}
export function parseHash(value) {
const parts = String(value ?? "").split("$");
if (parts.length !== 6 || parts[0] !== "scrypt") return null;
const [N, r, p] = parts.slice(1, 4).map((part) => (/^\d{1,7}$/.test(part) ? Number(part) : 0));
const salt = Buffer.from(parts[4], "base64url");
const key = Buffer.from(parts[5], "base64url");
if (N < 2 || N > 1 << 20 || (N & (N - 1)) !== 0 || r < 1 || r > 32 || p < 1 || p > 16) return null;
if (salt.length < 8 || key.length < 16 || key.length > 64) return null;
return { N, r, p, salt, key };
}
/** Constant-time check of candidate against a stored hash. */
export function verifyPassword(stored, candidate) {
const parsed = parseHash(stored);
if (!parsed) return Promise.resolve(false);
const { N, r, p, salt, key } = parsed;
return new Promise((done) => {
scrypt(String(candidate ?? ""), salt, key.length, { N, r, p, maxmem: MAXMEM }, (error, derived) => {
done(!error && derived.length === key.length && timingSafeEqual(derived, key));
});
});
}
/** Writes data to path through a private temporary file and a rename. */
function writePrivateAtomic(path, text, unchanged) {
const temporary = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}`);
const fd = openSync(temporary, "wx", 0o600);
try {
writeSync(fd, text);
fsyncSync(fd);
} finally {
closeSync(fd);
}
try {
if (unchanged && !unchanged()) throw new Error("file changed during the update");
renameSync(temporary, path);
} catch (error) {
try {
unlinkSync(temporary);
} catch {}
throw error;
}
}
const signature = (info) => `${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
export class AuthStore {
constructor(file, { now = Date.now, log = (line) => console.error(line) } = {}) {
this.file = file;
this.sessionsFile = `${file}.sessions.json`;
this.now = now;
this.log = log;
this.state = null;
this.stamp = "";
this.notBefore = 0;
this.revoked = new Map(); // id -> expires (seconds)
this.revokedGeneration = null;
this.loadSessions();
}
/** The current credential; throws when the file is missing or invalid. */
load() {
const info = lstatSync(this.file);
if (!info.isFile()) throw new Error("web auth file is not a regular file");
if (this.state && signature(info) === this.stamp) return this.state;
const parsed = JSON.parse(readFileSync(this.file, "utf8"));
if (!parsed || typeof parsed !== "object" || typeof parsed.secret !== "string" || parsed.secret.length < 32)
throw new Error("web auth file has no valid secret");
let hash = parsed.password_hash;
let weak = parsed.password_weak === true;
if (typeof hash !== "string" && typeof parsed.password === "string" && parsed.password.length >= 8) {
({ hash, weak } = this.migrate(parsed, info));
}
if (!parseHash(hash)) throw new Error("web auth file has no valid password hash");
const generation = Number.isSafeInteger(parsed.generation) && parsed.generation >= 0 ? parsed.generation : 0;
this.state = { hash, weak, secret: parsed.secret, generation };
// Re-stat: a successful migration replaced the file.
try {
this.stamp = signature(lstatSync(this.file));
} catch {
this.stamp = "";
}
if (this.revokedGeneration !== generation) {
// A new generation already invalidates every older token.
this.revoked.clear();
this.notBefore = 0;
this.revokedGeneration = generation;
}
return this.state;
}
/** Replaces a plaintext password by its hash, keeping the password itself. */
migrate(parsed, info) {
const hash = hashPassword(parsed.password);
const weak = passwordProblem(parsed.password) !== null;
const next = { ...parsed, password_hash: hash, password_weak: weak };
delete next.password;
if (this.state) {
// A plaintext password written over a running proxy's file is a password
// change: like ./password, it signs every session out.
const generation = Number.isSafeInteger(parsed.generation) && parsed.generation >= 0 ? parsed.generation : 0;
next.generation = generation + 1;
next.secret = randomBytes(48).toString("base64url");
parsed.generation = next.generation;
parsed.secret = next.secret;
}
try {
writePrivateAtomic(this.file, `${JSON.stringify(next, null, 2)}\n`, () => {
const current = lstatSync(this.file);
return signature(current) === signature(info);
});
this.log(`web auth: stored the sign-in password as a scrypt hash${weak ? "; it is weak, choose a stronger one with ./password" : ""}`);
} catch (error) {
// Signing in keeps working from the in-memory hash until the file changes.
this.log(`web auth: could not migrate the password file to a hash (${error.message})`);
}
return { hash, weak };
}
loadSessions() {
try {
const parsed = JSON.parse(readFileSync(this.sessionsFile, "utf8"));
this.revokedGeneration = Number.isSafeInteger(parsed.generation) ? parsed.generation : null;
this.notBefore = Number.isFinite(parsed.not_before) ? parsed.not_before : 0;
for (const [id, expires] of Object.entries(parsed.revoked ?? {}))
if (/^[A-Za-z0-9_-]{8,64}$/.test(id) && Number.isFinite(expires)) this.revoked.set(id, expires);
} catch {
// No list yet (or unreadable): nothing has been signed out.
}
}
saveSessions() {
const nowSeconds = Math.floor(this.now() / 1000);
for (const [id, expires] of this.revoked) if (expires <= nowSeconds) this.revoked.delete(id);
if (this.revoked.size > REVOKED_LIMIT) {
const sorted = [...this.revoked].sort((a, b) => a[1] - b[1]);
this.revoked = new Map(sorted.slice(sorted.length - REVOKED_LIMIT));
}
const body = {
generation: this.revokedGeneration,
not_before: this.notBefore,
revoked: Object.fromEntries(this.revoked),
};
try {
writePrivateAtomic(this.sessionsFile, `${JSON.stringify(body)}\n`);
} catch (error) {
// The revocation still holds in memory until the proxy restarts.
this.log(`web auth: could not record signed-out sessions (${error.message})`);
}
}
mac(payload) {
return createHmac("sha256", this.load().secret).update(payload).digest();
}
/** A new signed session token valid for ttlSeconds. */
issue(ttlSeconds) {
const { generation } = this.load();
const now = this.now();
const expires = Math.floor(now / 1000) + ttlSeconds;
const payload = `v2.${generation}.${now}.${expires}.${randomBytes(18).toString("base64url")}`;
return { token: `${payload}.${b64(this.mac(payload))}`, expires };
}
/** The session a token names, or null when it is forged, old or revoked. */
check(token) {
if (typeof token !== "string" || token.length > 256) return null;
const parts = token.split(".");
if (parts.length !== 6 || parts[0] !== "v2") return null;
const [, generation, issued, expires, id, mac] = parts;
if (![generation, issued, expires].every((part) => /^\d{1,16}$/.test(part))) return null;
const state = this.load();
const expected = this.mac(parts.slice(0, 5).join("."));
const given = Buffer.from(mac, "base64url");
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
if (Number(generation) !== state.generation) return null;
if (Number(expires) <= Math.floor(this.now() / 1000)) return null;
if (Number(issued) <= this.notBefore || this.revoked.has(id)) return null;
return { id, expires: Number(expires), issued: Number(issued) };
}
/** Signs one token out (server-side logout). */
revoke(token) {
const session = this.check(token);
if (!session) return false;
this.revoked.set(session.id, session.expires);
this.saveSessions();
return true;
}
/** Signs every token issued so far out ("Sign out everywhere"). */
revokeAll() {
this.load();
this.notBefore = Math.max(this.now(), this.notBefore + 1);
this.revoked.clear();
this.saveSessions();
}
}
+79
View File
@@ -0,0 +1,79 @@
// A brake on password guessing: per client exponential backoff after a few
// free failures, plus a server-wide sliding window so many clients (or one
// client behind many addresses) cannot keep guessing. The per-client map is
// bounded; the least recently failed client is evicted first.
export class LoginLimiter {
constructor({
now = Date.now,
freeFailures = 5,
baseMs = 1000,
maxMs = 15 * 60 * 1000,
idleMs = 60 * 60 * 1000,
maxKeys = 1024,
globalLimit = 50,
globalWindowMs = 5 * 60 * 1000,
} = {}) {
Object.assign(this, { now, freeFailures, baseMs, maxMs, idleMs, maxKeys, globalLimit, globalWindowMs });
this.clients = new Map(); // key -> { count, until, last }; insertion order = recency
this.recent = []; // failure times, oldest first, at most globalLimit
}
prune(now) {
while (this.recent.length && this.recent[0] <= now - this.globalWindowMs) this.recent.shift();
}
/** Milliseconds key must wait before its next attempt (0: go ahead). */
blocked(key) {
const now = this.now();
this.prune(now);
let wait = 0;
if (this.recent.length >= this.globalLimit) wait = this.recent[0] + this.globalWindowMs - now;
const entry = this.clients.get(key);
if (entry && now - entry.last > this.idleMs) this.clients.delete(key);
else if (entry && entry.until > now) wait = Math.max(wait, entry.until - now);
return Math.max(0, wait);
}
fail(key) {
const now = this.now();
this.prune(now);
this.recent.push(now);
if (this.recent.length > this.globalLimit) this.recent.shift();
const entry = this.clients.get(key) ?? { count: 0, until: 0, last: now };
this.clients.delete(key);
entry.count += 1;
entry.last = now;
if (entry.count >= this.freeFailures) {
const doublings = Math.min(entry.count - this.freeFailures, 20);
entry.until = now + Math.min(this.baseMs * 2 ** doublings, this.maxMs);
}
this.clients.set(key, entry);
while (this.clients.size > this.maxKeys) this.clients.delete(this.clients.keys().next().value);
}
succeed(key) {
this.clients.delete(key);
}
}
const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
/**
* The client a login attempt is charged to. Behind `tailscale serve` every
* request arrives from loopback, so there (and only there: a loopback peer
* that carries Tailscale's identity headers) the tailnet user, else the
* forwarded address, names the client. Any other request is its socket
* address. A local process could forge these headers, but it already runs on
* the machine; the global window still bounds it.
*/
export function clientKey(req) {
const address = req.socket?.remoteAddress ?? "";
if (LOOPBACK.has(address) && Object.keys(req.headers).some((name) => name.startsWith("tailscale-"))) {
const login = String(req.headers["tailscale-user-login"] ?? "").trim().toLowerCase();
if (login) return `tailscale:${login.slice(0, 256)}`;
const forwarded = String(req.headers["x-forwarded-for"] ?? "").split(",")[0].trim();
if (forwarded) return `forwarded:${forwarded.slice(0, 64)}`;
}
return `address:${address}`;
}
+76
View File
@@ -0,0 +1,76 @@
// The strength rule for a new web password, kept in step with
// scripts/password.py (which enforces it). The proxy only uses it to mark a
// migrated plaintext password as weak, so Settings can warn about it once.
export const PASSWORD_RULE =
"Use at least 16 characters, or a passphrase of 4 or more random words " +
"separated by spaces or dashes (15 characters or more in all). Common words, " +
"keyboard runs and repeated characters do not count towards the length.";
const COMMON = [
"password", "passwort", "pipelines", "pipeline", "qwerty", "azerty", "letmein",
"welcome", "admin", "administrator", "iloveyou", "monkey", "dragon", "master",
"secret", "login", "changeme", "default", "football", "baseball", "sunshine",
"princess", "shadow", "trustno", "superman", "hello", "test", "guest", "root",
].sort((a, b) => b.length - a.length);
const ROWS = ["qwertyuiop", "asdfghjkl", "zxcvbnm", "1234567890"];
const SEPARATORS = /[\s\-_.,;:+/]+/g;
/** Removes runs of 3+ repeated characters and 4+ consecutive characters. */
function withoutRuns(text) {
const chars = [...text];
const out = [];
let i = 0;
while (i < chars.length) {
let j = i + 1;
while (j < chars.length && chars[j] === chars[i]) j++;
if (j - i >= 3) {
i = j;
continue;
}
let run = 0;
for (const step of [1, -1]) {
j = i + 1;
while (j < chars.length && chars[j].codePointAt(0) - chars[j - 1].codePointAt(0) === step) j++;
if (j - i >= 4) {
run = j;
break;
}
}
if (run) {
i = run;
continue;
}
out.push(chars[i]);
i++;
}
return out.join("");
}
function substance(password) {
let text = password.toLowerCase();
for (const word of COMMON) text = text.split(word).join("");
for (const row of ROWS)
for (let size = row.length; size > 3; size--)
for (let start = 0; start + size <= row.length; start++)
text = text.split(row.slice(start, start + size)).join("");
return withoutRuns(text).replace(SEPARATORS, "");
}
/** Why a new password is too weak, or null. Lengths count code points. */
export function passwordProblem(password) {
const value = String(password ?? "");
const length = [...value].length;
if (length > 1024) return "Choose a password of at most 1024 characters.";
const words = value.split(SEPARATORS).filter(Boolean).map((word) => word.toLowerCase());
const passphrase =
words.length >= 4 &&
new Set(words).size >= 4 &&
words.every((word) => [...word].length >= 3) &&
length >= 15 &&
[...substance(value)].length >= 12;
if (passphrase) return null;
if (length < 16) return `Too short. ${PASSWORD_RULE}`;
if (new Set(value).size < 8 || [...substance(value)].length < 12) return `Too predictable. ${PASSWORD_RULE}`;
return null;
}
+2
View File
@@ -80,6 +80,8 @@ export class PeerRelay extends PeerRegistry {
"x-upload-name", "x-upload-name",
"x-chat-file-name", "x-chat-file-name",
"x-pipelines-upload-name", "x-pipelines-upload-name",
// The remote machine's own step-up token (POST /files).
"x-pipelines-elevation",
]) ])
if (req.headers[name]) headers[name] = req.headers[name]; if (req.headers[name]) headers[name] = req.headers[name];
const upstream = remoteRequest(target.url, { const upstream = remoteRequest(target.url, {
+1 -1
View File
@@ -77,7 +77,7 @@ export function boundedRequest(
export function sessionCookie(response) { export function sessionCookie(response) {
return (response.headers["set-cookie"] ?? []) return (response.headers["set-cookie"] ?? [])
.map((value) => value.split(";")[0]) .map((value) => value.split(";")[0])
.filter((value) => value.startsWith("pipelines_session=")) .filter((value) => value.startsWith("pipelines_session=") || value.startsWith("__Host-pipelines_session="))
.join("; "); .join("; ");
} }
+30
View File
@@ -0,0 +1,30 @@
// The upgraded browser sockets (the /connect websocket and relayed peer
// sockets), each with the session token it was opened with. A sweep destroys
// every socket whose session is no longer valid: signed out, signed out
// everywhere, expired, or issued before a password change.
export class SessionSockets {
constructor() {
this.sockets = new Map(); // socket -> token
}
track(socket, token) {
this.sockets.set(socket, token);
socket.once("close", () => this.sockets.delete(socket));
}
get size() {
return this.sockets.size;
}
/** Destroys the sockets whose token valid() rejects; returns how many. */
sweep(valid) {
let closed = 0;
for (const [socket, token] of this.sockets) {
if (valid(token)) continue;
this.sockets.delete(socket);
socket.destroy();
closed++;
}
return closed;
}
}
+72
View File
@@ -0,0 +1,72 @@
// Browser-facing hygiene for the proxy: request origin checks, the post-login
// redirect target, the session cookie's name and the security headers.
import { sameOriginUpgrade } from "./proxySecurity.js";
export const SESSION_COOKIE = "pipelines_session";
/** Over https the cookie is host-locked (Secure, Path=/, no Domain). */
export const HOST_SESSION_COOKIE = "__Host-pipelines_session";
/** Whether the browser reached the proxy over https (Tailscale serve). */
export function isHttps(req) {
const forwarded = String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim().toLowerCase();
return forwarded === "https" || Boolean(req.socket?.encrypted);
}
export function sessionCookieName(req) {
return isHttps(req) ? HOST_SESSION_COOKIE : SESSION_COOKIE;
}
/**
* Whether a state-changing request comes from this origin. Browsers send
* Origin on every POST; a native client (the app, curl, a peer proxy) sends
* none and has no ambient cookies to abuse. `Origin: null` and a cross-site
* Sec-Fetch-Site are refused.
*/
export function sameOriginRequest(req) {
const origin = req.headers.origin;
const site = req.headers["sec-fetch-site"];
if (site && !["same-origin", "none"].includes(String(site))) return false;
if (origin === undefined) return true;
return sameOriginUpgrade(origin, req.headers.host);
}
/**
* The local path to return to after signing in: one "/" followed by anything
* but "/" or "\" (which browsers treat as another host), no backslashes or
* control characters anywhere, else "/".
*/
export function safeNext(value) {
const next = String(value ?? "");
if (next.length > 2048 || !/^\/(?![/\\])/.test(next) || /[\\\u0000-\u001f\u007f]/.test(next)) return "/";
return next;
}
/** The proxy's own pages (sign-in, sign-out) are never framed and run no script. */
export const PAGE_POLICY =
"default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; form-action 'self'; " +
"frame-ancestors 'none'; base-uri 'none'";
/**
* Headers every response starts with. The app frames only its own documents
* (sandboxed srcdoc HTML previews), so same-origin framing stays allowed; a
* response that sets its own value (for example a sandboxing CSP) overrides
* these at writeHead. HSTS only on https.
*/
export function applySecurityHeaders(req, res) {
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "same-origin");
res.setHeader("X-Frame-Options", "SAMEORIGIN");
res.setHeader("Content-Security-Policy", "frame-ancestors 'self'");
if (isHttps(req)) res.setHeader("Strict-Transport-Security", "max-age=31536000");
}
/** Marks a response as one of the proxy's own pages. */
export function pageHeaders(extra = {}) {
return {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-store",
"Content-Security-Policy": PAGE_POLICY,
"X-Frame-Options": "DENY",
...extra,
};
}
+183
View File
@@ -0,0 +1,183 @@
import test from "node:test";
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import net from "node:net";
import { once } from "node:events";
import { hashPassword } from "../src/authStore.js";
const here = fileURLToPath(new URL("..", import.meta.url));
const PASSWORD = "tulip orbit canyon ember";
async function freePort() {
const server = net.createServer().listen(0, "127.0.0.1");
await once(server, "listening");
const { port } = server.address();
await new Promise((done) => server.close(done));
return port;
}
/** A stand-in Pipelines server that accepts every websocket upgrade and holds it. */
async function fakeUpstream(t) {
const held = new Set();
const server = net.createServer((socket) => {
held.add(socket);
socket.once("data", () => socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"));
socket.on("error", () => {});
socket.on("close", () => held.delete(socket));
}).listen(0, "127.0.0.1");
await once(server, "listening");
t.after(() => { for (const socket of held) socket.destroy(); return new Promise((done) => server.close(done)); });
return server.address().port;
}
async function startProxy(t, authData) {
const dir = await mkdtemp(join(tmpdir(), "pipelines-auth-proxy-"));
t.after(() => rm(dir, { recursive: true, force: true }));
const auth = join(dir, "web-auth.json");
await writeFile(auth, JSON.stringify(authData), { mode: 0o600 });
const upstream = await fakeUpstream(t);
const port = await freePort();
const child = spawn(process.execPath, ["serve.mjs", "--port", String(port), "--root", join(dir, "absent"),
"--pipelines", `127.0.0.1:${upstream}`], {
cwd: here,
env: { ...process.env, PIPELINES_WEB_AUTH: "", PIPELINES_WEB_AUTH_FILE: auth, PIPELINES_WEB_SWEEP_MS: "200" },
stdio: ["ignore", "pipe", "pipe"],
});
t.after(async () => { const exited = once(child, "exit"); child.kill(); await exited; });
await once(child.stdout, "data");
const base = `http://127.0.0.1:${port}`;
return { auth, port, base, host: `127.0.0.1:${port}` };
}
const login = (proxy, headers = {}, password = PASSWORD) =>
fetch(proxy.base + "/login", { method: "POST", body: new URLSearchParams({ password, next: "/runs/1" }), redirect: "manual", headers });
const cookieOf = (response) => response.headers.get("set-cookie").split(";")[0];
const signedIn = async (proxy, cookie) =>
(await fetch(proxy.base + "/login", { headers: { Cookie: cookie }, redirect: "manual" })).status === 302;
/** Opens /connect through the proxy and resolves when the 101 arrives. */
async function openSocket(proxy, cookie) {
const socket = net.connect(proxy.port, "127.0.0.1");
await once(socket, "connect");
socket.write(`GET /connect HTTP/1.1\r\nHost: ${proxy.host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
`Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\nCookie: ${cookie}\r\n\r\n`);
const [chunk] = await once(socket, "data");
assert.match(chunk.toString(), /^HTTP\/1.1 101/);
const closed = once(socket, "close");
socket.on("error", () => {});
return { socket, closed };
}
const within = (promise, ms, what) =>
Promise.race([promise, new Promise((_, fail) => setTimeout(() => fail(new Error(`${what} not within ${ms} ms`)), ms))]);
test("login: Origin check, safe next, headers and the cookie prefix", async (t) => {
const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40), generation: 0 });
const cross = await login(proxy, { Origin: "https://evil.example" });
assert.equal(cross.status, 403);
assert.equal(cross.headers.get("set-cookie"), null);
const page = await fetch(proxy.base + "/login?next=/%5Cevil.com");
const html = await page.text();
assert.match(html, /name="next" value="\/"/);
assert.match(page.headers.get("content-security-policy"), /frame-ancestors 'none'/);
assert.match(page.headers.get("content-security-policy"), /default-src 'none'/);
assert.equal(page.headers.get("x-frame-options"), "DENY");
assert.equal(page.headers.get("x-content-type-options"), "nosniff");
assert.equal(page.headers.get("referrer-policy"), "same-origin");
assert.equal(page.headers.get("strict-transport-security"), null);
const ok = await login(proxy, { Origin: proxy.base });
assert.equal(ok.status, 303);
assert.equal(ok.headers.get("location"), "/runs/1");
assert.match(ok.headers.get("set-cookie"), /^pipelines_session=v2\./);
assert.doesNotMatch(ok.headers.get("set-cookie"), /Secure/);
// An app response may be framed by the app itself only.
const app = await fetch(proxy.base + "/runs/1", { headers: { Cookie: cookieOf(ok) } });
assert.equal(app.headers.get("x-frame-options"), "SAMEORIGIN");
assert.match(app.headers.get("content-security-policy"), /frame-ancestors 'self'/);
// Over https (Tailscale serve): __Host- prefix, Secure, HSTS.
const https = await login(proxy, { "X-Forwarded-Proto": "https" });
const secure = https.headers.get("set-cookie");
assert.match(secure, /^__Host-pipelines_session=v2\./);
assert.match(secure, /; Path=\/;/);
assert.match(secure, /; Secure/);
assert.doesNotMatch(secure, /Domain=/i);
assert.match(https.headers.get("strict-transport-security"), /max-age=\d+/);
assert.equal(await signedIn(proxy, cookieOf(https)), true);
// A native client (no Origin) still signs in.
assert.equal((await login(proxy)).status, 303);
});
test("logout is a same-origin POST that revokes the token and closes its sockets", async (t) => {
const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40) });
const a = cookieOf(await login(proxy));
const b = cookieOf(await login(proxy));
const ws = await openSocket(proxy, a);
const other = await openSocket(proxy, b);
// GET only shows a button; a cross-site POST is refused.
const page = await fetch(proxy.base + "/logout", { headers: { Cookie: a }, redirect: "manual" });
assert.equal(page.status, 200);
assert.match(await page.text(), /method="post" action="\/logout"/);
assert.equal((await fetch(proxy.base + "/logout", { method: "POST", headers: { Cookie: a, Origin: "https://evil.example" }, redirect: "manual" })).status, 403);
assert.equal(await signedIn(proxy, a), true);
const out = await fetch(proxy.base + "/logout", { method: "POST", headers: { Cookie: a, Origin: proxy.base }, redirect: "manual" });
assert.equal(out.status, 303);
assert.match(out.headers.get("set-cookie"), /pipelines_session=; .*Max-Age=0/);
// The copied cookie no longer works anywhere, and its socket is gone.
assert.equal(await signedIn(proxy, a), false);
await within(ws.closed, 2000, "the signed-out socket closing");
assert.equal(await signedIn(proxy, b), true);
assert.equal(other.socket.destroyed, false);
other.socket.destroy();
});
test("a password change revokes every session and closes open websockets", async (t) => {
const data = { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40), generation: 4 };
const proxy = await startProxy(t, data);
const cookie = cookieOf(await login(proxy));
const ws = await openSocket(proxy, cookie);
// What ./password writes: a new hash, secret and generation, atomically.
const next = { ...data, password_hash: hashPassword("ember canyon orbit tulip"), secret: "n".repeat(40), generation: 5 };
await writeFile(proxy.auth + ".next", JSON.stringify(next), { mode: 0o600 });
await rename(proxy.auth + ".next", proxy.auth);
await within(ws.closed, 3000, "the websocket closing after the password change");
assert.equal(await signedIn(proxy, cookie), false);
assert.equal((await login(proxy)).status, 401);
assert.equal((await login(proxy, {}, "ember canyon orbit tulip")).status, 303);
});
test("sign out everywhere from Settings, the session report and the weak-password warning", async (t) => {
const proxy = await startProxy(t, { password: "old-password", secret: "s".repeat(40) });
// The migration kept the old password working and stored only a hash.
const first = await login(proxy, {}, "old-password");
assert.equal(first.status, 303);
const stored = JSON.parse(await readFile(proxy.auth, "utf8"));
assert.equal(stored.password, undefined);
assert.match(stored.password_hash, /^scrypt\$/);
const a = cookieOf(first);
const b = cookieOf(await login(proxy, {}, "old-password"));
assert.equal((await fetch(proxy.base + "/api/session")).status, 401);
const report = await (await fetch(proxy.base + "/api/session", { headers: { Cookie: a } })).json();
assert.equal(report.weak_password, true);
assert.match(report.password_rule, /16 characters/);
const ws = await openSocket(proxy, b);
assert.equal((await fetch(proxy.base + "/api/sessions/revoke-all", { method: "POST", headers: { Cookie: a, Origin: "https://evil.example" } })).status, 403);
const revoke = await fetch(proxy.base + "/api/sessions/revoke-all", { method: "POST", headers: { Cookie: a, Origin: proxy.base } });
assert.equal(revoke.status, 200);
assert.deepEqual(await revoke.json(), { revoked: true });
await within(ws.closed, 2000, "every socket closing");
assert.equal(await signedIn(proxy, a), false);
assert.equal(await signedIn(proxy, b), false);
assert.equal(await signedIn(proxy, cookieOf(await login(proxy, {}, "old-password"))), true);
});
test("repeated wrong passwords are slowed down", async (t) => {
const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40) });
for (let i = 0; i < 5; i++) assert.equal((await login(proxy, {}, "wrong")).status, 401);
const blocked = await login(proxy, {}, PASSWORD);
assert.equal(blocked.status, 429);
assert.ok(Number(blocked.headers.get("retry-after")) >= 1);
});
+6 -3
View File
@@ -27,11 +27,14 @@ test("atomic password updates take effect without restart and fail closed on inv
const cookie = first.headers.get("set-cookie").split(";")[0]; const cookie = first.headers.get("set-cookie").split(";")[0];
await writeFile(auth + ".next", JSON.stringify({ ...data, password:"new-password" })); await rename(auth + ".next",auth); await writeFile(auth + ".next", JSON.stringify({ ...data, password:"new-password" })); await rename(auth + ".next",auth);
assert.equal((await login("old-password")).status,401); assert.equal((await login("old-password")).status,401);
assert.equal((await login("new-password")).status,303); const second = await login("new-password"); assert.equal(second.status,303);
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,302); // A changed password signs the earlier session out; the new one is signed in.
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,200);
const cookie2 = second.headers.get("set-cookie").split(";")[0];
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie2},redirect:"manual"})).status,302);
await writeFile(auth + ".next", "malformed"); await rename(auth + ".next",auth); await writeFile(auth + ".next", "malformed"); await rename(auth + ".next",auth);
assert.equal((await login("new-password")).status,503); assert.equal((await login("new-password")).status,503);
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,503); assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie2},redirect:"manual"})).status,503);
await writeFile(auth,JSON.stringify(data)); await writeFile(auth,JSON.stringify(data));
assert.equal((await login("old-password")).status,303); assert.equal((await login("old-password")).status,303);
}); });
+195
View File
@@ -0,0 +1,195 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, readFile, rm, stat, writeFile, rename } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { AuthStore, REVOKED_LIMIT, hashPassword, parseHash, verifyPassword } from "../src/authStore.js";
import { passwordProblem } from "../src/passwordPolicy.js";
import { LoginLimiter, clientKey } from "../src/loginLimiter.js";
import { safeNext, sameOriginRequest, isHttps, sessionCookieName } from "../src/webSecurity.js";
import { SessionSockets } from "../src/sessionSockets.js";
const CHEAP = { N: 1024, r: 8, p: 1, keyLength: 32 };
async function fixture(t, data) {
const dir = await mkdtemp(join(tmpdir(), "pipelines-auth-store-"));
t.after(() => rm(dir, { recursive: true, force: true }));
const file = join(dir, "web-auth.json");
await writeFile(file, JSON.stringify(data), { mode: 0o600 });
return file;
}
const replace = async (file, data) => {
await writeFile(`${file}.next`, JSON.stringify(data), { mode: 0o600 });
await rename(`${file}.next`, file);
};
test("hashes are scrypt with recorded parameters and verify in constant time", async () => {
const stored = hashPassword("tulip orbit canyon ember", CHEAP);
assert.match(stored, /^scrypt\$1024\$8\$1\$[A-Za-z0-9_-]+\$[A-Za-z0-9_-]+$/);
assert.ok(parseHash(stored));
assert.equal(await verifyPassword(stored, "tulip orbit canyon ember"), true);
assert.equal(await verifyPassword(stored, "tulip orbit canyon embers"), false);
assert.equal(await verifyPassword("scrypt$1000$8$1$AAAAAAAAAAA$BBBBBBBBBBBBBBBBBBBBBB", "x"), false);
assert.equal(parseHash("plain"), null);
});
test("a plaintext password migrates to a hash without changing it", async (t) => {
const file = await fixture(t, { password: "old-password", secret: "s".repeat(40), other: "kept" });
const logs = [];
const store = new AuthStore(file, { log: (line) => logs.push(line) });
const state = store.load();
const written = JSON.parse(await readFile(file, "utf8"));
assert.equal(written.password, undefined);
assert.equal(written.other, "kept");
assert.equal(written.password_weak, true);
assert.equal(written.secret, "s".repeat(40)); // first start: sessions stay valid
assert.equal(state.weak, true);
assert.equal(await verifyPassword(written.password_hash, "old-password"), true);
assert.equal((await stat(file)).mode & 0o777, 0o600);
assert.ok(!logs.join("\n").includes("old-password"));
// A strong plaintext is not flagged.
const strong = await fixture(t, { password: "tulip orbit canyon ember", secret: "s".repeat(40) });
assert.equal(new AuthStore(strong, { log() {} }).load().weak, false);
});
test("a plaintext password written over a running proxy signs every session out", async (t) => {
const file = await fixture(t, { password_hash: hashPassword("first passphrase here ok", CHEAP), secret: "s".repeat(40), generation: 3 });
const store = new AuthStore(file, { log() {} });
const { token } = store.issue(60);
await replace(file, { password: "new-password", secret: "s".repeat(40), generation: 3 });
assert.equal(store.check(token), null);
const written = JSON.parse(await readFile(file, "utf8"));
assert.equal(written.generation, 4);
assert.notEqual(written.secret, "s".repeat(40));
});
test("tokens: signature, expiry, generation, logout and sign out everywhere", async (t) => {
let now = 1_800_000_000_000;
const data = { password_hash: hashPassword("tulip orbit canyon ember", CHEAP), secret: "s".repeat(40), generation: 1 };
const file = await fixture(t, data);
const store = new AuthStore(file, { now: () => now, log() {} });
const a = store.issue(60).token;
const b = store.issue(3600).token;
assert.ok(store.check(a));
assert.equal(store.check(a.slice(0, -2) + (a.endsWith("A") ? "BB" : "AA")), null);
assert.equal(store.check(a.replace(/^v2\.1\./, "v2.2.")), null);
assert.equal(store.check("1800000000.abc.def"), null); // the old unversioned format
// Server-side logout of one token leaves the other.
assert.equal(store.revoke(a), true);
assert.equal(store.check(a), null);
assert.ok(store.check(b));
// The list survives a proxy restart.
assert.equal(new AuthStore(file, { now: () => now, log() {} }).check(a), null);
assert.equal(((await stat(`${file}.sessions.json`)).mode & 0o777), 0o600);
// Expiry.
now += 61_000;
const c = store.issue(60).token;
now += 1000;
assert.ok(store.check(c));
now += 60_000;
assert.equal(store.check(c), null);
// Sign out everywhere: every earlier token, but not a later sign-in.
const d = store.issue(3600).token;
now += 1;
store.revokeAll();
assert.equal(store.check(b), null);
assert.equal(store.check(d), null);
now += 1;
const e = store.issue(3600).token;
assert.ok(store.check(e));
assert.ok(new AuthStore(file, { now: () => now, log() {} }).check(e));
assert.equal(new AuthStore(file, { now: () => now, log() {} }).check(d), null);
// ./password (new secret and generation) ends every session.
await replace(file, { ...data, secret: "t".repeat(40), generation: 2 });
assert.equal(store.check(e), null);
const f = store.issue(3600).token;
assert.ok(store.check(f));
});
test("the signed-out list is bounded, dropping the soonest to expire", async (t) => {
const file = await fixture(t, { password_hash: hashPassword("tulip orbit canyon ember", CHEAP), secret: "s".repeat(40) });
const store = new AuthStore(file, { now: () => 1_000_000, log() {} });
store.load();
for (let i = 0; i < REVOKED_LIMIT + 5; i++) store.revoked.set(`token-id-${String(i).padStart(6, "0")}`, 10_000 + i);
store.saveSessions();
assert.equal(store.revoked.size, REVOKED_LIMIT);
assert.ok(!store.revoked.has("token-id-000000"));
assert.ok(store.revoked.has(`token-id-${String(REVOKED_LIMIT + 4).padStart(6, "0")}`));
});
test("the strength rule matches scripts/password.py", () => {
for (const strong of ["tulip orbit canyon ember", "correct horse battery staple", "k7#Rv9!qLm2@Xz4s", "cat dog sun red"])
assert.equal(passwordProblem(strong), null, strong);
for (const weak of ["short", "old password", "J8m!x2Lq0#vR9tZ", "password password password", "a".repeat(20),
"Password12345678!", "qwertyuiop1234567890", "password welcome admin letmein", "dog dog dog dog dog"])
assert.notEqual(passwordProblem(weak), null, weak);
});
test("limiter: per-client backoff, success reset, global cap and bounded eviction", () => {
let now = 0;
const limiter = new LoginLimiter({ now: () => now, freeFailures: 3, baseMs: 1000, maxKeys: 4, globalLimit: 10, globalWindowMs: 60_000 });
for (let i = 0; i < 2; i++) limiter.fail("a");
assert.equal(limiter.blocked("a"), 0);
limiter.fail("a");
assert.equal(limiter.blocked("a"), 1000);
limiter.fail("a");
assert.equal(limiter.blocked("a"), 2000); // doubles
assert.equal(limiter.blocked("b"), 0);
limiter.succeed("a");
assert.equal(limiter.blocked("a"), 0);
// Eviction keeps at most maxKeys clients, the least recent leaving first.
for (const key of ["k1", "k2", "k3", "k4", "k5"]) limiter.fail(key);
assert.equal(limiter.clients.size, 4);
assert.ok(!limiter.clients.has("k1"));
// The global window: ten failures from anyone block everyone.
now = 120_000;
for (let i = 0; i < 10; i++) limiter.fail(`spread-${i}`);
assert.ok(limiter.blocked("someone-new") > 0);
assert.ok(limiter.recent.length <= 10);
now += 60_000;
assert.equal(limiter.blocked("someone-new"), 0);
});
test("the limiter charges Tailscale users only behind a loopback Tailscale proxy", () => {
const req = (address, headers) => ({ socket: { remoteAddress: address }, headers });
assert.equal(clientKey(req("127.0.0.1", { "tailscale-user-login": "Alan@Example.com" })), "tailscale:alan@example.com");
assert.equal(clientKey(req("::1", { "tailscale-user-name": "x", "x-forwarded-for": "100.64.0.7, 1.1.1.1" })), "forwarded:100.64.0.7");
assert.equal(clientKey(req("127.0.0.1", { "x-forwarded-for": "100.64.0.7" })), "address:127.0.0.1");
assert.equal(clientKey(req("192.168.1.5", { "tailscale-user-login": "forged@example.com" })), "address:192.168.1.5");
});
test("next targets stay on this origin", () => {
for (const good of ["/", "/runs/12", "/chat?x=1#y", "/a/b//c"]) assert.equal(safeNext(good), good);
for (const bad of ["//evil.com", "/\\evil.com", "\\\\evil.com", "https://evil.com", "evil", "/ok\\path", "/a\nb", "", null])
assert.equal(safeNext(bad), "/", String(bad));
});
test("origin checks, https detection and cookie naming", () => {
const req = (headers, encrypted = false) => ({ headers: { host: "pipelines.example:8443", ...headers }, socket: { encrypted } });
assert.equal(sameOriginRequest(req({})), true);
assert.equal(sameOriginRequest(req({ origin: "https://pipelines.example:8443" })), true);
assert.equal(sameOriginRequest(req({ origin: "https://evil.example" })), false);
assert.equal(sameOriginRequest(req({ origin: "null" })), false);
assert.equal(sameOriginRequest(req({ "sec-fetch-site": "cross-site" })), false);
assert.equal(sameOriginRequest(req({ "sec-fetch-site": "same-site", origin: "https://pipelines.example:8443" })), false);
assert.equal(isHttps(req({ "x-forwarded-proto": "https" })), true);
assert.equal(isHttps(req({})), false);
assert.equal(sessionCookieName(req({ "x-forwarded-proto": "https" })), "__Host-pipelines_session");
assert.equal(sessionCookieName(req({})), "pipelines_session");
});
test("socket sweep destroys only sockets whose session is gone", async () => {
const { EventEmitter } = await import("node:events");
const sockets = new SessionSockets();
const make = () => Object.assign(new EventEmitter(), { destroyed: false, destroy() { this.destroyed = true; this.emit("close"); } });
const keep = make(), drop = make();
sockets.track(keep, "good");
sockets.track(drop, "bad");
assert.equal(sockets.sweep((token) => token === "good"), 1);
assert.equal(drop.destroyed, true);
assert.equal(keep.destroyed, false);
assert.equal(sockets.size, 1);
keep.emit("close");
assert.equal(sockets.size, 0);
});