This commit is contained in:
Roland Geider
2026-05-03 18:21:54 +02:00
parent 7fb64b2925
commit 390dadcdf0
5 changed files with 144 additions and 273 deletions

View File

@@ -1,66 +0,0 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2025 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.
*/
import 'dart:convert';
import 'package:http/http.dart' as http;
/// Checks if the server's reverse proxy is configured correctly
/// by comparing pagination URLs with the base URL domain.
Future<SanityCheckResult> checkServerPaginationUrls({
required String baseUrl,
required String token,
http.Client? client,
}) async {
final httpClient = client ?? http.Client();
try {
final baseUri = Uri.parse(baseUrl);
final expectedHost = baseUri.host;
final expectedScheme = baseUri.scheme;
final response = await httpClient.get(
Uri.parse('$baseUrl/api/v2/exercise/?limit=1'),
headers: {
'Authorization': 'Token $token',
'Accept': 'application/json',
},
);
if (response.statusCode != 200) {
return const SanityCheckResult(isValid: false);
}
final data = jsonDecode(response.body) as Map<String, dynamic>;
final nextUrl = data['next'] as String?;
if (nextUrl == null) {
return const SanityCheckResult(isValid: true);
}
final nextUri = Uri.parse(nextUrl);
if (nextUri.host != expectedHost || nextUri.scheme != expectedScheme) {
return const SanityCheckResult(isValid: false);
}
return const SanityCheckResult(isValid: true);
} catch (e) {
return const SanityCheckResult(isValid: false);
}
}
/// Result of a server sanity check
class SanityCheckResult {
const SanityCheckResult({
required this.isValid,
});
final bool isValid;
}

View File

