From 1a58dd8f71bd9bcb033491edd21fdc1a0cdff9c5 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 30 Jul 2026 14:23:37 +0200 Subject: [PATCH] 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); + }); +}