mirror of
https://github.com/wger-project/flutter.git
synced 2026-11-29 09:20:56 +01:00
Merge pull request #1232 from bhavit04/feat/allow-self-signed-certs
feat(auth): allow connecting to servers with self-signed certificates
This commit is contained in:
@@ -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/core/consts.dart';
|
||||
import 'package:wger/core/http_overrides.dart';
|
||||
import 'package:wger/core/locale.dart';
|
||||
import 'package:wger/core/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, 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;
|
||||
}
|
||||
|
||||
@@ -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<bool> _loadAllowSelfSignedCerts() async {
|
||||
final value =
|
||||
(await _prefs.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS)) ?? ALLOW_SELF_SIGNED_CERTS_DEFAULT;
|
||||
// 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<void> setAllowSelfSignedCerts(bool value) async {
|
||||
final current = state.asData?.value ?? const AppSettings();
|
||||
state = AsyncData(current.copyWith(allowSelfSignedCerts: value));
|
||||
WgerHttpOverrides.allowSelfSignedCerts = value;
|
||||
await _prefs.setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, value);
|
||||
}
|
||||
|
||||
//
|
||||
// Dashboard config
|
||||
//
|
||||
|
||||
@@ -17,7 +17,9 @@ mixin _$AppSettings {
|
||||
ThemeMode get themeMode; List<DashboardItem> 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, 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.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@@ -28,16 +30,16 @@ $AppSettingsCopyWith<AppSettings> get copyWith => _$AppSettingsCopyWithImpl<AppS
|
||||
|
||||
@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)';
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +50,7 @@ abstract mixin class $AppSettingsCopyWith<$Res> {
|
||||
factory $AppSettingsCopyWith(AppSettings value, $Res Function(AppSettings) _then) = _$AppSettingsCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale, bool keepDataOnLogout
|
||||
ThemeMode themeMode, List<DashboardItem> 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<DashboardItem>,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 extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale, bool keepDataOnLogout)? $default,{required TResult orElse(),}) {final _that = this;
|
||||
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> 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 extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale, bool keepDataOnLogout) $default,) {final _that = this;
|
||||
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( ThemeMode themeMode, List<DashboardItem> 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 extends Object?>(TResult? Function( ThemeMode themeMode, List<DashboardItem> dashboardItems, Locale? userLocale, bool keepDataOnLogout)? $default,) {final _that = this;
|
||||
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( ThemeMode themeMode, List<DashboardItem> 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<DashboardItem> dashboardItems = const [], this.userLocale, this.keepDataOnLogout = KEEP_DATA_ON_LOGOUT_DEFAULT}): _dashboardItems = dashboardItems;
|
||||
const _AppSettings({this.themeMode = ThemeMode.system, final List<DashboardItem> 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, 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
|
||||
/// 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<DashboardItem> dashboardItems, Locale? userLocale, bool keepDataOnLogout
|
||||
ThemeMode themeMode, List<DashboardItem> 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<DashboardItem>,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,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ final class AppSettingsNotifierProvider
|
||||
AppSettingsNotifier create() => AppSettingsNotifier();
|
||||
}
|
||||
|
||||
String _$appSettingsNotifierHash() => r'd1fd574fb63a933ff4e26f5ecadab97c6033d2ee';
|
||||
String _$appSettingsNotifierHash() => r'499323f5b84feb0c395538db14e4d0a7de831b7c';
|
||||
|
||||
abstract class _$AppSettingsNotifier extends $AsyncNotifier<AppSettings> {
|
||||
FutureOr<AppSettings> build();
|
||||
|
||||
@@ -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: 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;
|
||||
|
||||
/// Secure-storage key for the headless refresh token.
|
||||
const SECURE_STORAGE_REFRESH_TOKEN = 'wger_refresh_token';
|
||||
|
||||
|
||||
101
lib/core/http_overrides.dart
Normal file
101
lib/core/http_overrides.dart
Normal file
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:wger/core/consts.dart';
|
||||
|
||||
/// [HttpOverrides] that accepts a self-signed / otherwise invalid TLS
|
||||
/// certificate, but only from [trustedHost] and only while
|
||||
/// [allowSelfSignedCerts] is set.
|
||||
///
|
||||
/// 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.
|
||||
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) => 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
|
||||
/// something a self-hosting setting may wave through.
|
||||
static final Set<String> _officialHosts = {
|
||||
Uri.parse(DEFAULT_SERVER_PROD).host,
|
||||
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) => _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) {
|
||||
return super.createHttpClient(context)..badCertificateCallback = acceptsBadCertificate;
|
||||
}
|
||||
}
|
||||
|
||||
/// Routes all `dart:io` HTTP traffic through [WgerHttpOverrides].
|
||||
///
|
||||
/// 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 = WgerHttpOverrides();
|
||||
}
|
||||
@@ -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');
|
||||
|
||||
@@ -32,7 +32,7 @@ final class AuthNotifierProvider extends $AsyncNotifierProvider<AuthNotifier, Au
|
||||
AuthNotifier create() => AuthNotifier();
|
||||
}
|
||||
|
||||
String _$authNotifierHash() => r'720d6e804991e1b0c0b0bbd2a2077ed8422c0e39';
|
||||
String _$authNotifierHash() => r'19bf6776a00c5a7374ddc918f55709ee3a193b3f';
|
||||
|
||||
abstract class _$AuthNotifier extends $AsyncNotifier<AuthState> {
|
||||
FutureOr<AuthState> build();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -29,9 +29,11 @@ Future<void> 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<void>(
|
||||
context: context,
|
||||
@@ -40,6 +42,7 @@ Future<void> showAdvancedSheet({
|
||||
builder: (_) => AdvancedSheet(
|
||||
initialHideCustomServer: initialHideCustomServer,
|
||||
initialUsePassword: initialUsePassword,
|
||||
initialAllowSelfSignedCerts: initialAllowSelfSignedCerts,
|
||||
loginMode: loginMode,
|
||||
serverUrlController: serverUrlController,
|
||||
onChanged: onChanged,
|
||||
@@ -50,13 +53,15 @@ Future<void> 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<AdvancedSheet> {
|
||||
late bool _hideCustomServer;
|
||||
late bool _usePassword;
|
||||
late bool _allowSelfSignedCerts;
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
@override
|
||||
@@ -77,11 +83,12 @@ class _AdvancedSheetState extends State<AdvancedSheet> {
|
||||
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,27 @@ class _AdvancedSheetState extends State<AdvancedSheet> {
|
||||
padding: const EdgeInsets.only(top: 2, bottom: 4),
|
||||
child: ServerField(controller: widget.serverUrlController),
|
||||
),
|
||||
// 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: !_hideCustomServer && _allowSelfSignedCerts,
|
||||
onChanged: _hideCustomServer
|
||||
? null
|
||||
: (value) => _set(() => _allowSelfSignedCerts = value),
|
||||
),
|
||||
if (widget.loginMode) ...[
|
||||
_SectionLabel(text: i18n.signInMethodSectionLabel),
|
||||
_OptionRow(
|
||||
|
||||
@@ -21,6 +21,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:wger/core/app_link_router.dart';
|
||||
import 'package:wger/core/app_settings_notifier.dart';
|
||||
import 'package:wger/core/consts.dart';
|
||||
import 'package:wger/core/error_dialogs.dart';
|
||||
import 'package:wger/core/errors.dart';
|
||||
@@ -247,18 +248,25 @@ class _AuthCardState extends ConsumerState<AuthCard> {
|
||||
}
|
||||
|
||||
/// 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,
|
||||
loginMode: _authMode == AuthMode.login,
|
||||
serverUrlController: _serverUrlController,
|
||||
onChanged: (hideCustomServer, usePassword) {
|
||||
onChanged: (hideCustomServer, usePassword, allowSelfSigned) {
|
||||
setState(() {
|
||||
_hideCustomServer = hideCustomServer;
|
||||
_useUsernameAndPassword = usePassword;
|
||||
});
|
||||
// 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) {
|
||||
@@ -274,6 +282,11 @@ class _AuthCardState extends ConsumerState<AuthCard> {
|
||||
// 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) {
|
||||
@@ -377,7 +390,7 @@ class _AuthCardState extends ConsumerState<AuthCard> {
|
||||
isCustomServer: !_hideCustomServer,
|
||||
isTokenMode: _authMode == AuthMode.login && !_useUsernameAndPassword,
|
||||
serverUrl: _serverUrlController.text,
|
||||
onTap: _showAdvancedSheet,
|
||||
onTap: () => _showAdvancedSheet(allowSelfSignedCerts),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
|
||||
@@ -132,6 +132,24 @@
|
||||
"@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": {},
|
||||
"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",
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
|
||||
@@ -25,11 +25,13 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:wger/core/app_link_router.dart';
|
||||
import 'package:wger/core/app_settings_notifier.dart';
|
||||
import 'package:wger/core/consts.dart';
|
||||
import 'package:wger/core/dashboard.dart';
|
||||
import 'package:wger/core/error_dialogs.dart';
|
||||
import 'package:wger/core/errors.dart';
|
||||
import 'package:wger/core/form_screen.dart';
|
||||
import 'package:wger/core/home_tabs_screen.dart';
|
||||
import 'package:wger/core/http_overrides.dart';
|
||||
import 'package:wger/core/keys.dart';
|
||||
import 'package:wger/core/locale.dart';
|
||||
import 'package:wger/core/logs.dart';
|
||||
@@ -99,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();
|
||||
|
||||
@@ -107,6 +113,13 @@ void main() async {
|
||||
// SharedPreferences to SharedPreferencesAsync migration function
|
||||
await PreferenceHelper.instance.migrationSupportFunctionForSharedPreferences();
|
||||
|
||||
// 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;
|
||||
WgerHttpOverrides.trustServer(await AuthNotifier.getServerUrlFromPrefs());
|
||||
|
||||
// Catch errors from Flutter itself (widget build, layout, paint, etc.)
|
||||
FlutterError.onError = (FlutterErrorDetails details) {
|
||||
final stack = details.stack ?? StackTrace.empty;
|
||||
|
||||
@@ -322,4 +322,41 @@ void main() {
|
||||
expect(await prefs.getBool(PREFS_KEEP_DATA_ON_LOGOUT), true);
|
||||
});
|
||||
});
|
||||
|
||||
group('allow self-signed certs', () {
|
||||
test('defaults to false', () async {
|
||||
final settings = await container.read(appSettingsProvider.future);
|
||||
expect(settings.allowSelfSignedCerts, false);
|
||||
});
|
||||
|
||||
test('loads true from prefs', () async {
|
||||
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
|
||||
final prefs = SharedPreferencesAsync();
|
||||
await prefs.setBool(PREFS_ALLOW_SELF_SIGNED_CERTS, true);
|
||||
|
||||
container.dispose();
|
||||
container = ProviderContainer(
|
||||
overrides: [appSettingsPrefsProvider.overrideWithValue(prefs)],
|
||||
);
|
||||
|
||||
final settings = await container.read(appSettingsProvider.future);
|
||||
expect(settings.allowSelfSignedCerts, true);
|
||||
});
|
||||
|
||||
test('setAllowSelfSignedCerts persists the toggle', () async {
|
||||
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
|
||||
final prefs = SharedPreferencesAsync();
|
||||
|
||||
container.dispose();
|
||||
container = ProviderContainer(
|
||||
overrides: [appSettingsPrefsProvider.overrideWithValue(prefs)],
|
||||
);
|
||||
|
||||
await container.read(appSettingsProvider.future);
|
||||
await container.read(appSettingsProvider.notifier).setAllowSelfSignedCerts(true);
|
||||
|
||||
expect(container.read(appSettingsProvider).requireValue.allowSelfSignedCerts, true);
|
||||
expect(await prefs.getBool(PREFS_ALLOW_SELF_SIGNED_CERTS), true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
127
test/core/http_overrides_test.dart
Normal file
127
test/core/http_overrides_test.dart
Normal file
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:wger/core/consts.dart';
|
||||
import 'package:wger/core/http_overrides.dart';
|
||||
|
||||
class _FakeCertificate extends Fake implements X509Certificate {}
|
||||
|
||||
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<WgerHttpOverrides>());
|
||||
});
|
||||
|
||||
test('rejects a bad certificate by default', () {
|
||||
expect(accepts('gym.example.com'), isFalse);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
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);
|
||||
expect(WgerHttpOverrides.trustedHost, isNull, reason: 'for ${url ?? 'null'}');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<AuthState> build() async => _state;
|
||||
}
|
||||
|
||||
void main() {
|
||||
const selfHosted = 'https://gym.example.com';
|
||||
|
||||
setUp(() {
|
||||
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
WgerHttpOverrides.allowSelfSignedCerts = false;
|
||||
WgerHttpOverrides.trustedHost = null;
|
||||
});
|
||||
|
||||
Future<void> 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);
|
||||
});
|
||||
}
|
||||
@@ -32,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';
|
||||
@@ -552,6 +553,64 @@ 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 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;
|
||||
await tester.pumpWidget(getWidget());
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byKey(const Key('advancedButton')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// Visible for the official server, but off and not interactive.
|
||||
final toggle = find.byKey(const Key('allowSelfSignedCertsSwitch'));
|
||||
expect(toggle, findsOneWidget);
|
||||
expect(tester.widget<SwitchListTile>(toggle).onChanged, isNull);
|
||||
expect(tester.widget<SwitchListTile>(toggle).value, isFalse);
|
||||
|
||||
await tester.tap(find.text('Self-hosted'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.widget<SwitchListTile>(toggle).onChanged, isNotNull);
|
||||
|
||||
await tester.tap(toggle);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
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<SwitchListTile>(toggle).value, isFalse);
|
||||
expect(tester.widget<SwitchListTile>(toggle).onChanged, isNull);
|
||||
expect(
|
||||
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<SwitchListTile>(toggle).value, isTrue);
|
||||
});
|
||||
|
||||
testWidgets('Sheet pre-selects Self-hosted for a custom last-used server', (
|
||||
WidgetTester tester,
|
||||
) async {
|
||||
|
||||
Reference in New Issue
Block a user