From 394fd672e683996605a8c72ea06b50c6415241a0 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 8 Nov 2026 16:49:45 +0000 Subject: [PATCH] Check all saved servers for compatible native app updates --- app/lib/application/pipelines_app.dart | 21 +++ app/lib/core/session/server_session.dart | 22 +++ .../settings/settings_topic_pages.dart | 8 +- .../settings/settings_updates_section.dart | 28 ++- app/lib/features/updates/app_updates.dart | 133 +++++++++++++- app/lib/features/updates/app_updates_io.dart | 156 ++++++++++++---- .../features/updates/app_updates_stub.dart | 5 + app/lib/features/updates/launch_update.dart | 8 +- .../updates/launch_update_dialog.dart | 14 +- app/notes/native-multi-server-updates.md | 39 ++++ app/pubspec.lock | 2 +- app/pubspec.yaml | 1 + .../session/server_session_requests_test.dart | 25 ++- .../updates/multi_server_updates_test.dart | 167 ++++++++++++++++++ .../updates/native_update_dialog_test.dart | 32 ++++ app/tool/search_selection_probe_entry.dart | 12 ++ 16 files changed, 615 insertions(+), 58 deletions(-) create mode 100644 app/notes/native-multi-server-updates.md create mode 100644 app/test/features/updates/multi_server_updates_test.dart create mode 100644 app/test/features/updates/native_update_dialog_test.dart diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 56490377..4c3f28fd 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -322,6 +322,21 @@ class _PipelinesAppState extends State readWeb: widget.webReleaseReader, installedVersion: widget.installedVersionReader, readAndroid: widget.androidFeedReader, + readNative: widget.servers == null + ? null + : () => newestServerUpdate( + widget.servers!.catalog.servers, + stillTrusted: (source, uri) => updateSourceStillTrusted( + widget.servers!.catalog.servers, + source, + uri, + ), + ), + nativeScope: + widget.servers?.catalog.servers + .map((s) => '${s.id}:${s.endpoints.join(',')}') + .join(';') ?? + '', ); if (!mounted || update == null || !dialogContext.mounted) return; if (!widget.webPlatform && endpoint != _session.endpoint) return; @@ -329,6 +344,12 @@ class _PipelinesAppState extends State final accepted = await showLaunchUpdateDialog( dialogContext, web: update is WebLaunchUpdate, + sourceName: update is AndroidLaunchUpdate + ? update.update.sourceName + : '', + nativePlatform: update is AndroidLaunchUpdate + ? update.update.platform + : '', cupertino: _cupertino, ); if (accepted != true || !mounted || !dialogContext.mounted) return; diff --git a/app/lib/core/session/server_session.dart b/app/lib/core/session/server_session.dart index ea4e0e39..393c466f 100644 --- a/app/lib/core/session/server_session.dart +++ b/app/lib/core/session/server_session.dart @@ -85,6 +85,28 @@ class ServerSession { return headers; } + /// Read one profile without changing the selected socket or credentials. + static Future Function(Uri)> credentialReader({ + required String id, + required Iterable endpoints, + }) async { + final origins = endpoints.map(loginUriFor).whereType().toSet(); + final key = _scopeKey(id); + final version = _versions[key]; + final value = id == _serverId + ? cookie + : (await SharedPreferences.getInstance()).getString(key); + return (Uri uri) { + if (_versions[key] != version || + !origins.contains(loginUriFor(uri)) || + value == null || + value.isEmpty) { + return const {}; + } + return {'Cookie': value}; + }; + } + static Future load() async { final generation = ++_generation; _serverId = null; diff --git a/app/lib/features/settings/settings_topic_pages.dart b/app/lib/features/settings/settings_topic_pages.dart index c84eb063..058d0d9a 100644 --- a/app/lib/features/settings/settings_topic_pages.dart +++ b/app/lib/features/settings/settings_topic_pages.dart @@ -88,7 +88,13 @@ extension _SettingsTopicPages on _SettingsScreenState { if (widget.showAndroidDownload) _single('Android app', const SettingsAndroidDownloadSection()), if (widget.showSignIn && appUpdatesSupported) - _single('App updates', SettingsUpdatesSection(endpoint: _endpoint)), + _single( + 'App updates', + SettingsUpdatesSection( + endpoint: _endpoint, + servers: widget.servers, + ), + ), if (!widget.showAndroidDownload && !(widget.showSignIn && appUpdatesSupported)) _single( diff --git a/app/lib/features/settings/settings_updates_section.dart b/app/lib/features/settings/settings_updates_section.dart index d6d0ddc2..31d9f3b6 100644 --- a/app/lib/features/settings/settings_updates_section.dart +++ b/app/lib/features/settings/settings_updates_section.dart @@ -3,14 +3,20 @@ import 'package:flutter/material.dart'; import '../../ui/adaptive/host.dart'; import '../updates/app_updates.dart'; +import 'server_connections.dart'; /// Check for updates: compares this build with the newest one the server /// offers and installs it on request. class SettingsUpdatesSection extends StatefulWidget { - const SettingsUpdatesSection({super.key, required this.endpoint}); + const SettingsUpdatesSection({ + super.key, + required this.endpoint, + this.servers, + }); /// The server's websocket address; its builds sit beside it. final String endpoint; + final ServerConnections? servers; @override State createState() => _SettingsUpdatesSectionState(); @@ -44,15 +50,25 @@ class _SettingsUpdatesSectionState extends State { _available = null; }); try { - final latest = await fetchLatestUpdate(base); + final latest = widget.servers == null + ? await fetchLatestUpdate(base) + : await newestServerUpdate( + widget.servers!.catalog.servers, + stillTrusted: (source, uri) => updateSourceStillTrusted( + widget.servers!.catalog.servers, + source, + uri, + ), + ); if (!mounted) return; final installed = _installed ?? 0; setState(() { if (latest.versionCode > installed) { _available = latest; - _message = 'Build ${latest.versionCode} is available.'; + _message = + 'Build ${latest.versionCode} is available${latest.sourceName.isEmpty ? '' : ' from ${latest.sourceName}'}.'; } else { - _message = 'Up to date.'; + _message = 'No newer compatible build found on reachable servers.'; } }); } catch (error) { @@ -77,7 +93,7 @@ class _SettingsUpdatesSectionState extends State { if (mounted) setState(() => _progress = value); }, ); - if (mounted) setState(() => _message = 'Opened the installer.'); + if (mounted) setState(() => _message = 'Opened the downloaded update.'); } catch (error) { if (mounted) setState(() => _message = '$error'); } finally { @@ -139,7 +155,7 @@ class _SettingsUpdatesSectionState extends State { if (_available != null) button( const Key('settings-install-update'), - 'Download and install', + 'Download update', _busy ? null : _install, true, ), diff --git a/app/lib/features/updates/app_updates.dart b/app/lib/features/updates/app_updates.dart index 260f7438..37651484 100644 --- a/app/lib/features/updates/app_updates.dart +++ b/app/lib/features/updates/app_updates.dart @@ -1,5 +1,8 @@ import 'dart:convert'; +import '../../core/servers/server_catalog.dart'; +import '../../core/session/server_session.dart'; + import 'app_updates_stub.dart' if (dart.library.io) 'app_updates_io.dart' as impl; @@ -11,23 +14,73 @@ class AppUpdate { required this.versionName, required this.apk, this.notes = '', + this.sourceName = '', + this.headersFor, + this.platform = 'android', + this.sha256 = '', }); final int versionCode; final String versionName; final Uri apk; final String notes; + final String sourceName; + final String platform; + final String sha256; + final Map Function(Uri)? headersFor; + + AppUpdate fromServer( + String name, + Map Function(Uri) headers, + ) => AppUpdate( + versionCode: versionCode, + versionName: versionName, + apk: apk, + notes: notes, + platform: platform, + sourceName: name, + sha256: sha256, + headersFor: headers, + ); /// Reads `version.json`; the APK path is relative to [base]. - static AppUpdate? parse(String body, Uri base) { + static AppUpdate? parse( + String body, + Uri base, { + String platform = 'android', + String architecture = 'arm64', + }) { try { final json = jsonDecode(body); if (json is! Map) return null; final code = json['versionCode']; - final file = '${json['apk'] ?? ''}'.trim(); - if (code is! num || file.isEmpty) return null; + final file = '${json[platform == 'android' ? 'apk' : 'file'] ?? ''}' + .trim(); + if (code is! int || + code < 1 || + file.isEmpty || + !RegExp(r'^[a-zA-Z0-9][a-zA-Z0-9._-]*$').hasMatch(file)) { + return null; + } + final digest = '${json['sha256'] ?? ''}'; + if (digest.isNotEmpty && !RegExp(r'^[a-fA-F0-9]{64}$').hasMatch(digest)) { + return null; + } + if (platform == 'android' && + json['platform'] != null && + json['platform'] != 'android') { + return null; + } + if (platform != 'android' && + (json['platform'] != platform || + json['architectures'] is! List || + !(json['architectures'] as List).contains(architecture))) { + return null; + } return AppUpdate( - versionCode: code.toInt(), + versionCode: code, + platform: platform, + sha256: '${json['sha256'] ?? ''}', versionName: '${json['versionName'] ?? ''}', apk: base.resolve(file), notes: '${json['notes'] ?? ''}', @@ -65,7 +118,7 @@ Uri? updatesBaseFor(Uri endpoint, {String configured = configuredUpdatesUrl}) { ); } -/// Whether this build can update itself (an Android phone). +/// Whether this native build supports platform-compatible update downloads. bool get appUpdatesSupported => impl.supported; /// The installed build number, or null where there is none to compare. @@ -80,3 +133,73 @@ Future downloadAndInstall( AppUpdate update, { void Function(double progress)? onProgress, }) => impl.downloadAndInstall(update, onProgress: onProgress); + +/// Checks each logical machine independently; aliases share only its credential. +/// Failed machines cannot hide a newer compatible build on a healthy machine. +Future newestServerUpdate( + Iterable servers, { + Future Function(Uri, Map Function(Uri))? read, + bool Function(SavedServer server, Uri uri)? stillTrusted, +}) async { + final results = await Future.wait( + servers.map((server) async { + Map Function(Uri) headers; + try { + headers = await ServerSession.credentialReader( + id: server.id, + endpoints: server.endpoints.map(Uri.parse), + ); + } catch (_) { + return null; + } + final snapshotHeaders = headers; + headers = (uri) { + if (stillTrusted != null && !stillTrusted(server, uri)) { + throw StateError( + 'The update server is no longer a saved trusted address.', + ); + } + return snapshotHeaders(uri); + }; + final candidates = await Future.wait( + server.endpoints.map((endpoint) async { + final base = updatesBaseFor(Uri.parse(endpoint), configured: ''); + if (base == null) return null; + try { + final update = await (read ?? impl.fetchLatestScoped)( + base, + headers, + ).timeout(const Duration(seconds: 15)); + return update.fromServer(server.name, headers); + } catch (_) { + return null; + } + }), + ); + final builds = candidates.whereType().toList() + ..sort((a, b) => b.versionCode.compareTo(a.versionCode)); + return builds.isEmpty ? null : builds.first; + }), + ); + final available = results.whereType().toList() + ..sort((a, b) => b.versionCode.compareTo(a.versionCode)); + if (available.isEmpty) { + throw const FormatException( + 'No compatible update could be read. Check your saved servers and sign-ins.', + ); + } + return available.first; +} + +/// Retained offers must stop trusting an alias if its profile is edited/removed. +bool updateSourceStillTrusted( + Iterable current, + SavedServer source, + Uri uri, +) => current.any( + (server) => + server.id == source.id && + server.endpoints.any( + (endpoint) => loginUriFor(Uri.parse(endpoint)) == loginUriFor(uri), + ), +); diff --git a/app/lib/features/updates/app_updates_io.dart b/app/lib/features/updates/app_updates_io.dart index 82831138..ea4cc66a 100644 --- a/app/lib/features/updates/app_updates_io.dart +++ b/app/lib/features/updates/app_updates_io.dart @@ -1,4 +1,8 @@ import 'dart:io'; +import 'dart:convert'; +import 'dart:ffi'; + +import 'package:crypto/crypto.dart' as crypto; import 'package:open_filex/open_filex.dart'; import 'package:package_info_plus/package_info_plus.dart'; @@ -7,19 +11,37 @@ import 'package:path_provider/path_provider.dart'; import '../../core/session/server_session.dart'; import 'app_updates.dart'; -bool get supported => Platform.isAndroid; +bool get supported => + Platform.isAndroid || Platform.isLinux || Platform.isMacOS; +String get nativePlatform => Platform.isMacOS + ? 'macos' + : Platform.isLinux + ? 'linux' + : 'android'; +String get nativeArchitecture { + final abi = Abi.current().toString(); + if (abi.endsWith('_arm64')) return 'arm64'; + if (abi.endsWith('_x64')) return 'x64'; + return 'unsupported'; +} Future installedVersionCode() async { + const embedded = int.fromEnvironment('PIPELINES_NATIVE_BUILD_CODE'); + if (embedded > 0) return embedded; final info = await PackageInfo.fromPlatform(); return int.tryParse(info.buildNumber); } -Future _get(HttpClient client, Uri uri) async { - final request = await client.getUrl(uri); +Future _get( + HttpClient client, + Uri uri, [ + Map Function(Uri)? headers, +]) async { + final request = await client.getUrl(uri).timeout(const Duration(seconds: 15)); request.followRedirects = false; // The updates sit behind the same web login the app signed in to. - ServerSession.headersFor(uri).forEach(request.headers.set); - final response = await request.close(); + (headers ?? ServerSession.headersFor)(uri).forEach(request.headers.set); + final response = await request.close().timeout(const Duration(seconds: 15)); if (response.statusCode == 401 || response.statusCode == 302) { await response.drain(); throw const HttpException('Sign in first (Settings → Sign in).'); @@ -31,47 +53,111 @@ Future _get(HttpClient client, Uri uri) async { return response; } -Future fetchLatest(Uri base) async { - final client = HttpClient()..connectionTimeout = const Duration(seconds: 15); +Future fetchLatest(Uri base) => + fetchLatestScoped(base, ServerSession.headersFor); + +Future fetchLatestScoped( + Uri base, + Map Function(Uri) headers, +) async { + final platform = nativePlatform; + if (platform == 'linux' && nativeArchitecture != 'x64') { + throw const FormatException( + 'No Linux build is available for this architecture.', + ); + } + final feed = platform == 'android' + ? base + : base.resolve(platform == 'linux' ? 'linux-x64/' : 'macos/'); + final client = HttpClient()..connectionTimeout = const Duration(seconds: 10); try { - final response = await _get(client, base.resolve('version.json')); - final body = await response - .transform(const SystemEncoding().decoder) - .join(); - final update = AppUpdate.parse(body, base); - if (update == null) throw const FormatException('No build is offered.'); + final response = await _get(client, feed.resolve('version.json'), headers); + var bytes = 0; + final chunks = []; + await for (final chunk in response.timeout(const Duration(seconds: 10))) { + bytes += chunk.length; + if (bytes > 65536) { + throw const FormatException('Update metadata is too large.'); + } + chunks.addAll(chunk); + } + final update = AppUpdate.parse( + utf8.decode(chunks), + feed, + platform: platform, + architecture: nativeArchitecture, + ); + if (update == null) { + throw const FormatException('No compatible build is offered.'); + } return update; } finally { client.close(force: true); } } +/// Downloads to a partial file and publishes it only after integrity checks. +Future downloadUpdate( + AppUpdate update, + Directory dir, { + void Function(double progress)? onProgress, +}) async { + final client = HttpClient()..connectionTimeout = const Duration(seconds: 15); + final suffix = update.platform == 'android' + ? 'apk' + : update.platform == 'macos' + ? 'zip' + : 'tar.gz'; + final file = File('${dir.path}/pipelines-${update.versionCode}.$suffix'); + final partial = File('${file.path}.part'); + try { + final response = await _get(client, update.apk, update.headersFor); + final total = response.contentLength; + final sink = partial.openWrite(); + var received = 0; + try { + await for (final chunk in response.timeout(const Duration(seconds: 30))) { + sink.add(chunk); + received += chunk.length; + if (total > 0) onProgress?.call(received / total); + } + } finally { + await sink.close(); + } + if (total >= 0 && received != total) { + throw const HttpException('The update download was incomplete.'); + } + if (update.sha256.isNotEmpty) { + final digest = await crypto.sha256.bind(partial.openRead()).first; + if (digest.toString() != update.sha256.toLowerCase()) { + throw const FormatException( + 'The downloaded update failed its integrity check.', + ); + } + } + await partial.rename(file.path); + return file; + } finally { + client.close(force: true); + if (await partial.exists()) await partial.delete(); + } +} + Future downloadAndInstall( AppUpdate update, { void Function(double progress)? onProgress, }) async { - final client = HttpClient()..connectionTimeout = const Duration(seconds: 15); - try { - final response = await _get(client, update.apk); - final total = response.contentLength; - final dir = await getTemporaryDirectory(); - final file = File('${dir.path}/pipelines-${update.versionCode}.apk'); - final sink = file.openWrite(); - var received = 0; - await for (final chunk in response) { - sink.add(chunk); - received += chunk.length; - if (total > 0) onProgress?.call(received / total); - } - await sink.close(); - final result = await OpenFilex.open( - file.path, - type: 'application/vnd.android.package-archive', + final dir = Platform.isAndroid + ? await getTemporaryDirectory() + : (await getDownloadsDirectory() ?? await getTemporaryDirectory()); + final file = await downloadUpdate(update, dir, onProgress: onProgress); + final result = await OpenFilex.open( + file.path, + type: Platform.isAndroid ? 'application/vnd.android.package-archive' : null, + ); + if (result.type != ResultType.done) { + throw HttpException( + 'Could not open the downloaded update: ${result.message}', ); - if (result.type != ResultType.done) { - throw HttpException('Could not open the installer: ${result.message}'); - } - } finally { - client.close(force: true); } } diff --git a/app/lib/features/updates/app_updates_stub.dart b/app/lib/features/updates/app_updates_stub.dart index f8e46f17..109ac74c 100644 --- a/app/lib/features/updates/app_updates_stub.dart +++ b/app/lib/features/updates/app_updates_stub.dart @@ -11,3 +11,8 @@ Future downloadAndInstall( AppUpdate update, { void Function(double progress)? onProgress, }) async => throw StateError('Updates are installed from a phone.'); + +Future fetchLatestScoped( + Uri base, + Map Function(Uri) headers, +) => fetchLatest(base); diff --git a/app/lib/features/updates/launch_update.dart b/app/lib/features/updates/launch_update.dart index b5c46554..a54deb7d 100644 --- a/app/lib/features/updates/launch_update.dart +++ b/app/lib/features/updates/launch_update.dart @@ -67,6 +67,8 @@ class LaunchUpdateChecker { required Future Function(Uri) readWeb, required Future Function() installedVersion, required Future Function(Uri) readAndroid, + Future Function()? readNative, + String nativeScope = '', }) async { final feed = web ? webReleaseUri(page) @@ -76,7 +78,7 @@ class LaunchUpdateChecker { if (feed == null || (web ? webBuildId.trim().isEmpty : !android)) { return null; } - final key = '${web ? 'web' : 'android'}:$feed'; + final key = '${web ? 'web' : 'native'}:$feed:$nativeScope'; if (_attempt == key) return null; _attempt = key; LaunchUpdate? update; @@ -89,7 +91,9 @@ class LaunchUpdateChecker { ); if (installed != null) { update = androidUpdateFor( - await readAndroid(feed).timeout(const Duration(seconds: 15)), + await (readNative == null ? readAndroid(feed) : readNative()).timeout( + const Duration(seconds: 30), + ), installed, ); } diff --git a/app/lib/features/updates/launch_update_dialog.dart b/app/lib/features/updates/launch_update_dialog.dart index 44a1bef8..deb95d9b 100644 --- a/app/lib/features/updates/launch_update_dialog.dart +++ b/app/lib/features/updates/launch_update_dialog.dart @@ -8,6 +8,8 @@ Future showLaunchUpdateDialog( BuildContext context, { required bool web, required bool cupertino, + String sourceName = '', + String nativePlatform = 'android', }) => cupertino ? showCupertinoDialog( context: context, @@ -16,7 +18,11 @@ Future showLaunchUpdateDialog( content: Text( web ? 'A newer Pipelines web build is available.' - : 'A newer Android build is available.', + : 'A newer ${nativePlatform == 'macos' + ? 'macOS' + : nativePlatform == 'linux' + ? 'Linux' + : 'Android'} build is available${sourceName.isEmpty ? '' : ' from $sourceName'}.${nativePlatform == 'android' ? '' : ' Download and extract the archive to update the app.'}', ), actions: [ CupertinoDialogAction( @@ -38,7 +44,11 @@ Future showLaunchUpdateDialog( content: Text( web ? 'A newer Pipelines web build is available.' - : 'A newer Android build is available.', + : 'A newer ${nativePlatform == 'macos' + ? 'macOS' + : nativePlatform == 'linux' + ? 'Linux' + : 'Android'} build is available${sourceName.isEmpty ? '' : ' from $sourceName'}.${nativePlatform == 'android' ? '' : ' Download and extract the archive to update the app.'}', ), actions: [ TextButton( diff --git a/app/notes/native-multi-server-updates.md b/app/notes/native-multi-server-updates.md new file mode 100644 index 00000000..1c5b9f57 --- /dev/null +++ b/app/notes/native-multi-server-updates.md @@ -0,0 +1,39 @@ +# Native updates from saved machines + +Android, Linux x64 and macOS clients check all saved logical servers on foreground +visits and through Settings → App updates. Each machine's aliases are checked +independently and failed/signed-out addresses do not hide compatible builds found +elsewhere. The newest numeric build wins; the prompt and manual result name its +saved machine alias. Native checks never select another server or change its socket. +Web release checks remain bound to the page origin. + +Android retains `/updates/version.json` and its APK installer. Linux reads +`/updates/linux-x64/version.json`; macOS reads `/updates/macos/version.json`. +Desktop feeds require the matching platform and actual native architecture, and a +relative artifact basename. Desktop updates download to Downloads and open the +archive; the running application is never replaced automatically. Build identity +uses `PIPELINES_NATIVE_BUILD_CODE` when embedded, with package build number as fallback. + +Each request uses a read-only per-profile credential snapshot, trusted only for its +explicit HTTP origins. Logout invalidates retained credentials, while removed +profiles/aliases invalidate retained update offers. Redirects are not followed. +Metadata is bounded to 64 KiB, requests/streams have deadlines, and a provided +SHA256 is verified before publishing/opening the download. Failed downloads delete +partial files. The already locked crypto dependency is promoted to direct use. + +Verification: focused updater, profile/request auth and startup-flow suite passed +36 tests after metadata validation, trust invalidation and download integrity checks, including loopback authenticated +archive integrity success/failure, newest-server selection with an offline peer, +foreign origin rejection, removed trust, and platform/architecture/path filtering. +Analyzer clean. Final checks and rendered capture evidence recorded in delivery. + +Inspected real generic full-app browser captures (no production endpoints): +- `/tmp/review/native-updates-material/01-native-update-prompt.png` (1280×900 dark Material, Linux) +- `/tmp/review/native-updates-cupertino/01-native-update-prompt.png` (900×900 light Cupertino, macOS) +Both show source alias, archive instructions, and working Later action. Browser +captures validate portable prompt layout; real desktop installer/device behavior +is not claimed by these captures. + +Final suite `/tmp/memwatch/out.6XWDNJ`: 36 passed; analyzer clean at +`/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/flutter-analyze.zQ46R4`. +Display names subsequently polished to Linux/macOS (feed values unchanged). diff --git a/app/pubspec.lock b/app/pubspec.lock index e0f9bedd..784cc22e 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -122,7 +122,7 @@ packages: source: hosted version: "0.3.5+5" crypto: - dependency: transitive + dependency: "direct main" description: name: crypto sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 90b2201a..1eafb709 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -33,6 +33,7 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. + crypto: ^3.0.7 cupertino_icons: ^1.0.8 web_socket_channel: ^3.0.3 shared_preferences: ^2.5.6 diff --git a/app/test/core/session/server_session_requests_test.dart b/app/test/core/session/server_session_requests_test.dart index f25255f0..33139290 100644 --- a/app/test/core/session/server_session_requests_test.dart +++ b/app/test/core/session/server_session_requests_test.dart @@ -1,4 +1,5 @@ import 'dart:io'; +import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; @@ -36,7 +37,8 @@ void main() { return; } await request.drain(); - if (request.uri.path == '/redirect/version.json' || + if (request.uri.path.startsWith('/redirect/') && + request.uri.path.endsWith('/version.json') || request.uri.path == '/redirect/socket') { request.response.statusCode = HttpStatus.temporaryRedirect; request.response.headers.set( @@ -46,7 +48,15 @@ void main() { } else if (request.uri.path == '/login') { request.response.statusCode = HttpStatus.found; } else { - request.response.write('{"versionCode":1,"apk":"app.apk"}'); + request.response.write( + jsonEncode({ + 'versionCode': 1, + 'apk': 'app.apk', + 'platform': updates.nativePlatform, + 'architectures': [updates.nativeArchitecture], + 'file': 'app.zip', + }), + ); } await request.response.close(); }); @@ -85,7 +95,9 @@ void main() { '/login', '/artifact', '/upload', - '/version.json', + Platform.isAndroid + ? '/version.json' + : '/${updates.nativePlatform == 'linux' ? 'linux-x64' : 'macos'}/version.json', '/socket', ]) { expect(cookies['${uri.port}$path'], [ @@ -100,9 +112,10 @@ void main() { updates.fetchLatest(trustedUri.resolve('redirect/')), throwsA(isA()), ); - expect(cookies['${trusted.port}/redirect/version.json'], [ - 'pipelines_session=fixture', - ]); + expect( + cookies['${trusted.port}/redirect/${Platform.isAndroid ? '' : '${updates.nativePlatform == 'linux' ? 'linux-x64' : 'macos'}/'}version.json'], + ['pipelines_session=fixture'], + ); expect(cookies['${external.port}/version.json'], isNull); }); diff --git a/app/test/features/updates/multi_server_updates_test.dart b/app/test/features/updates/multi_server_updates_test.dart new file mode 100644 index 00000000..e6522cc3 --- /dev/null +++ b/app/test/features/updates/multi_server_updates_test.dart @@ -0,0 +1,167 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:crypto/crypto.dart'; +import 'package:pipelines_app/features/updates/app_updates_io.dart' as io; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/session/server_session.dart'; +import 'package:pipelines_app/features/updates/app_updates.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + test( + 'retained update refuses credentials after alias/profile removal', + () async { + SharedPreferences.setMockInitialValues({}); + final source = SavedServer.validated( + id: 'source', + name: 'Home', + endpoints: ['wss://home.test/connect'], + ); + var current = [source]; + final update = await newestServerUpdate( + current, + stillTrusted: (server, uri) => + updateSourceStillTrusted(current, server, uri), + read: (base, headers) async => AppUpdate( + versionCode: 12, + versionName: '', + apk: base.resolve('app.apk'), + ), + ); + current = []; + expect(() => update.headersFor!(update.apk), throwsStateError); + }, + ); + test( + 'downloads authenticate their source, verify digest and remove failed partials', + () async { + final previousOverrides = HttpOverrides.current; + HttpOverrides.global = null; + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final directory = await Directory.systemTemp.createTemp('update-test-'); + final payload = utf8.encode('archive fixture'); + final cookies = []; + server.listen((request) async { + cookies.add(request.headers.value('cookie')); + request.response.add(payload); + await request.response.close(); + }); + final uri = Uri.parse('http://127.0.0.1:${server.port}/archive.zip'); + AppUpdate candidate(String digest) => AppUpdate( + versionCode: 12, + versionName: '', + apk: uri, + platform: 'macos', + sha256: digest, + headersFor: (_) => {'Cookie': 'source=second'}, + ); + try { + final file = await io.downloadUpdate( + candidate(sha256.convert(payload).toString()), + directory, + ); + expect(await file.readAsBytes(), payload); + await file.delete(); + await expectLater( + io.downloadUpdate(candidate('0' * 64), directory), + throwsFormatException, + ); + expect(await directory.list().toList(), isEmpty); + expect(cookies, ['source=second', 'source=second']); + } finally { + await server.close(force: true); + await directory.delete(recursive: true); + HttpOverrides.global = previousOverrides; + } + }, + ); + test( + 'desktop metadata rejects wrong architecture, platform and escaped URLs', + () { + final base = Uri.parse('https://host/updates/macos/'); + final value = { + 'versionCode': 42, + 'platform': 'macos', + 'architectures': ['arm64'], + 'file': 'Pipelines-macos-42.zip', + }; + AppUpdate? parse() => AppUpdate.parse( + jsonEncode(value), + base, + platform: 'macos', + architecture: 'arm64', + ); + expect(parse()!.platform, 'macos'); + value['architectures'] = ['x64']; + expect(parse(), isNull); + value['architectures'] = ['arm64']; + value['platform'] = 'linux'; + expect(parse(), isNull); + value['platform'] = 'macos'; + value['file'] = 'https://evil/archive.zip'; + expect(parse(), isNull); + value['file'] = '../archive.zip'; + expect(parse(), isNull); + value['file'] = 'archive.zip'; + value['versionCode'] = 42.5; + expect(parse(), isNull); + }, + ); + test( + 'all saved machines checked with isolated auth without switching active server', + () async { + SharedPreferences.setMockInitialValues({ + 'pipelines.session.v2.first.cookie': 'session=first', + 'pipelines.session.v2.second.cookie': 'session=second', + }); + final a = Uri.parse('wss://first.test/connect'); + final b = Uri.parse('wss://second.test/connect'); + await ServerSession.activateServer(id: 'first', endpoints: [a]); + final calls = []; + final update = await newestServerUpdate( + [ + SavedServer.validated(id: 'first', name: 'Mac', endpoints: ['$a']), + SavedServer.validated(id: 'second', name: 'Linux', endpoints: ['$b']), + SavedServer.validated( + id: 'offline', + name: 'Offline', + endpoints: ['wss://offline.test/connect'], + ), + ], + read: (base, headers) async { + calls.add(base.host); + expect(headers(Uri.parse('https://untrusted.test/')), isEmpty); + if (base.host == 'offline.test') throw StateError('offline'); + final second = base.host == 'second.test'; + expect( + headers(base)['Cookie'], + second ? 'session=second' : 'session=first', + ); + return AppUpdate( + versionCode: second ? 20 : 10, + versionName: '', + apk: base.resolve('pipelines.apk'), + ); + }, + ); + expect(calls, containsAll(['first.test', 'second.test', 'offline.test'])); + expect(update.versionCode, 20); + expect(update.sourceName, 'Linux'); + expect( + update.headersFor!(Uri.parse('https://second.test/'))['Cookie'], + 'session=second', + ); + expect(update.headersFor!(Uri.parse('https://first.test/')), isEmpty); + expect(ServerSession.serverId, 'first'); + expect(ServerSession.headersFor(a)['Cookie'], 'session=first'); + final firstReader = await ServerSession.credentialReader( + id: 'first', + endpoints: [a], + ); + await ServerSession.signOut(); + expect(firstReader(a), isEmpty); + }, + ); +} diff --git a/app/test/features/updates/native_update_dialog_test.dart b/app/test/features/updates/native_update_dialog_test.dart new file mode 100644 index 00000000..68790c99 --- /dev/null +++ b/app/test/features/updates/native_update_dialog_test.dart @@ -0,0 +1,32 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/updates/launch_update_dialog.dart'; + +void main() { + testWidgets('desktop prompt identifies source and archive action', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => TextButton( + onPressed: () => showLaunchUpdateDialog( + context, + web: false, + cupertino: false, + nativePlatform: 'linux', + sourceName: 'Home Linux', + ), + child: const Text('Check'), + ), + ), + ), + ); + await tester.tap(find.text('Check')); + await tester.pumpAndSettle(); + expect(find.textContaining('from Home Linux'), findsOneWidget); + expect(find.textContaining('extract the archive'), findsOneWidget); + expect(find.text('Download'), findsOneWidget); + expect(find.textContaining('Android'), findsNothing); + }); +} diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index 7be1acfc..c185af07 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -1,4 +1,6 @@ import 'health_probe_fixture.dart'; +import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:pipelines_app/features/updates/app_updates.dart'; import 'package:pipelines_app/ui/motion/quick_switch_animation.dart'; import 'package:pipelines_app/ui/motion/animation_speed.dart'; // Standalone fixture entry for real-browser Search result-selection evidence. @@ -793,6 +795,16 @@ Future main() async { useAppUrlStrategy(); final app = PipelinesApp( server: fixtureServer(params), + webPlatform: params['nativeUpdate'] == null ? kIsWeb : false, + androidSupported: params['nativeUpdate'] == null ? null : true, + installedVersionReader: () async => 1, + androidFeedReader: (base) async => AppUpdate( + versionCode: 2, + versionName: '0.1.2', + apk: base.resolve('Pipelines.zip'), + platform: params['nativeUpdate'] ?? 'android', + sourceName: 'Home Linux', + ), client: PipelinesClient(channelFactory: (_) => _FixtureChannel()), cupertino: cupertino, routeInformationProvider: fixtureRouteProvider(opensRoute ? route : null),