From 65995c666afec2dcc494b281684650869e527053 Mon Sep 17 00:00:00 2001 From: bhavit04 Date: Sun, 21 Jun 2026 12:30:39 +0530 Subject: [PATCH 1/5] feat(auth): allow connecting to servers with self-signed certificates Self-hosted instances served behind a self-signed (or otherwise invalid) TLS certificate could not be reached from the app: both the API client and image loading failed certificate validation. Add an opt-in "Allow self-signed certificates" toggle to the advanced sign-in sheet, shown only when a self-hosted server is selected. When enabled it installs an HttpOverrides.global that skips certificate validation, which transparently covers the http-package API client and the dart:io HttpClient used by NetworkImage / extended_image. The preference is persisted in AppSettings and re-applied on startup before the first request, and applied immediately when toggled so the next login already trusts the certificate. The override is a no-op on web, where dart:io networking does not apply. Native media players (the video_player plugin) use their own networking stack and are not affected by this override. Closes #116 Co-Authored-By: Claude Opus 4.8 --- lib/helpers/consts.dart | 7 +++ lib/helpers/http_overrides.dart | 49 +++++++++++++++++++ lib/l10n/app_en.arb | 4 ++ lib/main.dart | 9 ++++ lib/providers/app_settings_notifier.dart | 27 ++++++++++ .../app_settings_notifier.freezed.dart | 43 +++++++++------- lib/providers/app_settings_notifier.g.dart | 3 +- lib/widgets/auth/advanced_sheet.dart | 27 ++++++++-- lib/widgets/auth/auth_card.dart | 16 +++++- test/auth/auth_screen_test.dart | 32 ++++++++++++ test/core/settings_test.dart | 43 ++++++++++++++++ test/helpers/http_overrides_test.dart | 45 +++++++++++++++++ 12 files changed, 282 insertions(+), 23 deletions(-) create mode 100644 lib/helpers/http_overrides.dart create mode 100644 test/helpers/http_overrides_test.dart diff --git a/lib/helpers/consts.dart b/lib/helpers/consts.dart index 30136fdd7..aee6c1eda 100644 --- a/lib/helpers/consts.dart +++ b/lib/helpers/consts.dart @@ -79,6 +79,13 @@ const PREFS_DB_OWNER_USER_ID = 'dbOwnerUserId'; const PREFS_KEEP_DATA_ON_LOGOUT = 'keepDataOnLogout'; const KEEP_DATA_ON_LOGOUT_DEFAULT = true; +/// User preference: trust self-signed/invalid TLS certificates so the app can +/// connect to self-hosted instances behind a self-signed cert. Off by default +/// since it disables certificate validation. Defaults to +/// [ALLOW_SELF_SIGNED_CERTS_DEFAULT]. +const PREFS_ALLOW_SELF_SIGNED_CERTS = 'allowSelfSignedCerts'; +const ALLOW_SELF_SIGNED_CERTS_DEFAULT = false; + /// Secure-storage key for the headless refresh token. const SECURE_STORAGE_REFRESH_TOKEN = 'wger_refresh_token'; diff --git a/lib/helpers/http_overrides.dart b/lib/helpers/http_overrides.dart new file mode 100644 index 000000000..1a6263212 --- /dev/null +++ b/lib/helpers/http_overrides.dart @@ -0,0 +1,49 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:io'; + +import 'package:flutter/foundation.dart'; + +/// [HttpOverrides] that accepts self-signed / otherwise invalid TLS +/// certificates. +/// +/// Installing this as [HttpOverrides.global] makes *every* `dart:io` +/// `HttpClient` skip certificate validation, which transparently covers both +/// the `http` package client used for API calls and the `HttpClient` that +/// `NetworkImage` / `extended_image` use to load images. Native media players +/// (e.g. the `video_player` plugin on Android/iOS) use their own networking +/// stack and are not affected by this override. +class WgerHttpOverrides extends HttpOverrides { + @override + HttpClient createHttpClient(SecurityContext? context) { + return super.createHttpClient(context) + ..badCertificateCallback = (X509Certificate cert, String host, int port) => true; + } +} + +/// Installs or removes [WgerHttpOverrides] based on [allow]. +/// +/// No-op on the web, where `dart:io` networking (and thus [HttpOverrides]) does +/// not apply. Passing `false` restores the default certificate validation. +void applySelfSignedCertOverride(bool allow) { + if (kIsWeb) { + return; + } + HttpOverrides.global = allow ? WgerHttpOverrides() : null; +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b185a7107..3ef67dc4a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -132,6 +132,10 @@ "@serverOptionSelfHostedTitle": {}, "serverOptionSelfHostedDetail": "Connect to your own instance", "@serverOptionSelfHostedDetail": {}, + "allowSelfSignedCertsTitle": "Allow self-signed certificates", + "@allowSelfSignedCertsTitle": {}, + "allowSelfSignedCertsDetail": "Disables TLS certificate validation. Only enable this for a server you trust.", + "@allowSelfSignedCertsDetail": {}, "authOptionPasswordTitle": "Username and password", "@authOptionPasswordTitle": {}, "signInWithToken": "Sign in with token", diff --git a/lib/main.dart b/lib/main.dart index a210da338..a425f1dd7 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -25,7 +25,9 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:wger/core/error_dialogs.dart'; import 'package:wger/core/keys.dart'; +import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/errors.dart'; +import 'package:wger/helpers/http_overrides.dart'; import 'package:wger/helpers/locale.dart'; import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -108,6 +110,13 @@ void main() async { // SharedPreferences to SharedPreferencesAsync migration function await PreferenceHelper.instance.migrationSupportFunctionForSharedPreferences(); + // Install the self-signed certificate override before any network request + // (e.g. the auto-login probe) is made, based on the persisted preference. + final allowSelfSignedCerts = + await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS) ?? + ALLOW_SELF_SIGNED_CERTS_DEFAULT; + applySelfSignedCertOverride(allowSelfSignedCerts); + // Catch errors from Flutter itself (widget build, layout, paint, etc.) FlutterError.onError = (FlutterErrorDetails details) { final stack = details.stack ?? StackTrace.empty; diff --git a/lib/providers/app_settings_notifier.dart b/lib/providers/app_settings_notifier.dart index fc808e119..7b1ae7468 100644 --- a/lib/providers/app_settings_notifier.dart +++ b/lib/providers/app_settings_notifier.dart @@ -25,6 +25,7 @@ import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:wger/helpers/consts.dart'; +import 'package:wger/helpers/http_overrides.dart'; import 'package:wger/helpers/locale.dart'; import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -82,6 +83,10 @@ sealed class AppSettings with _$AppSettings { /// When true, a manual logout keeps the local database on disk instead /// of wiping it, so the same user signing back in resumes incrementally. @Default(KEEP_DATA_ON_LOGOUT_DEFAULT) bool keepDataOnLogout, + + /// When true, TLS certificate validation is disabled so the app can + /// connect to self-hosted instances using a self-signed certificate. + @Default(ALLOW_SELF_SIGNED_CERTS_DEFAULT) bool allowSelfSignedCerts, }) = _AppSettings; } @@ -101,11 +106,13 @@ class AppSettingsNotifier extends _$AppSettingsNotifier { final userLocale = await _loadUserLocale(); final items = await _loadDashboardItems(); final keepDataOnLogout = await _loadKeepDataOnLogout(); + final allowSelfSignedCerts = await _loadAllowSelfSignedCerts(); return AppSettings( themeMode: themeMode, userLocale: userLocale, dashboardItems: items, keepDataOnLogout: keepDataOnLogout, + allowSelfSignedCerts: allowSelfSignedCerts, ); } @@ -191,6 +198,26 @@ class AppSettingsNotifier extends _$AppSettingsNotifier { await _prefs.setBool(PREFS_KEEP_DATA_ON_LOGOUT, value); } + // + // Allow self-signed certificates + // + + Future _loadAllowSelfSignedCerts() async { + final value = + (await _prefs.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS)) ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT; + // Keep the global override in sync with the persisted value so the very + // first HTTP request after build() honours the setting. + applySelfSignedCertOverride(value); + return value; + } + + Future setAllowSelfSignedCerts(bool value) async { + final current = state.asData?.value ?? const AppSettings(); + state = AsyncData(current.copyWith(allowSelfSignedCerts: value)); + applySelfSignedCertOverride(value); + await _prefs.setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, value); + } + // // Dashboard config // diff --git a/lib/providers/app_settings_notifier.freezed.dart b/lib/providers/app_settings_notifier.freezed.dart index 16b0f1020..31ec0b079 100644 --- a/lib/providers/app_settings_notifier.freezed.dart +++ b/lib/providers/app_settings_notifier.freezed.dart @@ -17,7 +17,9 @@ mixin _$AppSettings { ThemeMode get themeMode; List get dashboardItems;/// Locale override. Null means the app follows the system locale. Locale? get userLocale;/// When true, a manual logout keeps the local database on disk instead /// of wiping it, so the same user signing back in resumes incrementally. - bool get keepDataOnLogout; + bool get keepDataOnLogout;/// When true, TLS certificate validation is disabled so the app can +/// connect to self-hosted instances using a self-signed certificate. + bool get allowSelfSignedCerts; /// Create a copy of AppSettings /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -28,16 +30,16 @@ $AppSettingsCopyWith get copyWith => _$AppSettingsCopyWithImpl Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(dashboardItems),userLocale,keepDataOnLogout); +int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(dashboardItems),userLocale,keepDataOnLogout,allowSelfSignedCerts); @override String toString() { - return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale, keepDataOnLogout: $keepDataOnLogout)'; + return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale, keepDataOnLogout: $keepDataOnLogout, allowSelfSignedCerts: $allowSelfSignedCerts)'; } @@ -48,7 +50,7 @@ abstract mixin class $AppSettingsCopyWith<$Res> { factory $AppSettingsCopyWith(AppSettings value, $Res Function(AppSettings) _then) = _$AppSettingsCopyWithImpl; @useResult $Res call({ - ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout + ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout, bool allowSelfSignedCerts }); @@ -65,12 +67,13 @@ class _$AppSettingsCopyWithImpl<$Res> /// Create a copy of AppSettings /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,Object? keepDataOnLogout = null,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,Object? keepDataOnLogout = null,Object? allowSelfSignedCerts = null,}) { return _then(_self.copyWith( themeMode: null == themeMode ? _self.themeMode : themeMode // ignore: cast_nullable_to_non_nullable as ThemeMode,dashboardItems: null == dashboardItems ? _self.dashboardItems : dashboardItems // ignore: cast_nullable_to_non_nullable as List,userLocale: freezed == userLocale ? _self.userLocale : userLocale // ignore: cast_nullable_to_non_nullable as Locale?,keepDataOnLogout: null == keepDataOnLogout ? _self.keepDataOnLogout : keepDataOnLogout // ignore: cast_nullable_to_non_nullable +as bool,allowSelfSignedCerts: null == allowSelfSignedCerts ? _self.allowSelfSignedCerts : allowSelfSignedCerts // ignore: cast_nullable_to_non_nullable as bool, )); } @@ -153,10 +156,10 @@ return $default(_that);case _: /// } /// ``` -@optionalTypeArgs TResult maybeWhen(TResult Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout)? $default,{required TResult orElse(),}) {final _that = this; +@optionalTypeArgs TResult maybeWhen(TResult Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout, bool allowSelfSignedCerts)? $default,{required TResult orElse(),}) {final _that = this; switch (_that) { case _AppSettings() when $default != null: -return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout);case _: +return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout,_that.allowSelfSignedCerts);case _: return orElse(); } @@ -174,10 +177,10 @@ return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keep /// } /// ``` -@optionalTypeArgs TResult when(TResult Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout) $default,) {final _that = this; +@optionalTypeArgs TResult when(TResult Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout, bool allowSelfSignedCerts) $default,) {final _that = this; switch (_that) { case _AppSettings(): -return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout);} +return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout,_that.allowSelfSignedCerts);} } /// A variant of `when` that fallback to returning `null` /// @@ -191,10 +194,10 @@ return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keep /// } /// ``` -@optionalTypeArgs TResult? whenOrNull(TResult? Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout)? $default,) {final _that = this; +@optionalTypeArgs TResult? whenOrNull(TResult? Function( ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout, bool allowSelfSignedCerts)? $default,) {final _that = this; switch (_that) { case _AppSettings() when $default != null: -return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout);case _: +return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keepDataOnLogout,_that.allowSelfSignedCerts);case _: return null; } @@ -206,7 +209,7 @@ return $default(_that.themeMode,_that.dashboardItems,_that.userLocale,_that.keep class _AppSettings implements AppSettings { - const _AppSettings({this.themeMode = ThemeMode.system, final List dashboardItems = const [], this.userLocale, this.keepDataOnLogout = KEEP_DATA_ON_LOGOUT_DEFAULT}): _dashboardItems = dashboardItems; + const _AppSettings({this.themeMode = ThemeMode.system, final List dashboardItems = const [], this.userLocale, this.keepDataOnLogout = KEEP_DATA_ON_LOGOUT_DEFAULT, this.allowSelfSignedCerts = ALLOW_SELF_SIGNED_CERTS_DEFAULT}): _dashboardItems = dashboardItems; @override@JsonKey() final ThemeMode themeMode; @@ -222,6 +225,9 @@ class _AppSettings implements AppSettings { /// When true, a manual logout keeps the local database on disk instead /// of wiping it, so the same user signing back in resumes incrementally. @override@JsonKey() final bool keepDataOnLogout; +/// When true, TLS certificate validation is disabled so the app can +/// connect to self-hosted instances using a self-signed certificate. +@override@JsonKey() final bool allowSelfSignedCerts; /// Create a copy of AppSettings /// with the given fields replaced by the non-null parameter values. @@ -233,16 +239,16 @@ _$AppSettingsCopyWith<_AppSettings> get copyWith => __$AppSettingsCopyWithImpl<_ @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other._dashboardItems, _dashboardItems)&&(identical(other.userLocale, userLocale) || other.userLocale == userLocale)&&(identical(other.keepDataOnLogout, keepDataOnLogout) || other.keepDataOnLogout == keepDataOnLogout)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&const DeepCollectionEquality().equals(other._dashboardItems, _dashboardItems)&&(identical(other.userLocale, userLocale) || other.userLocale == userLocale)&&(identical(other.keepDataOnLogout, keepDataOnLogout) || other.keepDataOnLogout == keepDataOnLogout)&&(identical(other.allowSelfSignedCerts, allowSelfSignedCerts) || other.allowSelfSignedCerts == allowSelfSignedCerts)); } @override -int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(_dashboardItems),userLocale,keepDataOnLogout); +int get hashCode => Object.hash(runtimeType,themeMode,const DeepCollectionEquality().hash(_dashboardItems),userLocale,keepDataOnLogout,allowSelfSignedCerts); @override String toString() { - return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale, keepDataOnLogout: $keepDataOnLogout)'; + return 'AppSettings(themeMode: $themeMode, dashboardItems: $dashboardItems, userLocale: $userLocale, keepDataOnLogout: $keepDataOnLogout, allowSelfSignedCerts: $allowSelfSignedCerts)'; } @@ -253,7 +259,7 @@ abstract mixin class _$AppSettingsCopyWith<$Res> implements $AppSettingsCopyWith factory _$AppSettingsCopyWith(_AppSettings value, $Res Function(_AppSettings) _then) = __$AppSettingsCopyWithImpl; @override @useResult $Res call({ - ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout + ThemeMode themeMode, List dashboardItems, Locale? userLocale, bool keepDataOnLogout, bool allowSelfSignedCerts }); @@ -270,12 +276,13 @@ class __$AppSettingsCopyWithImpl<$Res> /// Create a copy of AppSettings /// with the given fields replaced by the non-null parameter values. -@override @pragma('vm:prefer-inline') $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,Object? keepDataOnLogout = null,}) { +@override @pragma('vm:prefer-inline') $Res call({Object? themeMode = null,Object? dashboardItems = null,Object? userLocale = freezed,Object? keepDataOnLogout = null,Object? allowSelfSignedCerts = null,}) { return _then(_AppSettings( themeMode: null == themeMode ? _self.themeMode : themeMode // ignore: cast_nullable_to_non_nullable as ThemeMode,dashboardItems: null == dashboardItems ? _self._dashboardItems : dashboardItems // ignore: cast_nullable_to_non_nullable as List,userLocale: freezed == userLocale ? _self.userLocale : userLocale // ignore: cast_nullable_to_non_nullable as Locale?,keepDataOnLogout: null == keepDataOnLogout ? _self.keepDataOnLogout : keepDataOnLogout // ignore: cast_nullable_to_non_nullable +as bool,allowSelfSignedCerts: null == allowSelfSignedCerts ? _self.allowSelfSignedCerts : allowSelfSignedCerts // ignore: cast_nullable_to_non_nullable as bool, )); } diff --git a/lib/providers/app_settings_notifier.g.dart b/lib/providers/app_settings_notifier.g.dart index 2a729d42a..85fb2bb6d 100644 --- a/lib/providers/app_settings_notifier.g.dart +++ b/lib/providers/app_settings_notifier.g.dart @@ -33,7 +33,8 @@ final class AppSettingsNotifierProvider AppSettingsNotifier create() => AppSettingsNotifier(); } -String _$appSettingsNotifierHash() => r'fe24b3b36a74af66268086628fe377141e52c8ff'; +String _$appSettingsNotifierHash() => + r'2ba0d53f1a48ba6876571c965e9e804c04be5645'; abstract class _$AppSettingsNotifier extends $AsyncNotifier { FutureOr build(); diff --git a/lib/widgets/auth/advanced_sheet.dart b/lib/widgets/auth/advanced_sheet.dart index 175680e1c..63d9999b4 100644 --- a/lib/widgets/auth/advanced_sheet.dart +++ b/lib/widgets/auth/advanced_sheet.dart @@ -29,9 +29,11 @@ Future showAdvancedSheet({ required BuildContext context, required bool initialHideCustomServer, required bool initialUsePassword, + required bool initialAllowSelfSignedCerts, required bool loginMode, required TextEditingController serverUrlController, - required void Function(bool hideCustomServer, bool usePassword) onChanged, + required void Function(bool hideCustomServer, bool usePassword, bool allowSelfSignedCerts) + onChanged, }) { return showModalBottomSheet( context: context, @@ -40,6 +42,7 @@ Future showAdvancedSheet({ builder: (_) => AdvancedSheet( initialHideCustomServer: initialHideCustomServer, initialUsePassword: initialUsePassword, + initialAllowSelfSignedCerts: initialAllowSelfSignedCerts, loginMode: loginMode, serverUrlController: serverUrlController, onChanged: onChanged, @@ -50,13 +53,15 @@ Future showAdvancedSheet({ class AdvancedSheet extends StatefulWidget { final bool initialHideCustomServer; final bool initialUsePassword; + final bool initialAllowSelfSignedCerts; final bool loginMode; final TextEditingController serverUrlController; - final void Function(bool hideCustomServer, bool usePassword) onChanged; + final void Function(bool hideCustomServer, bool usePassword, bool allowSelfSignedCerts) onChanged; const AdvancedSheet({ required this.initialHideCustomServer, required this.initialUsePassword, + required this.initialAllowSelfSignedCerts, required this.loginMode, required this.serverUrlController, required this.onChanged, @@ -70,6 +75,7 @@ class AdvancedSheet extends StatefulWidget { class _AdvancedSheetState extends State { late bool _hideCustomServer; late bool _usePassword; + late bool _allowSelfSignedCerts; final _formKey = GlobalKey(); @override @@ -77,11 +83,12 @@ class _AdvancedSheetState extends State { super.initState(); _hideCustomServer = widget.initialHideCustomServer; _usePassword = widget.initialUsePassword; + _allowSelfSignedCerts = widget.initialAllowSelfSignedCerts; } void _set(VoidCallback change) { setState(change); - widget.onChanged(_hideCustomServer, _usePassword); + widget.onChanged(_hideCustomServer, _usePassword, _allowSelfSignedCerts); } @override @@ -151,6 +158,20 @@ class _AdvancedSheetState extends State { padding: const EdgeInsets.only(top: 2, bottom: 4), child: ServerField(controller: widget.serverUrlController), ), + if (!_hideCustomServer) + SwitchListTile( + key: const Key('allowSelfSignedCertsSwitch'), + contentPadding: EdgeInsets.zero, + title: Text(i18n.allowSelfSignedCertsTitle), + subtitle: Text( + i18n.allowSelfSignedCertsDetail, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ), + value: _allowSelfSignedCerts, + onChanged: (value) => _set(() => _allowSelfSignedCerts = value), + ), if (widget.loginMode) ...[ _SectionLabel(text: i18n.signInMethodSectionLabel), _OptionRow( diff --git a/lib/widgets/auth/auth_card.dart b/lib/widgets/auth/auth_card.dart index bd1a08c2d..e7d706488 100644 --- a/lib/widgets/auth/auth_card.dart +++ b/lib/widgets/auth/auth_card.dart @@ -27,6 +27,7 @@ import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/errors.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/providers/app_link_router.dart'; +import 'package:wger/providers/app_settings_notifier.dart'; import 'package:wger/providers/auth_notifier.dart'; import 'package:wger/providers/auth_state.dart'; import 'package:wger/providers/network_provider.dart'; @@ -69,6 +70,7 @@ class _AuthCardState extends ConsumerState { bool _autoValidate = false; bool _hideCustomServer = true; bool _useUsernameAndPassword = true; + bool _allowSelfSignedCerts = ALLOW_SELF_SIGNED_CERTS_DEFAULT; var _isLoading = false; final _usernameController = TextEditingController(); @@ -105,6 +107,13 @@ class _AuthCardState extends ConsumerState { } }); + // Surface the persisted self-signed-cert preference in the advanced sheet. + ref.read(appSettingsProvider.future).then((settings) { + if (mounted) { + setState(() => _allowSelfSignedCerts = settings.allowSelfSignedCerts); + } + }); + _preFillTextFields(); } @@ -252,13 +261,18 @@ class _AuthCardState extends ConsumerState { context: context, initialHideCustomServer: _hideCustomServer, initialUsePassword: _useUsernameAndPassword, + initialAllowSelfSignedCerts: _allowSelfSignedCerts, loginMode: _authMode == AuthMode.login, serverUrlController: _serverUrlController, - onChanged: (hideCustomServer, usePassword) { + onChanged: (hideCustomServer, usePassword, allowSelfSignedCerts) { setState(() { _hideCustomServer = hideCustomServer; _useUsernameAndPassword = usePassword; + _allowSelfSignedCerts = allowSelfSignedCerts; }); + // Persist immediately and install the override so the next login + // request (still made from this screen) trusts the self-signed cert. + ref.read(appSettingsProvider.notifier).setAllowSelfSignedCerts(allowSelfSignedCerts); }, ).then((_) { if (mounted) { diff --git a/test/auth/auth_screen_test.dart b/test/auth/auth_screen_test.dart index 02a1218ee..12572215f 100644 --- a/test/auth/auth_screen_test.dart +++ b/test/auth/auth_screen_test.dart @@ -17,6 +17,7 @@ */ import 'dart:convert'; +import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -544,6 +545,37 @@ void main() { expect(find.text('http://localhost:8000'), findsNothing); }); + testWidgets('Self-hosted exposes the self-signed-cert toggle and persists it', ( + WidgetTester tester, + ) async { + // Toggling the switch installs a global HttpOverrides; undo it so the + // override does not leak into later tests in this isolate. + addTearDown(() => HttpOverrides.global = null); + + await tester.binding.setSurfaceSize(const Size(1080, 1920)); + tester.view.devicePixelRatio = 1.0; + await tester.pumpWidget(getWidget()); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + + // The toggle only exists once a self-hosted server is selected. + final toggle = find.byKey(const Key('allowSelfSignedCertsSwitch')); + expect(toggle, findsNothing); + await tester.tap(find.text('Self-hosted')); + await tester.pumpAndSettle(); + expect(toggle, findsOneWidget); + + await tester.tap(toggle); + await tester.pumpAndSettle(); + + expect( + await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), + isTrue, + ); + }); + testWidgets('Sheet pre-selects Self-hosted for a custom last-used server', ( WidgetTester tester, ) async { diff --git a/test/core/settings_test.dart b/test/core/settings_test.dart index 2de004f31..a1ee7dec4 100644 --- a/test/core/settings_test.dart +++ b/test/core/settings_test.dart @@ -167,6 +167,49 @@ void main() { }); }); + group('Allow-self-signed-certs (AppSettingsNotifier)', () { + riverpod.ProviderContainer makeContainer() { + final container = riverpod.ProviderContainer( + overrides: [ + appSettingsPrefsProvider.overrideWithValue(mockSharedPreferences), + ], + ); + addTearDown(container.dispose); + return container; + } + + test('defaults to false', () async { + when( + mockSharedPreferences.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), + ).thenAnswer((_) async => null); + + final settings = await makeContainer().read(appSettingsProvider.future); + expect(settings.allowSelfSignedCerts, false); + }); + + test('loads true from prefs', () async { + when( + mockSharedPreferences.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), + ).thenAnswer((_) async => true); + + final settings = await makeContainer().read(appSettingsProvider.future); + expect(settings.allowSelfSignedCerts, true); + }); + + test('persists the toggle', () async { + when( + mockSharedPreferences.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), + ).thenAnswer((_) async => null); + final container = makeContainer(); + + await container.read(appSettingsProvider.future); + await container.read(appSettingsProvider.notifier).setAllowSelfSignedCerts(true); + + expect(container.read(appSettingsProvider).requireValue.allowSelfSignedCerts, true); + verify(mockSharedPreferences.setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, true)).called(1); + }); + }); + group('Language switcher', () { testWidgets('shows system option when no override set', (WidgetTester tester) async { await tester.pumpWidget(createSettingsScreen()); diff --git a/test/helpers/http_overrides_test.dart b/test/helpers/http_overrides_test.dart new file mode 100644 index 000000000..563184909 --- /dev/null +++ b/test/helpers/http_overrides_test.dart @@ -0,0 +1,45 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/helpers/http_overrides.dart'; + +void main() { + // Restore the default networking after each test so we don't leak the + // certificate override into other tests sharing the same isolate. + final HttpOverrides? original = HttpOverrides.current; + tearDown(() => HttpOverrides.global = original); + + test('applySelfSignedCertOverride(true) installs WgerHttpOverrides', () { + applySelfSignedCertOverride(true); + expect(HttpOverrides.current, isA()); + }); + + test('applySelfSignedCertOverride(false) removes the override', () { + applySelfSignedCertOverride(true); + applySelfSignedCertOverride(false); + expect(HttpOverrides.current, isNull); + }); + + test('WgerHttpOverrides creates a usable HttpClient', () { + final client = WgerHttpOverrides().createHttpClient(null); + expect(client, isA()); + }); +} From 3a574795850eae5461a440532840e2f08c277873 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 13:57:41 +0200 Subject: [PATCH 2/5] Scope the self-signed setting to one host and apply without a restart --- lib/core/app_settings_notifier.dart | 8 +- lib/core/http_overrides.dart | 65 +++++++++++--- lib/core/network/auth_notifier.dart | 6 ++ lib/features/auth/widgets/advanced_sheet.dart | 31 ++++--- lib/main.dart | 12 ++- test/core/http_overrides_test.dart | 87 ++++++++++++++++--- .../auth/screens/auth_screen_test.dart | 30 +++++-- 7 files changed, 184 insertions(+), 55 deletions(-) diff --git a/lib/core/app_settings_notifier.dart b/lib/core/app_settings_notifier.dart index 2f3225bf5..8be792443 100644 --- a/lib/core/app_settings_notifier.dart +++ b/lib/core/app_settings_notifier.dart @@ -205,16 +205,16 @@ class AppSettingsNotifier extends _$AppSettingsNotifier { Future _loadAllowSelfSignedCerts() async { final value = (await _prefs.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS)) ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT; - // Keep the global override in sync with the persisted value so the very - // first HTTP request after build() honours the setting. - applySelfSignedCertOverride(value); + // The override reads a static, so mirror the setting on both load and write + // and it can never drift from this provider. + WgerHttpOverrides.allowSelfSignedCerts = value; return value; } Future setAllowSelfSignedCerts(bool value) async { final current = state.asData?.value ?? const AppSettings(); state = AsyncData(current.copyWith(allowSelfSignedCerts: value)); - applySelfSignedCertOverride(value); + WgerHttpOverrides.allowSelfSignedCerts = value; await _prefs.setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, value); } diff --git a/lib/core/http_overrides.dart b/lib/core/http_overrides.dart index 1a6263212..6f8d49baf 100644 --- a/lib/core/http_overrides.dart +++ b/lib/core/http_overrides.dart @@ -19,31 +19,68 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; +import 'package:wger/core/consts.dart'; -/// [HttpOverrides] that accepts self-signed / otherwise invalid TLS -/// certificates. +/// [HttpOverrides] that accepts a self-signed / otherwise invalid TLS +/// certificate, but only from [trustedHost] and only while +/// [allowSelfSignedCerts] is set. /// -/// Installing this as [HttpOverrides.global] makes *every* `dart:io` -/// `HttpClient` skip certificate validation, which transparently covers both -/// the `http` package client used for API calls and the `HttpClient` that -/// `NetworkImage` / `extended_image` use to load images. Native media players +/// Installed as [HttpOverrides.global], so every `dart:io` `HttpClient` routes +/// through it: both the `http` package client used for API calls and the +/// `HttpClient` behind `NetworkImage` / `extended_image`. Native media players /// (e.g. the `video_player` plugin on Android/iOS) use their own networking -/// stack and are not affected by this override. +/// stack and are not affected. class WgerHttpOverrides extends HttpOverrides { + /// Whether the user opted into trusting an invalid certificate. + /// + /// Both this and [trustedHost] are read when the handshake happens rather + /// than when the client is built, so changing either also applies to clients + /// that already exist. dart:io reads [HttpOverrides.current] once in the + /// `HttpClient` constructor, and the auth client is built during startup, so + /// swapping the override itself would only take effect after a restart. + static bool allowSelfSignedCerts = ALLOW_SELF_SIGNED_CERTS_DEFAULT; + + /// Host the opt-in applies to. While null, every invalid certificate is + /// rejected no matter what [allowSelfSignedCerts] says. + static String? trustedHost; + + /// Narrows [trustedHost] to the host of [serverUrl]. A null, empty or + /// hostless URL clears it. + static void trustServer(String? serverUrl) { + final host = serverUrl == null ? null : Uri.tryParse(serverUrl)?.host; + trustedHost = (host == null || host.isEmpty) ? null : host; + } + + /// Hosts the opt-in can never apply to. The servers we run ourselves have a + /// valid certificate, so an invalid one there is a genuine problem and not + /// something a self-hosting setting may wave through. + static final Set _officialHosts = { + Uri.parse(DEFAULT_SERVER_PROD).host, + Uri.parse(DEFAULT_SERVER_TEST).host, + }; + + /// Whether an invalid certificate presented by [host] is accepted. + /// + /// Installed as the `badCertificateCallback` of every client, so it runs per + /// handshake and sees the current [allowSelfSignedCerts] / [trustedHost] + /// rather than the values from when the client was built. + static bool acceptsBadCertificate(X509Certificate cert, String host, int port) => + allowSelfSignedCerts && host == trustedHost && !_officialHosts.contains(host); + @override HttpClient createHttpClient(SecurityContext? context) { - return super.createHttpClient(context) - ..badCertificateCallback = (X509Certificate cert, String host, int port) => true; + return super.createHttpClient(context)..badCertificateCallback = acceptsBadCertificate; } } -/// Installs or removes [WgerHttpOverrides] based on [allow]. +/// Routes all `dart:io` HTTP traffic through [WgerHttpOverrides]. /// -/// No-op on the web, where `dart:io` networking (and thus [HttpOverrides]) does -/// not apply. Passing `false` restores the default certificate validation. -void applySelfSignedCertOverride(bool allow) { +/// Must run before the first `HttpClient` is created, since dart:io only +/// consults [HttpOverrides.current] in the client constructor. No-op on the +/// web, where `dart:io` networking (and thus [HttpOverrides]) does not apply. +void installHttpOverrides() { if (kIsWeb) { return; } - HttpOverrides.global = allow ? WgerHttpOverrides() : null; + HttpOverrides.global = WgerHttpOverrides(); } diff --git a/lib/core/network/auth_notifier.dart b/lib/core/network/auth_notifier.dart index 99879f60f..e53dad9a5 100644 --- a/lib/core/network/auth_notifier.dart +++ b/lib/core/network/auth_notifier.dart @@ -33,6 +33,7 @@ import 'package:wger/core/errors.dart'; import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/core/exceptions/mfa_required_exception.dart'; import 'package:wger/core/helpers.dart'; +import 'package:wger/core/http_overrides.dart'; import 'package:wger/core/network/auth_credentials_storage.dart'; import 'package:wger/core/network/auth_http_client.dart'; import 'package:wger/core/network/auth_state.dart'; @@ -198,6 +199,11 @@ class AuthNotifier extends _$AuthNotifier { String serverUrl, PackageInfo appVersion, ) async { + // Narrow the certificate opt-in to the server we are about to talk to. This + // is the single point every auth entry point passes through, and it runs + // before the first request to that host. + WgerHttpOverrides.trustServer(serverUrl); + final gate = await _gating.serverVersionGate(serverUrl); if (gate.tooOld) { _logger.info('login blocked: server ${gate.version} below $MIN_SERVER_VERSION'); diff --git a/lib/features/auth/widgets/advanced_sheet.dart b/lib/features/auth/widgets/advanced_sheet.dart index 0fea90a9f..01251621e 100644 --- a/lib/features/auth/widgets/advanced_sheet.dart +++ b/lib/features/auth/widgets/advanced_sheet.dart @@ -158,20 +158,27 @@ class _AdvancedSheetState extends State { padding: const EdgeInsets.only(top: 2, bottom: 4), child: ServerField(controller: widget.serverUrlController), ), - if (!_hideCustomServer) - SwitchListTile( - key: const Key('allowSelfSignedCertsSwitch'), - contentPadding: EdgeInsets.zero, - title: Text(i18n.allowSelfSignedCertsTitle), - subtitle: Text( - i18n.allowSelfSignedCertsDetail, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.error, - ), + // Stays visible for the official server so the option is + // discoverable, but disabled: wger.de has a valid certificate and + // is never trusted through this setting. The stored preference is + // kept, so switching back to self-hosted restores it. + SwitchListTile( + key: const Key('allowSelfSignedCertsSwitch'), + contentPadding: EdgeInsets.zero, + title: Text(i18n.allowSelfSignedCertsTitle), + subtitle: Text( + i18n.allowSelfSignedCertsDetail, + style: theme.textTheme.bodySmall?.copyWith( + color: _hideCustomServer + ? theme.colorScheme.onSurfaceVariant + : theme.colorScheme.error, ), - value: _allowSelfSignedCerts, - onChanged: (value) => _set(() => _allowSelfSignedCerts = value), ), + value: !_hideCustomServer && _allowSelfSignedCerts, + onChanged: _hideCustomServer + ? null + : (value) => _set(() => _allowSelfSignedCerts = value), + ), if (widget.loginMode) ...[ _SectionLabel(text: i18n.signInMethodSectionLabel), _OptionRow( diff --git a/lib/main.dart b/lib/main.dart index a75df6882..ea966a53a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -101,6 +101,10 @@ void main() async { // Needs to be called before runApp WidgetsFlutterBinding.ensureInitialized(); + // Has to happen before anything creates an HttpClient: dart:io only reads + // HttpOverrides.current in the client constructor, never again. + installHttpOverrides(); + // Logger _setupLogging(); @@ -109,12 +113,12 @@ void main() async { // SharedPreferences to SharedPreferencesAsync migration function await PreferenceHelper.instance.migrationSupportFunctionForSharedPreferences(); - // Install the self-signed certificate override before any network request - // (e.g. the auto-login probe) is made, based on the persisted preference. - final allowSelfSignedCerts = + // Seed the certificate opt-in from the prefs so the auto-login probe already + // honours it; AppSettingsNotifier keeps it in sync from here on. + WgerHttpOverrides.allowSelfSignedCerts = await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS) ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT; - applySelfSignedCertOverride(allowSelfSignedCerts); + WgerHttpOverrides.trustServer(await AuthNotifier.getServerUrlFromPrefs()); // Catch errors from Flutter itself (widget build, layout, paint, etc.) FlutterError.onError = (FlutterErrorDetails details) { diff --git a/test/core/http_overrides_test.dart b/test/core/http_overrides_test.dart index 0b588ac79..0b55dbd73 100644 --- a/test/core/http_overrides_test.dart +++ b/test/core/http_overrides_test.dart @@ -19,27 +19,86 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/core/consts.dart'; import 'package:wger/core/http_overrides.dart'; -void main() { - // Restore the default networking after each test so we don't leak the - // certificate override into other tests sharing the same isolate. - final HttpOverrides? original = HttpOverrides.current; - tearDown(() => HttpOverrides.global = original); +class _FakeCertificate extends Fake implements X509Certificate {} - test('applySelfSignedCertOverride(true) installs WgerHttpOverrides', () { - applySelfSignedCertOverride(true); +void main() { + final cert = _FakeCertificate(); + + // Restore the default networking and the opt-in so nothing leaks into other + // tests sharing the same isolate. The test binding installs its own overrides + // to keep tests off the network, so put back what was there rather than null. + final HttpOverrides? originalOverrides = HttpOverrides.current; + tearDown(() { + HttpOverrides.global = originalOverrides; + WgerHttpOverrides.allowSelfSignedCerts = false; + WgerHttpOverrides.trustedHost = null; + }); + + /// The decision the TLS handshake would make for [host]. + bool accepts(String host) => WgerHttpOverrides.acceptsBadCertificate(cert, host, 443); + + test('installHttpOverrides routes traffic through WgerHttpOverrides', () { + installHttpOverrides(); expect(HttpOverrides.current, isA()); }); - test('applySelfSignedCertOverride(false) removes the override', () { - applySelfSignedCertOverride(true); - applySelfSignedCertOverride(false); - expect(HttpOverrides.current, isNull); + test('rejects a bad certificate by default', () { + expect(accepts('gym.example.com'), isFalse); }); - test('WgerHttpOverrides creates a usable HttpClient', () { - final client = WgerHttpOverrides().createHttpClient(null); - expect(client, isA()); + test('accepts the trusted host once opted in', () { + WgerHttpOverrides.allowSelfSignedCerts = true; + WgerHttpOverrides.trustServer('https://gym.example.com:8000'); + + expect(accepts('gym.example.com'), isTrue); + }); + + test('rejects any other host while opted in', () { + WgerHttpOverrides.allowSelfSignedCerts = true; + WgerHttpOverrides.trustServer('https://gym.example.com'); + + expect(accepts('other.example.com'), isFalse); + }); + + test('never trusts the official servers, even when they are the trusted host', () { + // Reachable by typing wger.de into the self-hosted field with the opt-in on. + WgerHttpOverrides.allowSelfSignedCerts = true; + + for (final url in [DEFAULT_SERVER_PROD, DEFAULT_SERVER_TEST]) { + WgerHttpOverrides.trustServer(url); + expect(accepts(Uri.parse(url).host), isFalse, reason: 'for $url'); + } + }); + + test('rejects the trusted host again once opted out', () { + WgerHttpOverrides.trustServer('https://gym.example.com'); + WgerHttpOverrides.allowSelfSignedCerts = true; + WgerHttpOverrides.allowSelfSignedCerts = false; + + expect(accepts('gym.example.com'), isFalse); + }); + + test('the decision is re-read per call, not baked in when it is handed out', () { + // The regression that matters: dart:io reads HttpOverrides.current in the + // HttpClient constructor only, and the auth client is built during startup. + // A client therefore holds this callback from before the user can opt in, + // exactly like the reference grabbed here. + const held = WgerHttpOverrides.acceptsBadCertificate; + expect(held(cert, 'gym.example.com', 443), isFalse); + + WgerHttpOverrides.allowSelfSignedCerts = true; + WgerHttpOverrides.trustServer('https://gym.example.com'); + + expect(held(cert, 'gym.example.com', 443), isTrue); + }); + + test('trustServer clears the host for a null, empty or hostless URL', () { + for (final url in [null, '', 'not a url']) { + WgerHttpOverrides.trustServer(url); + expect(WgerHttpOverrides.trustedHost, isNull, reason: 'for ${url ?? 'null'}'); + } }); } diff --git a/test/features/auth/screens/auth_screen_test.dart b/test/features/auth/screens/auth_screen_test.dart index caa9708d6..76bfd8e1b 100644 --- a/test/features/auth/screens/auth_screen_test.dart +++ b/test/features/auth/screens/auth_screen_test.dart @@ -17,7 +17,6 @@ */ import 'dart:convert'; -import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -33,6 +32,7 @@ import 'package:shared_preferences_platform_interface/in_memory_shared_preferenc import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'package:wger/core/consts.dart'; +import 'package:wger/core/http_overrides.dart'; import 'package:wger/core/network/auth_notifier.dart'; import 'package:wger/core/network/network_provider.dart'; import 'package:wger/core/network/secure_token_storage.dart'; @@ -556,9 +556,9 @@ void main() { testWidgets('Self-hosted exposes the self-signed-cert toggle and persists it', ( WidgetTester tester, ) async { - // Toggling the switch installs a global HttpOverrides; undo it so the - // override does not leak into later tests in this isolate. - addTearDown(() => HttpOverrides.global = null); + // Toggling the switch flips a static the override reads; reset it so it + // does not leak into later tests in this isolate. + addTearDown(() => WgerHttpOverrides.allowSelfSignedCerts = false); await tester.binding.setSurfaceSize(const Size(1080, 1920)); tester.view.devicePixelRatio = 1.0; @@ -568,12 +568,15 @@ void main() { await tester.tap(find.byKey(const Key('advancedButton'))); await tester.pumpAndSettle(); - // The toggle only exists once a self-hosted server is selected. + // Visible for the official server, but off and not interactive. final toggle = find.byKey(const Key('allowSelfSignedCertsSwitch')); - expect(toggle, findsNothing); + expect(toggle, findsOneWidget); + expect(tester.widget(toggle).onChanged, isNull); + expect(tester.widget(toggle).value, isFalse); + await tester.tap(find.text('Self-hosted')); await tester.pumpAndSettle(); - expect(toggle, findsOneWidget); + expect(tester.widget(toggle).onChanged, isNotNull); await tester.tap(toggle); await tester.pumpAndSettle(); @@ -582,6 +585,19 @@ void main() { await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), isTrue, ); + expect(WgerHttpOverrides.allowSelfSignedCerts, isTrue); + + // Back on the official server it reads as off again, while the stored + // preference survives for the next self-hosted login. + await tester.tap(find.text('wger.de')); + await tester.pumpAndSettle(); + + expect(tester.widget(toggle).value, isFalse); + expect(tester.widget(toggle).onChanged, isNull); + expect( + await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), + isTrue, + ); }); testWidgets('Sheet pre-selects Self-hosted for a custom last-used server', ( From 0ecd06ff3c5ed323de76cce1fe3208b43840930a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 14:06:19 +0200 Subject: [PATCH 3/5] Read the certificate setting from the provider instead of mirroring it --- lib/features/auth/widgets/auth_card.dart | 31 +++++++++---------- .../auth/screens/auth_screen_test.dart | 11 +++++++ 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/lib/features/auth/widgets/auth_card.dart b/lib/features/auth/widgets/auth_card.dart index aa3373adf..1d735abb2 100644 --- a/lib/features/auth/widgets/auth_card.dart +++ b/lib/features/auth/widgets/auth_card.dart @@ -70,7 +70,6 @@ class _AuthCardState extends ConsumerState { bool _autoValidate = false; bool _hideCustomServer = true; bool _useUsernameAndPassword = true; - bool _allowSelfSignedCerts = ALLOW_SELF_SIGNED_CERTS_DEFAULT; var _isLoading = false; final _usernameController = TextEditingController(); @@ -107,13 +106,6 @@ class _AuthCardState extends ConsumerState { } }); - // Surface the persisted self-signed-cert preference in the advanced sheet. - ref.read(appSettingsProvider.future).then((settings) { - if (mounted) { - setState(() => _allowSelfSignedCerts = settings.allowSelfSignedCerts); - } - }); - _preFillTextFields(); } @@ -256,23 +248,25 @@ class _AuthCardState extends ConsumerState { } /// Opens the advanced bottom sheet (server + sign-in-method selection). - void _showAdvancedSheet() { + /// + /// [allowSelfSignedCerts] is the persisted setting, passed in from `build` so + /// the sheet opens on the current value. + void _showAdvancedSheet(bool allowSelfSignedCerts) { showAdvancedSheet( context: context, initialHideCustomServer: _hideCustomServer, initialUsePassword: _useUsernameAndPassword, - initialAllowSelfSignedCerts: _allowSelfSignedCerts, + initialAllowSelfSignedCerts: allowSelfSignedCerts, loginMode: _authMode == AuthMode.login, serverUrlController: _serverUrlController, - onChanged: (hideCustomServer, usePassword, allowSelfSignedCerts) { + onChanged: (hideCustomServer, usePassword, allowSelfSigned) { setState(() { _hideCustomServer = hideCustomServer; _useUsernameAndPassword = usePassword; - _allowSelfSignedCerts = allowSelfSignedCerts; }); - // Persist immediately and install the override so the next login - // request (still made from this screen) trusts the self-signed cert. - ref.read(appSettingsProvider.notifier).setAllowSelfSignedCerts(allowSelfSignedCerts); + // Persist immediately so the next login request, still made from this + // screen, already trusts the certificate. + ref.read(appSettingsProvider.notifier).setAllowSelfSignedCerts(allowSelfSigned); }, ).then((_) { if (mounted) { @@ -288,6 +282,11 @@ class _AuthCardState extends ConsumerState { // Login/registration both need the server, so disable the action while // there is no connectivity. final isOnline = ref.watch(networkStatusProvider); + final allowSelfSignedCerts = ref.watch( + appSettingsProvider.select( + (s) => s.value?.allowSelfSignedCerts ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT, + ), + ); Widget errorMessage = const SizedBox.shrink(); if (_httpError != null) { @@ -391,7 +390,7 @@ class _AuthCardState extends ConsumerState { isCustomServer: !_hideCustomServer, isTokenMode: _authMode == AuthMode.login && !_useUsernameAndPassword, serverUrl: _serverUrlController.text, - onTap: _showAdvancedSheet, + onTap: () => _showAdvancedSheet(allowSelfSignedCerts), ), ], ), diff --git a/test/features/auth/screens/auth_screen_test.dart b/test/features/auth/screens/auth_screen_test.dart index 76bfd8e1b..4b8f0dd5b 100644 --- a/test/features/auth/screens/auth_screen_test.dart +++ b/test/features/auth/screens/auth_screen_test.dart @@ -598,6 +598,17 @@ void main() { await PreferenceHelper.asyncPref.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), isTrue, ); + + // Reopening seeds the sheet from the provider, so the earlier opt-in is + // still there for a self-hosted server. + await tester.tap(find.byKey(const Key('advancedCloseButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('advancedButton'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Self-hosted')); + await tester.pumpAndSettle(); + + expect(tester.widget(toggle).value, isTrue); }); testWidgets('Sheet pre-selects Self-hosted for a custom last-used server', ( From 1a58dd8f71bd9bcb033491edd21fdc1a0cdff9c5 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 14:23:37 +0200 Subject: [PATCH 4/5] Warn in the settings while certificates are not being verified --- lib/core/http_overrides.dart | 27 ++++- lib/features/account/widgets/settings.dart | 4 + .../widgets/settings/certs_not_verified.dart | 63 +++++++++++ lib/l10n/app_de.arb | 6 +- lib/l10n/app_en.arb | 14 +++ lib/l10n/app_es.arb | 6 +- lib/l10n/app_fr.arb | 6 +- test/core/http_overrides_test.dart | 23 ++++ .../settings/certs_not_verified_test.dart | 107 ++++++++++++++++++ 9 files changed, 247 insertions(+), 9 deletions(-) create mode 100644 lib/features/account/widgets/settings/certs_not_verified.dart create mode 100644 test/features/account/widgets/settings/certs_not_verified_test.dart diff --git a/lib/core/http_overrides.dart b/lib/core/http_overrides.dart index 6f8d49baf..5cf51ed36 100644 --- a/lib/core/http_overrides.dart +++ b/lib/core/http_overrides.dart @@ -46,10 +46,7 @@ class WgerHttpOverrides extends HttpOverrides { /// Narrows [trustedHost] to the host of [serverUrl]. A null, empty or /// hostless URL clears it. - static void trustServer(String? serverUrl) { - final host = serverUrl == null ? null : Uri.tryParse(serverUrl)?.host; - trustedHost = (host == null || host.isEmpty) ? null : host; - } + static void trustServer(String? serverUrl) => trustedHost = _hostOf(serverUrl); /// Hosts the opt-in can never apply to. The servers we run ourselves have a /// valid certificate, so an invalid one there is a genuine problem and not @@ -59,13 +56,31 @@ class WgerHttpOverrides extends HttpOverrides { Uri.parse(DEFAULT_SERVER_TEST).host, }; + static String? _hostOf(String? serverUrl) { + final host = serverUrl == null ? null : Uri.tryParse(serverUrl)?.host; + return (host == null || host.isEmpty) ? null : host; + } + + static bool _accepts(String host) => + allowSelfSignedCerts && host == trustedHost && !_officialHosts.contains(host); + /// Whether an invalid certificate presented by [host] is accepted. /// /// Installed as the `badCertificateCallback` of every client, so it runs per /// handshake and sees the current [allowSelfSignedCerts] / [trustedHost] /// rather than the values from when the client was built. - static bool acceptsBadCertificate(X509Certificate cert, String host, int port) => - allowSelfSignedCerts && host == trustedHost && !_officialHosts.contains(host); + static bool acceptsBadCertificate(X509Certificate cert, String host, int port) => _accepts(host); + + /// The host of [serverUrl] while it is exempt from certificate validation, + /// null otherwise. + /// + /// Answers the same question as [acceptsBadCertificate], so a UI built on this + /// cannot warn about an exemption that does not exist, or stay silent about + /// one that does. + static String? exemptHost(String? serverUrl) { + final host = _hostOf(serverUrl); + return (host != null && _accepts(host)) ? host : null; + } @override HttpClient createHttpClient(SecurityContext? context) { diff --git a/lib/features/account/widgets/settings.dart b/lib/features/account/widgets/settings.dart index 697e3bf4e..d8cc3cee9 100644 --- a/lib/features/account/widgets/settings.dart +++ b/lib/features/account/widgets/settings.dart @@ -18,6 +18,7 @@ import 'package:flutter/material.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; +import 'package:wger/features/account/widgets/settings/certs_not_verified.dart'; import 'package:wger/features/account/widgets/settings/data_privacy.dart'; import 'package:wger/features/account/widgets/settings/image_cache.dart'; import 'package:wger/features/account/widgets/settings/language.dart'; @@ -39,6 +40,9 @@ class SettingsPage extends StatelessWidget { body: WidescreenWrapper( child: ListView( children: [ + // Collapses to nothing unless certificates are actually going + // unverified, so it sits above the first section rather than in one. + const SettingsCertsNotVerified(), ListTile( title: Text( i18n.settingsCacheTitle, diff --git a/lib/features/account/widgets/settings/certs_not_verified.dart b/lib/features/account/widgets/settings/certs_not_verified.dart new file mode 100644 index 000000000..869dd999c --- /dev/null +++ b/lib/features/account/widgets/settings/certs_not_verified.dart @@ -0,0 +1,63 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/core/app_settings_notifier.dart'; +import 'package:wger/core/consts.dart'; +import 'package:wger/core/http_overrides.dart'; +import 'package:wger/core/network/auth_notifier.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Warns that invalid TLS certificates are currently being accepted, naming the +/// host it applies to. Renders nothing while certificates are verified normally. +/// +/// Read-only on purpose: the opt-in belongs to the login screen. Switching it off +/// here would cut the connection to the very server the user is logged into, and +/// getting back in would need a logout anyway. +class SettingsCertsNotVerified extends ConsumerWidget { + const SettingsCertsNotVerified({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final i18n = AppLocalizations.of(context); + final theme = Theme.of(context); + + // The opt-in is watched to rebuild on a change; whether it actually takes + // effect for this server is up to the override. + final allowSelfSignedCerts = ref.watch( + appSettingsProvider.select( + (s) => s.value?.allowSelfSignedCerts ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT, + ), + ); + final serverUrl = ref.watch(authProvider.select((s) => s.value?.serverUrl)); + final host = allowSelfSignedCerts ? WgerHttpOverrides.exemptHost(serverUrl) : null; + + if (host == null) { + return const SizedBox.shrink(); + } + + return ListTile( + textColor: theme.colorScheme.error, + key: const ValueKey('certsNotVerifiedWarning'), + leading: Icon(Icons.gpp_bad_outlined, color: theme.colorScheme.error), + title: Text(i18n.certsNotVerifiedTitle), + subtitle: Text(i18n.certsNotVerifiedDetail(host)), + ); + } +} diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 9c882bf79..b9844e330 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1162,5 +1162,9 @@ "gymModeLogScopeCurrentRoutine": "Aktuelle Routine", "gymModeLogScopeWeeks": "Letzte {weeks} Wochen", "gymModeDistinctLogs": "Doppelte Werte ausblenden", - "gymModeShowWorkoutDuration": "Trainingsdauer anzeigen" + "gymModeShowWorkoutDuration": "Trainingsdauer anzeigen", + "allowSelfSignedCertsTitle": "Selbstsignierte Zertifikate erlauben", + "allowSelfSignedCertsDetail": "Deaktiviert die Validierung des TLS-Zertifikats. Aktiviere das nur für einen Server, dem du vertraust.", + "certsNotVerifiedTitle": "Zertifikatsvalidierung ist deaktiviert", + "certsNotVerifiedDetail": "Zertifikate für {host} werden nicht geprüft. Zum Ändern melde dich ab und passe die Option im Anmeldebildschirm an." } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 570723da6..3aa58560d 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -136,6 +136,20 @@ "@allowSelfSignedCertsTitle": {}, "allowSelfSignedCertsDetail": "Disables TLS certificate validation. Only enable this for a server you trust.", "@allowSelfSignedCertsDetail": {}, + "certsNotVerifiedTitle": "Certificate validation is off", + "@certsNotVerifiedTitle": { + "description": "Warning shown in the settings while the app accepts invalid TLS certificates from the server the user is logged into." + }, + "certsNotVerifiedDetail": "Certificates for {host} are not checked. To change this, log out and adjust the option on the login screen.", + "@certsNotVerifiedDetail": { + "description": "Explains the certificate warning. The option can only be set before logging in, hence the hint to log out.", + "type": "text", + "placeholders": { + "host": { + "type": "String" + } + } + }, "authOptionPasswordTitle": "Username and password", "@authOptionPasswordTitle": {}, "signInWithToken": "Sign in with token", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 379ac8391..0d9cbd9bd 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1201,5 +1201,9 @@ "gymModeLogScopeCurrentRoutine": "Rutina actual", "gymModeLogScopeWeeks": "Últimas {weeks} semanas", "gymModeDistinctLogs": "Ocultar valores duplicados", - "gymModeShowWorkoutDuration": "Mostrar la duración del entrenamiento" + "gymModeShowWorkoutDuration": "Mostrar la duración del entrenamiento", + "allowSelfSignedCertsTitle": "Permitir certificados autofirmados", + "allowSelfSignedCertsDetail": "Desactiva la validación del certificado TLS. Actívalo solo para un servidor de confianza.", + "certsNotVerifiedTitle": "La validación de certificados está desactivada", + "certsNotVerifiedDetail": "Los certificados de {host} no se comprueban. Para cambiarlo, cierra la sesión y ajusta la opción en la pantalla de inicio de sesión." } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 1c8d48d30..3ac5b3442 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1172,5 +1172,9 @@ "gymModeLogScopeCurrentRoutine": "Routine actuelle", "gymModeLogScopeWeeks": "{weeks} dernières semaines", "gymModeDistinctLogs": "Masquer les valeurs en double", - "gymModeShowWorkoutDuration": "Afficher la durée de l'entraînement" + "gymModeShowWorkoutDuration": "Afficher la durée de l'entraînement", + "allowSelfSignedCertsTitle": "Autoriser les certificats auto-signés", + "allowSelfSignedCertsDetail": "Désactive la validation du certificat TLS. Ne l'activez que pour un serveur de confiance.", + "certsNotVerifiedTitle": "La validation des certificats est désactivée", + "certsNotVerifiedDetail": "Les certificats de {host} ne sont pas vérifiés. Pour changer cela, déconnectez-vous et modifiez l'option sur l'écran de connexion." } diff --git a/test/core/http_overrides_test.dart b/test/core/http_overrides_test.dart index 0b55dbd73..f234a8494 100644 --- a/test/core/http_overrides_test.dart +++ b/test/core/http_overrides_test.dart @@ -95,6 +95,29 @@ void main() { expect(held(cert, 'gym.example.com', 443), isTrue); }); + group('exemptHost', () { + test('names the host while it is exempt', () { + WgerHttpOverrides.allowSelfSignedCerts = true; + WgerHttpOverrides.trustServer('https://gym.example.com:8000'); + + expect(WgerHttpOverrides.exemptHost('https://gym.example.com:8000'), 'gym.example.com'); + }); + + test('is null whenever the handshake would reject', () { + // Same rule as acceptsBadCertificate, so the warning cannot drift from it. + WgerHttpOverrides.allowSelfSignedCerts = false; + WgerHttpOverrides.trustServer('https://gym.example.com'); + expect(WgerHttpOverrides.exemptHost('https://gym.example.com'), isNull); + + WgerHttpOverrides.allowSelfSignedCerts = true; + expect(WgerHttpOverrides.exemptHost('https://other.example.com'), isNull); + expect(WgerHttpOverrides.exemptHost(null), isNull); + + WgerHttpOverrides.trustServer(DEFAULT_SERVER_PROD); + expect(WgerHttpOverrides.exemptHost(DEFAULT_SERVER_PROD), isNull); + }); + }); + test('trustServer clears the host for a null, empty or hostless URL', () { for (final url in [null, '', 'not a url']) { WgerHttpOverrides.trustServer(url); diff --git a/test/features/account/widgets/settings/certs_not_verified_test.dart b/test/features/account/widgets/settings/certs_not_verified_test.dart new file mode 100644 index 000000000..8e7b1dbf3 --- /dev/null +++ b/test/features/account/widgets/settings/certs_not_verified_test.dart @@ -0,0 +1,107 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; +import 'package:wger/core/app_settings_notifier.dart'; +import 'package:wger/core/consts.dart'; +import 'package:wger/core/http_overrides.dart'; +import 'package:wger/core/network/auth_notifier.dart'; +import 'package:wger/core/network/auth_state.dart'; +import 'package:wger/features/account/widgets/settings/certs_not_verified.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +class _FakeAuthNotifier extends AuthNotifier { + _FakeAuthNotifier(this._state); + + final AuthState _state; + + @override + Future build() async => _state; +} + +void main() { + const selfHosted = 'https://gym.example.com'; + + setUp(() { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + }); + + tearDown(() { + WgerHttpOverrides.allowSelfSignedCerts = false; + WgerHttpOverrides.trustedHost = null; + }); + + Future pumpWidget(WidgetTester tester, {required String serverUrl}) async { + final prefs = SharedPreferencesAsync(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + appSettingsPrefsProvider.overrideWithValue(prefs), + authProvider.overrideWith( + () => _FakeAuthNotifier( + AuthState(status: AuthStatus.loggedIn, serverUrl: serverUrl), + ), + ), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: Locale('en'), + home: Scaffold(body: SettingsCertsNotVerified()), + ), + ), + ); + await tester.pumpAndSettle(); + } + + final warning = find.byKey(const ValueKey('certsNotVerifiedWarning')); + + testWidgets('stays hidden while certificates are verified', (tester) async { + await pumpWidget(tester, serverUrl: selfHosted); + + expect(warning, findsNothing); + }); + + testWidgets('warns and names the host while the exemption is in effect', (tester) async { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + await SharedPreferencesAsync().setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, true); + WgerHttpOverrides.trustServer(selfHosted); + + await pumpWidget(tester, serverUrl: selfHosted); + + expect(warning, findsOneWidget); + expect(find.textContaining('gym.example.com'), findsOneWidget); + }); + + testWidgets('stays hidden on the official server even with the opt-in stored', (tester) async { + // The preference survives a switch back to wger.de, but the override never + // exempts it, so warning about it would be a lie. + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + await SharedPreferencesAsync().setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, true); + WgerHttpOverrides.trustServer(DEFAULT_SERVER_PROD); + + await pumpWidget(tester, serverUrl: DEFAULT_SERVER_PROD); + + expect(warning, findsNothing); + }); +} From b732b619c206f3dbdb2ba2302481a040107702a7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 15:02:04 +0200 Subject: [PATCH 5/5] Describe updated behaviour in comments --- lib/core/app_settings_notifier.dart | 4 ++-- lib/core/app_settings_notifier.freezed.dart | 8 ++++---- lib/core/app_settings_notifier.g.dart | 2 +- lib/core/consts.dart | 8 ++++---- lib/core/network/auth_notifier.g.dart | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/core/app_settings_notifier.dart b/lib/core/app_settings_notifier.dart index 8be792443..358d9d0ba 100644 --- a/lib/core/app_settings_notifier.dart +++ b/lib/core/app_settings_notifier.dart @@ -84,8 +84,8 @@ sealed class AppSettings with _$AppSettings { /// of wiping it, so the same user signing back in resumes incrementally. @Default(KEEP_DATA_ON_LOGOUT_DEFAULT) bool keepDataOnLogout, - /// When true, TLS certificate validation is disabled so the app can - /// connect to self-hosted instances using a self-signed certificate. + /// When true, an invalid TLS certificate is accepted from the self-hosted + /// server the app is configured for. Never applies to the official servers. @Default(ALLOW_SELF_SIGNED_CERTS_DEFAULT) bool allowSelfSignedCerts, }) = _AppSettings; } diff --git a/lib/core/app_settings_notifier.freezed.dart b/lib/core/app_settings_notifier.freezed.dart index 31ec0b079..7c18c83ce 100644 --- a/lib/core/app_settings_notifier.freezed.dart +++ b/lib/core/app_settings_notifier.freezed.dart @@ -17,8 +17,8 @@ mixin _$AppSettings { ThemeMode get themeMode; List get dashboardItems;/// Locale override. Null means the app follows the system locale. Locale? get userLocale;/// When true, a manual logout keeps the local database on disk instead /// of wiping it, so the same user signing back in resumes incrementally. - bool get keepDataOnLogout;/// When true, TLS certificate validation is disabled so the app can -/// connect to self-hosted instances using a self-signed certificate. + bool get keepDataOnLogout;/// When true, an invalid TLS certificate is accepted from the self-hosted +/// server the app is configured for. Never applies to the official servers. bool get allowSelfSignedCerts; /// Create a copy of AppSettings /// with the given fields replaced by the non-null parameter values. @@ -225,8 +225,8 @@ class _AppSettings implements AppSettings { /// When true, a manual logout keeps the local database on disk instead /// of wiping it, so the same user signing back in resumes incrementally. @override@JsonKey() final bool keepDataOnLogout; -/// When true, TLS certificate validation is disabled so the app can -/// connect to self-hosted instances using a self-signed certificate. +/// When true, an invalid TLS certificate is accepted from the self-hosted +/// server the app is configured for. Never applies to the official servers. @override@JsonKey() final bool allowSelfSignedCerts; /// Create a copy of AppSettings diff --git a/lib/core/app_settings_notifier.g.dart b/lib/core/app_settings_notifier.g.dart index 0e698d183..ead2c8f16 100644 --- a/lib/core/app_settings_notifier.g.dart +++ b/lib/core/app_settings_notifier.g.dart @@ -33,7 +33,7 @@ final class AppSettingsNotifierProvider AppSettingsNotifier create() => AppSettingsNotifier(); } -String _$appSettingsNotifierHash() => r'2ba0d53f1a48ba6876571c965e9e804c04be5645'; +String _$appSettingsNotifierHash() => r'499323f5b84feb0c395538db14e4d0a7de831b7c'; abstract class _$AppSettingsNotifier extends $AsyncNotifier { FutureOr build(); diff --git a/lib/core/consts.dart b/lib/core/consts.dart index f63b3f1d4..ac324bd3a 100644 --- a/lib/core/consts.dart +++ b/lib/core/consts.dart @@ -79,10 +79,10 @@ const PREFS_DB_OWNER_USER_ID = 'dbOwnerUserId'; const PREFS_KEEP_DATA_ON_LOGOUT = 'keepDataOnLogout'; const KEEP_DATA_ON_LOGOUT_DEFAULT = true; -/// User preference: trust self-signed/invalid TLS certificates so the app can -/// connect to self-hosted instances behind a self-signed cert. Off by default -/// since it disables certificate validation. Defaults to -/// [ALLOW_SELF_SIGNED_CERTS_DEFAULT]. +/// User preference: accept an invalid TLS certificate from the configured +/// self-hosted server, so the app can reach instances behind a self-signed +/// cert. Off by default, and never applies to the official servers. Defaults +/// to [ALLOW_SELF_SIGNED_CERTS_DEFAULT]. const PREFS_ALLOW_SELF_SIGNED_CERTS = 'allowSelfSignedCerts'; const ALLOW_SELF_SIGNED_CERTS_DEFAULT = false; diff --git a/lib/core/network/auth_notifier.g.dart b/lib/core/network/auth_notifier.g.dart index d1cfe2bb9..86ce6eeff 100644 --- a/lib/core/network/auth_notifier.g.dart +++ b/lib/core/network/auth_notifier.g.dart @@ -32,7 +32,7 @@ final class AuthNotifierProvider extends $AsyncNotifierProvider AuthNotifier(); } -String _$authNotifierHash() => r'720d6e804991e1b0c0b0bbd2a2077ed8422c0e39'; +String _$authNotifierHash() => r'19bf6776a00c5a7374ddc918f55709ee3a193b3f'; abstract class _$AuthNotifier extends $AsyncNotifier { FutureOr build();