mirror of
https://github.com/wger-project/flutter.git
synced 2026-11-29 09:20:56 +01:00
Warn in the settings while certificates are not being verified
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user