@@ -29,7 +29,6 @@ import 'package:package_info_plus/package_info_plus.dart';
import 'package:version/version.dart';
import 'package:wger/core/exceptions/http_exception.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/sanity_checks.dart';
import 'package:wger/helpers/shared_preferences.dart';
import 'helpers.dart';
@@ -155,6 +154,42 @@ class AuthProvider with ChangeNotifier {
return needUpdate;
}
/// Detects reverse-proxy misconfiguration on the server by checking that
/// pagination URLs returned by the API point to the same host and scheme as
/// the configured [serverUrl].
///
/// Returns `true` when the configuration looks fine (or the check could not
/// be completed conclusively), `false` when a mismatch is detected.
Future<bool> serverConfigSane() async {
try {
final baseUri = Uri.parse(serverUrl!);
final response = await client.get(
Uri.parse('$serverUrl/api/v2/exercise/?limit=1'),
headers: {
HttpHeaders.authorizationHeader: 'Token $token',
HttpHeaders.acceptHeader: 'application/json',
},
);
if (response.statusCode != 200) {
return true;
}
final data = jsonDecode(response.body) as Map<String, dynamic>;
final nextUrl = data['next'] as String?;
if (nextUrl == null) {
return true;
}
final nextUri = Uri.parse(nextUrl);
return nextUri.host.toLowerCase() == baseUri.host.toLowerCase() &&
nextUri.scheme == baseUri.scheme;
} catch (e) {
_logger.info('serverConfigSane check failed: $e');
return true;
}
}
/// Registers a new user
Future<LoginActions> register({
required String username,
@@ -196,6 +231,7 @@ class AuthProvider with ChangeNotifier {
String? apiToken,
) async {
await logout(shouldNotify: false);
_serverConfigWarning = false;
// Login using the API token
if (apiToken != null && apiToken.isNotEmpty) {
@@ -249,19 +285,11 @@ class AuthProvider with ChangeNotifier {
return LoginActions.update;
}
// Check server configuration sanity
try {
final sanityCheck = await checkServerPaginationUrls(
baseUrl: serverUrl,
token: token!,
);
if (!sanityCheck.isValid) {
_serverConfigWarning = true;
notifyListeners();
}
} catch (e) {
_logger.info('Sanity check error: $e');
// Surface a warning to the user when the server's reverse proxy is
// misconfigured (pagination URLs pointing to the wrong host).
if (!await serverConfigSane()) {
_serverConfigWarning = true;
notifyListeners();
}
// Log user in

View File

@@ -21,7 +21,7 @@ void showServerConfigWarning(BuildContext context) {
builder: (context) => AlertDialog(
title: Row(
children: [
const Icon(Icons.warning, color: Colors.orange, size: 28),
Icon(Icons.warning, color: Theme.of(context).colorScheme.error, size: 28),
const SizedBox(width: 12),
Expanded(child: Text(i18n.serverConfigIssueTitle)),
],

View File

@@ -16,6 +16,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart';
import 'package:mockito/mockito.dart';
@@ -145,4 +147,103 @@ void main() {
expect(authProvider.serverUpdateRequired(), false);
});
});
group('server config sanity check', () {
final tCheckUri = Uri.parse('http://localhost/api/v2/exercise/?limit=1');
setUp(() {
authProvider.token = 'test-token';
});
Response paginatedResponse(String? next) => Response(
'{"count": 1, "next": ${next == null ? 'null' : '"$next"'}, "previous": null, "results": []}',
200,
);
test('matching pagination URL — sane', () async {
when(mockClient.get(tCheckUri, headers: anyNamed('headers'))).thenAnswer(
(_) =>
Future(() => paginatedResponse('http://localhost/api/v2/exercise/?limit=1&offset=1')),
);
expect(await authProvider.serverConfigSane(), true);
});
test('host mismatch (localhost leak through reverse proxy) — not sane', () async {
authProvider.serverUrl = 'https://wger.example.com';
final uri = Uri.parse('https://wger.example.com/api/v2/exercise/?limit=1');
when(mockClient.get(uri, headers: anyNamed('headers'))).thenAnswer(
(_) => Future(
() => paginatedResponse('http://localhost:8000/api/v2/exercise/?limit=1&offset=1'),
),
);
expect(await authProvider.serverConfigSane(), false);
});
test('scheme mismatch (https expected, http returned) — not sane', () async {
authProvider.serverUrl = 'https://wger.example.com';
final uri = Uri.parse('https://wger.example.com/api/v2/exercise/?limit=1');
when(mockClient.get(uri, headers: anyNamed('headers'))).thenAnswer(
(_) => Future(
() => paginatedResponse('http://wger.example.com/api/v2/exercise/?limit=1&offset=1'),
),
);
expect(await authProvider.serverConfigSane(), false);
});
test('host comparison is case-insensitive', () async {
authProvider.serverUrl = 'https://Wger.Example.com';
final uri = Uri.parse('https://Wger.Example.com/api/v2/exercise/?limit=1');
when(mockClient.get(uri, headers: anyNamed('headers'))).thenAnswer(
(_) => Future(
() => paginatedResponse('https://wger.example.com/api/v2/exercise/?limit=1&offset=1'),
),
);
expect(await authProvider.serverConfigSane(), true);
});
test('no pagination (next is null) — sane', () async {
when(mockClient.get(tCheckUri, headers: anyNamed('headers'))).thenAnswer(
(_) => Future(() => paginatedResponse(null)),
);
expect(await authProvider.serverConfigSane(), true);
});
test('non-200 response — inconclusive, returns sane', () async {
when(mockClient.get(tCheckUri, headers: anyNamed('headers'))).thenAnswer(
(_) => Future(() => Response('Internal Server Error', 500)),
);
expect(await authProvider.serverConfigSane(), true);
});
test('network error — inconclusive, returns sane', () async {
when(mockClient.get(tCheckUri, headers: anyNamed('headers'))).thenAnswer(
(_) => Future.error(Exception('Network error')),
);
expect(await authProvider.serverConfigSane(), true);
});
test('sends Authorization and Accept headers', () async {
Map<String, String>? captured;
when(mockClient.get(tCheckUri, headers: anyNamed('headers'))).thenAnswer((invocation) {
captured = invocation.namedArguments[#headers] as Map<String, String>;
return Future(() => paginatedResponse(null));
});
await authProvider.serverConfigSane();
expect(captured?[HttpHeaders.authorizationHeader], 'Token test-token');
expect(captured?[HttpHeaders.acceptHeader], 'application/json');
});
test('port numbers match — sane', () async {
authProvider.serverUrl = 'https://wger.example.com:8443';
final uri = Uri.parse('https://wger.example.com:8443/api/v2/exercise/?limit=1');
when(mockClient.get(uri, headers: anyNamed('headers'))).thenAnswer(
(_) => Future(
() =>
paginatedResponse('https://wger.example.com:8443/api/v2/exercise/?limit=1&offset=1'),
),
);
expect(await authProvider.serverConfigSane(), true);
});
});
}

View File

@@ -1,192 +0,0 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) 2025 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.
*
* wger Workout Manager 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_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:wger/helpers/sanity_checks.dart';
import 'dart:convert';
void main() {
group('checkServerPaginationUrls', () {
const testToken = 'test-token-123';
const testBaseUrl = 'https://wger.example.com';
test('returns valid when pagination URL matches base URL', () async {
final client = MockClient((request) async {
return http.Response(
jsonEncode({
'count': 100,
'next': 'https://wger.example.com/api/v2/exercise/?limit=1&offset=1',
'previous': null,
'results': [],
}),
200,
);
});
final result = await checkServerPaginationUrls(
baseUrl: testBaseUrl,
token: testToken,
client: client,
);
expect(result.isValid, isTrue);
});
test('detects host mismatch (localhost issue)', () async {
final client = MockClient((request) async {
return http.Response(
jsonEncode({
'count': 100,
'next': 'http://localhost:8000/api/v2/exercise/?limit=1&offset=1',
'previous': null,
'results': [],
}),
200,
);
});
final result = await checkServerPaginationUrls(
baseUrl: testBaseUrl,
token: testToken,
client: client,
);
expect(result.isValid, isFalse);
});
test('detects protocol mismatch (https vs http)', () async {
final client = MockClient((request) async {
return http.Response(
jsonEncode({
'count': 100,
'next': 'http://wger.example.com/api/v2/exercise/?limit=1&offset=1',
'previous': null,
'results': [],
}),
200,
);
});
final result = await checkServerPaginationUrls(
baseUrl: testBaseUrl,
token: testToken,
client: client,
);
expect(result.isValid, isFalse);
});
test('returns valid when next URL is null (no pagination)', () async {
final client = MockClient((request) async {
return http.Response(
jsonEncode({
'count': 1,
'next': null,
'previous': null,
'results': [],
}),
200,
);
});
final result = await checkServerPaginationUrls(
baseUrl: testBaseUrl,
token: testToken,
client: client,
);
expect(result.isValid, isTrue);
});
test('handles server error gracefully', () async {
final client = MockClient((request) async {
return http.Response('Internal Server Error', 500);
});
final result = await checkServerPaginationUrls(
baseUrl: testBaseUrl,
token: testToken,
client: client,
);
expect(result.isValid, isFalse);
});
test('handles network errors gracefully', () async {
final client = MockClient((request) async {
throw Exception('Network error');
});
final result = await checkServerPaginationUrls(
baseUrl: testBaseUrl,
token: testToken,
client: client,
);
expect(result.isValid, isFalse);
});
test('includes correct headers in request', () async {
String? authHeader;
String? acceptHeader;
final client = MockClient((request) async {
authHeader = request.headers['Authorization'];
acceptHeader = request.headers['Accept'];
return http.Response(
jsonEncode({'count': 0, 'next': null, 'results': []}),
200,
);
});
await checkServerPaginationUrls(
baseUrl: testBaseUrl,
token: testToken,
client: client,
);
expect(authHeader, 'Token $testToken');
expect(acceptHeader, 'application/json');
});
test('handles port numbers correctly in URL comparison', () async {
final client = MockClient((request) async {
return http.Response(
jsonEncode({
'count': 100,
'next': 'https://wger.example.com:8443/api/v2/exercise/?limit=1&offset=1',
'previous': null,
'results': [],
}),
200,
);
});
final result = await checkServerPaginationUrls(
baseUrl: 'https://wger.example.com:8443',
token: testToken,
client: client,
);
expect(result.isValid, isTrue);
});
});
}