From c75403b3ed794fe53965939fd91281fdca7dd97d Mon Sep 17 00:00:00 2001 From: Oliver Date: Mon, 2 Nov 2026 19:15:27 +1100 Subject: [PATCH] Session auth (#904) * use session auth rather than token auth * Add unit tests for login * Ensure user cannot reuse login after logout * handle logout mid session * Additional unit tests * ensure sensitive data is redacted from sentry * Handle session disconnect * Additional tweaks * Update pubspec.lock * Update release_notes.md * Bump version number * Adjust login button * Clear stored session when host changes * Improved redacting of sensitive info * Improved handling of local session storage * prevent failed migration from logging as complete * Fix for error raised in overlapping requests * replace userInfo on successful response * handle empty response * Improved session comparison * Add UI testing --- android/app/src/main/AndroidManifest.xml | 4 +- android/app/src/main/res/xml/backup_rules.xml | 10 + .../main/res/xml/data_extraction_rules.xml | 16 + assets/release_notes.md | 11 + dart_test.yaml | 6 +- lib/api.dart | 702 +++++--- lib/auth/allauth_client.dart | 102 ++ lib/auth/auth_manager.dart | 186 +++ lib/auth/auth_method.dart | 43 + lib/auth/auth_result.dart | 287 ++++ lib/auth/session_store.dart | 408 +++++ lib/inventree/redact.dart | 340 ++++ lib/inventree/sentry.dart | 9 +- lib/l10n/app_en.arb | 69 +- lib/l10n/collect_translations.py | 6 +- lib/main.dart | 10 + lib/managed_config.dart | 16 +- lib/settings/login.dart | 160 +- lib/settings/login_mfa.dart | 205 +++ lib/settings/select_server.dart | 26 +- lib/user_profile.dart | 296 +++- lib/widget/dialogs.dart | 15 + lib/widget/notes_list_widget.dart | 2 +- pubspec.lock | 38 +- pubspec.yaml | 3 +- test/api_test.dart | 46 +- test/auth_flow_test.dart | 1469 +++++++++++++++++ test/auth_server_test.dart | 558 +++++++ test/auth_test.dart | 844 ++++++++++ test/fake_server.dart | 429 +++++ test/redact_test.dart | 279 ++++ test/setup.dart | 49 +- test/widget/login_test.dart | 721 ++++++++ 33 files changed, 6948 insertions(+), 417 deletions(-) create mode 100644 android/app/src/main/res/xml/backup_rules.xml create mode 100644 android/app/src/main/res/xml/data_extraction_rules.xml create mode 100644 lib/auth/allauth_client.dart create mode 100644 lib/auth/auth_manager.dart create mode 100644 lib/auth/auth_method.dart create mode 100644 lib/auth/auth_result.dart create mode 100644 lib/auth/session_store.dart create mode 100644 lib/inventree/redact.dart create mode 100644 lib/settings/login_mfa.dart create mode 100644 test/auth_flow_test.dart create mode 100644 test/auth_server_test.dart create mode 100644 test/auth_test.dart create mode 100644 test/fake_server.dart create mode 100644 test/redact_test.dart create mode 100644 test/widget/login_test.dart diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index cba340f0..74cbacf3 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -25,7 +25,9 @@ + android:icon="@mipmap/ic_launcher" + android:fullBackupContent="@xml/backup_rules" + android:dataExtractionRules="@xml/data_extraction_rules"> + + + + + diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 00000000..c311459e --- /dev/null +++ b/android/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/assets/release_notes.md b/assets/release_notes.md index 364482d6..aa2e5b9d 100644 --- a/assets/release_notes.md +++ b/assets/release_notes.md @@ -1,3 +1,14 @@ +## 1.0.0 - November 2026 +--- + +- Login now uses secure sessions, matching the web interface (API tokens are no longer used) +- Supports two-factor authentication (TOTP and recovery codes), with "trust this device" +- Session data is stored in secure device storage +- Username is remembered after logout +- Expired sessions now return the user to the login screen +- Credentials are removed from error reports +- Requires InvenTree server API version 314 or newer - existing users must log in again + ## 0.26.0 - October 2026 --- diff --git a/dart_test.yaml b/dart_test.yaml index 722312b3..256b2841 100644 --- a/dart_test.yaml +++ b/dart_test.yaml @@ -1,4 +1,4 @@ -# Test files share a single server account, and each requests an API token -# with the same name - which revokes any token previously issued under that name. -# Run test files sequentially to prevent them invalidating each other's tokens +# Test files share a single server account, and a single on-disk preferences +# database (path_provider is mocked to the working directory). +# Run test files sequentially to prevent them interfering with each other concurrency: 1 diff --git a/lib/api.dart b/lib/api.dart index 4a7e3316..394aa26c 100644 --- a/lib/api.dart +++ b/lib/api.dart @@ -18,12 +18,15 @@ import "package:path_provider/path_provider.dart"; import "package:inventree/api_form.dart"; import "package:inventree/app_colors.dart"; +import "package:inventree/auth/auth_result.dart"; +import "package:inventree/auth/session_store.dart"; import "package:inventree/preferences.dart"; import "package:inventree/l10.dart"; import "package:inventree/helpers.dart"; import "package:inventree/inventree/model.dart"; import "package:inventree/inventree/notification.dart"; import "package:inventree/inventree/status_codes.dart"; +import "package:inventree/inventree/redact.dart"; import "package:inventree/inventree/sentry.dart"; import "package:inventree/settings/login.dart"; import "package:inventree/user_profile.dart"; @@ -117,16 +120,20 @@ class APIResponse { */ class InvenTreeFileService extends FileService { InvenTreeFileService({HttpClient? client, bool strictHttps = false}) { - _client = client ?? HttpClient(); + if (client != null) { + // Shared client - certificate handling is already configured by its owner. + // Overriding the callback here would discard per-profile certificate trust. + _client = client; + } else { + _client = HttpClient(); - if (_client != null) { - _client!.badCertificateCallback = (cert, host, port) { + _client.badCertificateCallback = (cert, host, port) { return !strictHttps; }; } } - HttpClient? _client; + late final HttpClient _client; @override Future get( @@ -135,7 +142,7 @@ class InvenTreeFileService extends FileService { }) async { final Uri resolved = Uri.base.resolve(url); - final HttpClientRequest req = await _client!.getUrl(resolved); + final HttpClientRequest req = await _client.getUrl(resolved); if (headers != null) { headers.forEach((key, value) { @@ -162,8 +169,8 @@ class InvenTreeFileService extends FileService { /* * InvenTree API - Access to the InvenTree REST interface. * - * InvenTree implements token-based authentication, which is - * initialised using a username:password combination. + * Requests are authenticated using a server session (cookie based), + * which is established by logging in via the allauth API (see lib/auth/). */ /* @@ -193,14 +200,12 @@ class InvenTreeAPI { } // Minimum required API version for server - // 2024-03-02 (release 0.14.0) - // Ref: https://github.com/inventree/InvenTree/releases/tag/0.14.0 - static const _minApiVersion = 180; + // Session authentication requires the allauth "headless" API + // Ref: https://github.com/inventree/InvenTree/pull/6293 + static const _minApiVersion = 314; bool _strictHttps = false; - // Endpoint for requesting an API token - static const _URL_TOKEN = "user/me/token/"; static const _URL_ROLES = "user/me/roles/"; static const _URL_ME = "user/me/"; @@ -246,10 +251,10 @@ class InvenTreeAPI { // Available user permissions are loaded when connecting to the server Map permissions = {}; - // Profile authentication token - String get token => profile?.token ?? ""; + // Session cookies for the active profile + SessionStore session = SessionStore(); - bool get hasToken => token.isNotEmpty; + bool get hasSession => session.hasSession; String? get serverAddress { return profile?.server; @@ -396,7 +401,7 @@ class InvenTreeAPI { bool _connecting = false; bool isConnected() { - return profile != null && _connected && baseUrl.isNotEmpty && hasToken; + return profile != null && _connected && baseUrl.isNotEmpty && hasSession; } bool isConnecting() { @@ -410,52 +415,25 @@ class InvenTreeAPI { * Performs the following steps: * * 1. Check the api/ endpoint to see if the sever exists - * 2. If no token available, perform user authentication - * 2. Check the api/user/me/ endpoint to see if the user is authenticated - * 3. If not authenticated, purge token, and exit - * 4. Request user roles - * 5. Request information on available plugins + * 2. If no session available, exit (user must login) + * 3. Check the api/user/me/ endpoint to see if the session is valid + * 4. If not authenticated, purge the session, and exit + * 5. Request user roles + * 6. Request information on available plugins */ Future _connectToServer() async { if (!await checkServer()) { return false; } - if (!hasToken) { + if (!hasSession) { return false; } - if (!await _checkAuth()) { - final UserProfile? expiredProfile = profile; - - // Invalidate the token - if (expiredProfile != null) { - expiredProfile.token = ""; - await UserProfileDBManager().updateProfile(expiredProfile); - } - - if (expiredProfile != null) { - showServerError( - _URL_ME, - L10().sessionExpired, - "${L10().sessionExpiredDetail}\n${expiredProfile.name}", - ); - - // Take the user straight to the login screen for this profile, - // rather than leaving them to work out why Home shows disconnected - OneContext().push( - MaterialPageRoute( - builder: (context) => InvenTreeLoginWidget(expiredProfile), - ), - ); - } else { - showServerError( - _URL_ME, - L10().serverNotConnected, - L10().serverAuthenticationError, - ); - } + final APIResponse authResponse = await _checkAuth(); + if (!authResponse.successful()) { + await _handleAuthFailure(authResponse); return false; } @@ -471,6 +449,269 @@ class InvenTreeAPI { return true; } + /* + * The user/me/ request failed - determine why, and what to do about it + */ + Future _handleAuthFailure(APIResponse response) async { + final UserProfile? expiredProfile = profile; + + // Not an authentication problem (e.g. network error, server error) + // Retain the session, as it may still be valid + if (response.statusCode != 401 && response.statusCode != 403) { + if (response.isValid()) { + showStatusCodeError(_URL_ME, response.statusCode); + } + return; + } + + // The server requires MFA to be configured for this user, + // which must be done via the web interface + if (response.asMap()["id"] == FLOW_MFA_REGISTER) { + String detail = L10().mfaRegistrationRequiredDetail; + + final String serverMessage = (response.asMap()["error"] ?? "").toString(); + + if (serverMessage.isNotEmpty) { + detail = "${serverMessage}\n\n${detail}"; + } + + // End the (restricted) server session + await delete("auth/v1/auth/session"); + + await _expireSession(expiredProfile); + + _showAuthError(L10().mfaRegistrationRequired, detail); + + // Logging in again will not help - but suppress errors from other requests + _loginRequired = true; + return; + } + + await _expireSession(expiredProfile); + + if (expiredProfile != null) { + _showAuthError( + L10().sessionExpired, + "${L10().sessionExpiredDetail}\n${expiredProfile.name}", + ); + + // Take the user straight to the login screen for this profile, + // rather than leaving them to work out why Home shows disconnected + _requestLogin(expiredProfile); + } else { + showServerError( + _URL_ME, + L10().serverNotConnected, + L10().serverAuthenticationError, + ); + } + } + + // Pending check of whether the session is still valid (see _handleUnauthorized). + // Requests rejected while the check is running share its result + Future? _sessionCheck; + + // Zone value which identifies the session check request itself + static const Symbol _SESSION_CHECK_ZONE = #inventreeSessionCheck; + + // Set once the session has been found to be invalid, until the user logs in + // again (or leaves the login screen) + bool _loginRequired = false; + + // Set while the login screen is open (opened by _requestLogin) + bool _loginScreenOpen = false; + + // Set while displaying the reason for an authentication failure + bool _showingAuthError = false; + + /* + * Errors caused by an expired session are not displayed to the user - + * they are directed to the login screen instead. + * Checked by showServerError() before displaying an error. + * + * Only applies once the session is known to be invalid - requests rejected + * while the session is being checked wait for the result (_handleUnauthorized) + */ + bool get suppressServerErrors => _loginRequired && !_showingAuthError; + + void _showAuthError(String title, String description) { + _showingAuthError = true; + + try { + showServerError(_URL_ME, title, description); + } finally { + _showingAuthError = false; + } + } + + /* + * Take the user to the login screen for the provided profile + * (unless it is already open) + */ + void _requestLogin(UserProfile? prf) { + _loginRequired = true; + + if (prf == null || _loginScreenOpen) { + return; + } + + _loginScreenOpen = true; + + debug("API : Opening login screen for '${prf.name}'"); + + final route = MaterialPageRoute( + builder: (context) => InvenTreeLoginWidget(prf), + ); + + final NavigatorState? navigator = testNavigatorKey?.currentState; + + if (navigator != null) { + navigator.push(route).then((_) => onLoginScreenClosed()); + } else if (hasContext()) { + OneContext().push(route).then((_) => onLoginScreenClosed()); + } + } + + // Navigator for the login screen in widget tests (which have no OneContext) + @visibleForTesting + GlobalKey? testNavigatorKey; + + /* + * The login screen was closed (logged in, or dismissed by the user). + * If the user did not login, the next rejected request opens it again + */ + @visibleForTesting + void onLoginScreenClosed() { + _loginScreenOpen = false; + _loginRequired = false; + } + + /* + * Return true if a response for [uri] indicates that authentication failed + * (e.g. the session has expired, or was ended from the web interface). + * + * Responses from the allauth endpoints are excluded - these return 401 + * as part of normal operation (e.g. logout, pending login flows) + */ + bool _isUnauthorized(Uri uri, int statusCode) { + if (statusCode != 401 || !session.isServerUri(uri)) { + return false; + } + + return !uri.path.contains("/api/auth/"); + } + + /* + * A request was rejected with 401. + * + * If connected, confirm that the session is no longer valid (a single request + * could be rejected for other reasons), and if so, end the connection and take + * the user to the login screen. If not connected (e.g. a screen which was open + * when the session expired), take the user to the login screen. + * + * Returns true if the failure has been handled, and should not be reported + * to the user as an error. + */ + Future _handleUnauthorized(String url) async { + // The connection routine reports authentication problems itself + if (_connecting) { + return false; + } + + // This is the session check request itself - the check handles the result + // (waiting for the check here would never complete) + if (Zone.current[_SESSION_CHECK_ZONE] == true) { + return false; + } + + // Another request is already checking the session - share its result, + // so this request is only treated as handled if login is actually required + final Future? pending = _sessionCheck; + + if (pending != null) { + return pending; + } + + if (!_connected) { + if (!_loginRequired) { + _requestLogin(profile); + } + + return true; + } + + final Future check = _checkSession(); + _sessionCheck = check; + + try { + return await check; + } finally { + if (identical(_sessionCheck, check)) { + _sessionCheck = null; + } + } + } + + /* + * Check whether the session is still valid (after a request was rejected). + * If not, expire the session and direct the user to login again. + * + * Returns true if the session has expired (login is required). + */ + Future _checkSession() async { + // Run the request in a zone which identifies it as the session check + final APIResponse response = await runZoned( + _checkAuth, + zoneValues: {_SESSION_CHECK_ZONE: true}, + ); + + if (response.statusCode != 401 && response.statusCode != 403) { + // Session is still valid (or the server could not be reached), + // so report the original error as normal + return false; + } + + debug("API : Session expired while connected"); + + // The user is no longer authenticated + userInfo = {}; + + // Expire the session and direct the user to login again + await _handleAuthFailure(response); + + _connected = false; + _notification_timer?.cancel(); + _notification_timer = null; + _connectionStatusChanged(); + + return true; + } + + // Mark a response which was rejected because the user must login again + // (so that it is not reported as an error - see reportModelError) + void _markLoginRequired(APIResponse response) { + response.error = "LoginRequired"; + response.errorDetail = L10().sessionExpired; + } + + /* + * Discard the session and CSRF cookies for the provided profile. + * Other cookies (e.g. MFA "trusted device") are retained. + */ + Future _expireSession(UserProfile? prf) async { + session.clearAuthCookies(); + + if (prf != null) { + // The session is no longer valid on the server, so a stored copy cannot + // be used to reconnect - but it should still not be left in storage + if (!await UserProfileDBManager().removeStoredSession(prf, session)) { + debug("API : Expired session could not be removed from storage"); + } + + prf.hasSession = false; + } + } + /* * Check that the remote server is available. * Ping the api/ endpoint, which does not require user authentication @@ -537,17 +778,20 @@ class InvenTreeAPI { /* * Check that the user is authenticated * Fetch the user information + * + * The user information is only replaced if the check succeeds - a failed check + * (e.g. network error while connected) must not discard the current identity. + * It is cleared on disconnect, and when the session expires. */ - Future _checkAuth() async { + Future _checkAuth() async { debug("Checking user auth @ ${_URL_ME}"); - userInfo.clear(); - - final response = await get(_URL_ME); + // Do not display an error for an unexpected status code here, + // the caller determines what to show the user + final response = await get(_URL_ME, expectedStatusCode: null); if (response.successful() && response.statusCode == 200) { userInfo = response.asMap(); - return true; } else { debug( "Auth request failed: Server returned status ${response.statusCode}", @@ -555,126 +799,30 @@ class InvenTreeAPI { if (response.data != null) { debug("Server response: ${response.data.toString()}"); } - - return false; } + + return response; } /* - * Fetch a token from the server, - * with a temporary authentication header + * Prepare to authenticate against the server for the provided profile. + * Any stored session / CSRF cookies are discarded (in memory only), + * but other cookies (e.g. MFA "trusted device") are retained. + * The session is not persisted until authentication succeeds (see InvenTreeAuth). */ - Future fetchToken( - UserProfile userProfile, - String username, - String password, { - bool showDialog = true, - }) async { - debug("Fetching user token from ${userProfile.server}"); + Future beginAuthentication(UserProfile userProfile) async { + disconnectFromServer(); - profile = userProfile; - - await _refreshHttpsPolicy(); - - // Form a name to request the token with - String platform_name = "inventree-mobile-app"; - - final deviceInfo = await getDeviceInfo(); - - if (Platform.isAndroid) { - platform_name += "-android"; - } else if (Platform.isIOS) { - platform_name += "-ios"; - } else if (Platform.isMacOS) { - platform_name += "-macos"; - } else if (Platform.isLinux) { - platform_name += "-linux"; - } else if (Platform.isWindows) { - platform_name += "-windows"; - } - - if (deviceInfo.containsKey("name")) { - platform_name += "-" + (deviceInfo["name"] as String); - } - - if (deviceInfo.containsKey("model")) { - platform_name += "-" + (deviceInfo["model"] as String); - } - - if (deviceInfo.containsKey("systemVersion")) { - platform_name += "-" + (deviceInfo["systemVersion"] as String); - } - - // The token endpoint depends on the server API version, which may not be - // known yet (first login), or may belong to a different server profile. - // Note: newer servers will not re-issue an existing token via the legacy endpoint - final infoResponse = await get(_makeUrl("/api/", base: userProfile.server)); - - if (!infoResponse.successful()) { - return infoResponse; - } - - serverInfo = {...infoResponse.asMap()}; - - // Construct auth header from username and password - String authHeader = - "Basic " + base64Encode(utf8.encode("${username}:${password}")); - - String actualTokenUrl = supportsNewUserEndpoints - ? _URL_TOKEN - : "user/token/"; - - // Perform request to get a token - final response = await get( - actualTokenUrl, - params: {"name": platform_name}, - headers: {HttpHeaders.authorizationHeader: authHeader}, + final SessionStore store = await UserProfileDBManager().loadSession( + userProfile, ); - final data = response.asMap(); + store.clearAuthCookies(); - // Invalid response - if (!response.successful()) { - if (showDialog) { - switch (response.statusCode) { - case 401: - case 403: - showServerError( - apiUrl, - L10().serverAuthenticationError, - L10().invalidUsernamePassword, - ); - default: - showStatusCodeError(apiUrl, response.statusCode); - } - } + profile = userProfile; + session = store; - debug("Token request failed: STATUS ${response.statusCode}"); - - if (response.data != null) { - debug("Response data: ${response.data.toString()}"); - } - } else if (!data.containsKey("token")) { - // The request was otherwise successful, but the response is missing - // the expected token field - a distinct (and much rarer) problem from - // an authentication failure, so only reachable when that did NOT occur - if (showDialog) { - showServerError( - apiUrl, - L10().tokenMissing, - L10().tokenMissingFromResponse, - ); - } - } - - // Save the token to the user profile - userProfile.token = (data["token"] ?? "") as String; - - debug("Received token from server"); - - await UserProfileDBManager().updateProfile(userProfile); - - return response; + await _refreshHttpsPolicy(); } void disconnectFromServer() { @@ -682,8 +830,13 @@ class InvenTreeAPI { _connected = false; _connecting = false; + _loginRequired = false; profile = null; + // Drop the in-memory session (it remains in secure storage) + session.onChanged = null; + session = SessionStore(); + _resetHttpClient(); // Clear received settings @@ -693,6 +846,7 @@ class InvenTreeAPI { roles.clear(); _plugins.clear(); serverInfo.clear(); + userInfo = {}; _connectionStatusChanged(); } @@ -713,8 +867,18 @@ class InvenTreeAPI { return false; } + // Load the stored session, and persist any changes the server makes to it + final SessionStore store = await UserProfileDBManager().loadSession(prf); + + store.onChanged = () { + UserProfileDBManager().saveSession(prf, store); + }; + + session = store; + // Cancel notification timer _notification_timer?.cancel(); + _notification_timer = null; _connecting = true; _connectionStatusChanged(); @@ -724,6 +888,8 @@ class InvenTreeAPI { _connecting = false; if (_connected) { + _loginScreenOpen = false; + showSnackIcon( L10().serverConnected, icon: TablerIcons.server, @@ -967,7 +1133,7 @@ class InvenTreeAPI { .timeout(Duration(seconds: 10)); // Set headers - defaultHeaders().forEach((key, value) { + defaultHeaders(url: _uri.toString()).forEach((key, value) { _request?.headers.set(key, value); }); } on SocketException catch (error) { @@ -1008,6 +1174,10 @@ class InvenTreeAPI { hideLoadingOverlay(); OpenFilex.open(local_path); } + } else if (_isUnauthorized(_uri, response.statusCode) && + await _handleUnauthorized(url)) { + // User has been directed to login, rather than shown an error + hideLoadingOverlay(); } else { showStatusCodeError(url, response.statusCode); } @@ -1047,7 +1217,7 @@ class InvenTreeAPI { final request = http.MultipartRequest(method, uri); // Default headers - defaultHeaders().forEach((key, value) { + defaultHeaders(method: method, url: uri.toString()).forEach((key, value) { request.headers[key] = value; }); @@ -1079,9 +1249,14 @@ class InvenTreeAPI { response.statusCode = httpResponse.statusCode; - jsondata = httpResponse.body; + // package:http folds multiple Set-Cookie headers into a single value + final String? setCookie = httpResponse.headers["set-cookie"]; - response.data = json.decode(jsondata); + if (setCookie != null) { + session.captureHeaders(uri, splitSetCookieHeader(setCookie)); + } + + jsondata = httpResponse.body; // Report a server-side error if (response.statusCode == 500) { @@ -1092,11 +1267,30 @@ class InvenTreeAPI { "method": request.method, "name": name, "statusCode": response.statusCode.toString(), - "requestHeaders": request.headers.toString(), - "responseHeaders": httpResponse.headers.toString(), + "requestHeaders": redactHeaders(request.headers), + "responseHeaders": redactHeaders(httpResponse.headers), + "responseData": _truncate(httpResponse.body), }, ); } + + try { + response.data = json.decode(jsondata); + } on FormatException { + // An authentication failure may not have a JSON body (e.g. empty, + // or an HTML page from a proxy) - it is handled below, rather than + // reported as an invalid response + if (!_isUnauthorized(uri, response.statusCode)) { + rethrow; + } + + response.data = {}; + } + + if (_isUnauthorized(uri, response.statusCode) && + await _handleUnauthorized(url)) { + _markLoginRequired(response); + } } on SocketException catch (error) { showServerError( url, @@ -1112,15 +1306,18 @@ class InvenTreeAPI { L10().formatExceptionJson + ":\n${jsondata}", ); - sentryReportMessage( - "Error decoding JSON response from server", - context: { - "method": "uploadFile", - "url": url, - "statusCode": response.statusCode.toString(), - "data": jsondata, - }, - ); + // Server errors have already been reported (including the response data) + if (response.statusCode < 500) { + sentryReportMessage( + "Error decoding JSON response from server", + context: { + "method": "uploadFile", + "url": url, + "statusCode": response.statusCode.toString(), + "data": jsondata, + }, + ); + } } on TimeoutException { showTimeoutError(url); response.error = "TimeoutException"; @@ -1303,20 +1500,6 @@ class InvenTreeAPI { return null; } - // Add any required query parameters to the URL using ?key=value notation - if (urlParams.isNotEmpty) { - String query = "?"; - - urlParams.forEach((k, v) => query += "${k}=${v}&"); - - _url += query; - } - - // Remove extraneous character if present - if (_url.endsWith("&")) { - _url = _url.substring(0, _url.length - 1); - } - Uri? _uri = Uri.tryParse(_url); if (_uri == null || _uri.host.isEmpty) { @@ -1324,6 +1507,17 @@ class InvenTreeAPI { return null; } + // Add any required query parameters to the URL (merged with any already present). + // Values are URL encoded - e.g. a search for "M3 & M4" or "C++" + if (urlParams.isNotEmpty) { + _uri = _uri.replace( + queryParameters: { + ..._uri.queryParametersAll, + ...urlParams, + }, + ); + } + HttpClientRequest? _request; // Attempt to open a connection to the server @@ -1333,7 +1527,10 @@ class InvenTreeAPI { _request = await _openUrlWithRetry(method, _uri); // Default headers - defaultHeaders().forEach((key, value) { + defaultHeaders(method: method, url: _uri.toString()).forEach(( + key, + value, + ) { _request?.headers.set(key, value); }); @@ -1463,7 +1660,7 @@ class InvenTreeAPI { .openUrl(method, uri) .timeout(Duration(seconds: 10)); - defaultHeaders().forEach((key, value) { + defaultHeaders(method: method, url: uri.toString()).forEach((key, value) { request.headers.set(key, value); }); @@ -1539,9 +1736,29 @@ class InvenTreeAPI { response.statusCode = _response.statusCode; + // Store any cookies provided by the server (e.g. session, CSRF token) + session.captureHeaders( + request.uri, + _response.headers[HttpHeaders.setCookieHeader], + ); + // If the server returns a server error code, alert the user if (_response.statusCode >= 500) { - showStatusCodeError(url, _response.statusCode); + // Read the response body, which may describe the error + // (not necessarily JSON - e.g. an HTML error page from a proxy) + final String body = ignoreResponse + ? "" + : await _response + .transform(const Utf8Decoder(allowMalformed: true)) + .join(); + + try { + response.data = body.isEmpty ? {} : json.decode(body) ?? {}; + } on FormatException { + response.data = {}; + } + + showStatusCodeError(url, _response.statusCode, details: response.data); // Some server errors are not ones for us to worry about! switch (_response.statusCode) { @@ -1556,9 +1773,9 @@ class InvenTreeAPI { "url": request.uri.toString(), "method": request.method, "statusCode": _response.statusCode.toString(), - "requestHeaders": request.headers.toString(), - "responseHeaders": _response.headers.toString(), - "responseData": response.data.toString(), + "requestHeaders": redactHttpHeaders(request.headers), + "responseHeaders": redactHttpHeaders(_response.headers), + "responseData": _truncate(body), }, ); } @@ -1567,8 +1784,12 @@ class InvenTreeAPI { ? {} : await responseToJson(url, _response) ?? {}; - // First check that the returned status code is what we expected - if (statusCode != null && statusCode != _response.statusCode) { + if (_isUnauthorized(request.uri, _response.statusCode) && + await _handleUnauthorized(url)) { + // User has been directed to login, rather than shown an error + _markLoginRequired(response); + } else if (statusCode != null && statusCode != _response.statusCode) { + // Check that the returned status code is what we expected showStatusCodeError( url, _response.statusCode, @@ -1605,6 +1826,10 @@ class InvenTreeAPI { return response; } + // Limit the size of response data included in error reports + String _truncate(String data, {int length = 2000}) => + data.length > length ? "${data.substring(0, length)}..." : data; + /* * Convert a HttpClientResponse response object to JSON */ @@ -1632,7 +1857,7 @@ class InvenTreeAPI { sentryReportMessage( "Error decoding JSON response from server", context: { - "headers": response.headers.toString(), + "headers": redactHttpHeaders(response.headers), "statusCode": response.statusCode.toString(), "data": body.toString(), "endpoint": url, @@ -1640,11 +1865,18 @@ class InvenTreeAPI { ); } - showServerError( - url, - L10().formatException, - L10().formatExceptionJson + ":\n${body}", - ); + // An authentication failure may not have a JSON body (e.g. from a proxy). + // It is handled as such by the caller (see _handleUnauthorized), + // rather than reported as an invalid response + final Uri? uri = Uri.tryParse(url); + + if (uri == null || !_isUnauthorized(uri, response.statusCode)) { + showServerError( + url, + L10().formatException, + L10().formatExceptionJson + ":\n${body}", + ); + } // Return an empty map return {}; @@ -1717,28 +1949,48 @@ class InvenTreeAPI { return Intl.getCurrentLocale(); } - // Return a list of request headers - Map defaultHeaders() { - Map headers = {}; + // HTTP methods which require CSRF protection + static const List _unsafeMethods = ["POST", "PUT", "PATCH", "DELETE"]; - if (hasToken) { - headers[HttpHeaders.authorizationHeader] = _authorizationHeader(); - } + /* + * Return a list of request headers. + * + * Session credentials (cookies, CSRF token) are only included + * if [url] points at the active server - never for a foreign host. + * If [url] is not provided, the request is assumed to be to the server. + */ + Map defaultHeaders({String method = "GET", String? url}) { + Map headers = {}; headers[HttpHeaders.acceptHeader] = "application/json"; headers[HttpHeaders.contentTypeHeader] = "application/json"; headers[HttpHeaders.acceptLanguageHeader] = currentLocale; - return headers; - } + final Uri? target = Uri.tryParse( + (url == null || url.isEmpty) ? baseUrl : makeUrl(url), + ); - // Construct a token authorization header - String _authorizationHeader() { - if (token.isNotEmpty) { - return "Token ${token}"; - } else { - return ""; + if (target == null || !session.isServerUri(target)) { + return headers; } + + final String cookies = session.cookieHeader(target); + + if (cookies.isNotEmpty) { + headers[HttpHeaders.cookieHeader] = cookies; + } + + if (_unsafeMethods.contains(method.toUpperCase())) { + if (session.hasCsrfToken) { + headers["X-CSRFToken"] = session.csrfToken; + } + + // Django CSRF protection checks the Origin (or Referer, for HTTPS) + headers["Origin"] = target.origin; + headers[HttpHeaders.refererHeader] = baseUrl; + } + + return headers; } static String get staticImage => "/static/img/blank_image.png"; @@ -1791,7 +2043,7 @@ class InvenTreeAPI { }, ); }, - httpHeaders: defaultHeaders(), + httpHeaders: defaultHeaders(url: url), height: height, width: width, cacheManager: imageCacheManager, diff --git a/lib/auth/allauth_client.dart b/lib/auth/allauth_client.dart new file mode 100644 index 00000000..165232c6 --- /dev/null +++ b/lib/auth/allauth_client.dart @@ -0,0 +1,102 @@ +import "package:inventree/api.dart"; +import "package:inventree/auth/auth_result.dart"; +import "package:inventree/helpers.dart"; + +/* + * Thin wrapper around the allauth "headless" API endpoints exposed by the server. + * InvenTree only exposes the "browser" client, which uses session + CSRF cookies. + * + * All requests are made via InvenTreeAPI, which attaches (and captures) + * the session cookies for the active profile. + */ +class AllauthClient { + const AllauthClient(); + + static const String URL_CONFIG = "auth/v1/config"; + static const String URL_SESSION = "auth/v1/auth/session"; + static const String URL_LOGIN = "auth/v1/auth/login"; + static const String URL_MFA_AUTHENTICATE = "auth/v1/auth/2fa/authenticate"; + static const String URL_MFA_TRUST = "auth/v1/auth/2fa/trust"; + static const String URL_PROVIDER_TOKEN = "auth/v1/auth/provider/token"; + + InvenTreeAPI get _api => InvenTreeAPI(); + + // Server authentication configuration + Future getConfig() async { + final response = await _api.get(URL_CONFIG, expectedStatusCode: null); + + return AuthConfig.fromResponse(response); + } + + // Current session status + Future getSession() async { + final response = await _api.get(URL_SESSION, expectedStatusCode: null); + + return AuthResult.fromResponse(response); + } + + /* + * Ensure that we have a CSRF token before making any "unsafe" requests. + * Requesting the session status causes the server to issue a CSRF cookie. + */ + Future ensureCsrf() async { + if (_api.session.hasCsrfToken) { + return true; + } + + await _api.get(URL_SESSION, expectedStatusCode: null); + + if (!_api.session.hasCsrfToken) { + debug("AllauthClient: Server did not provide a CSRF token"); + return false; + } + + return true; + } + + Future _post(String url, Map body) async { + final response = await _api.post(url, body: body, expectedStatusCode: null); + + return AuthResult.fromResponse(response); + } + + // Login with username (or email) and password + Future loginPassword({ + required String login, + required String password, + String field = "username", + }) async { + return _post(URL_LOGIN, {field: login, "password": password}); + } + + // Provide a TOTP (or recovery) code to complete a pending MFA flow + Future authenticateMfa(String code) async { + return _post(URL_MFA_AUTHENTICATE, {"code": code}); + } + + // Respond to a pending "trust this device" flow + Future trustDevice(bool trust) async { + return _post(URL_MFA_TRUST, {"trust": trust}); + } + + /* + * Login with a token issued by a third-party (SSO) provider. + * Not yet used by the app - provided for future SSO support. + */ + Future loginProviderToken({ + required String provider, + required Map token, + String process = "login", + }) async { + return _post(URL_PROVIDER_TOKEN, { + "provider": provider, + "process": process, + "token": token, + }); + } + + // End the server session (the server responds with 401 on success) + Future logout() async { + await _api.delete(URL_SESSION); + } +} diff --git a/lib/auth/auth_manager.dart b/lib/auth/auth_manager.dart new file mode 100644 index 00000000..821ef08b --- /dev/null +++ b/lib/auth/auth_manager.dart @@ -0,0 +1,186 @@ +import "package:inventree/api.dart"; +import "package:inventree/auth/allauth_client.dart"; +import "package:inventree/auth/auth_method.dart"; +import "package:inventree/auth/auth_result.dart"; +import "package:inventree/auth/session_store.dart"; +import "package:inventree/helpers.dart"; +import "package:inventree/l10.dart"; +import "package:inventree/user_profile.dart"; + +/* + * Coordinates authentication against an InvenTree server. + * + * - Starts a login using an AuthMethod (e.g. username / password) + * - Steps through any additional flows required by the server (e.g. MFA) + * - Persists the resulting session cookies against the profile + * + * The UI only needs to react to the AuthResult returned by each step. + */ +class InvenTreeAuth { + factory InvenTreeAuth() { + return _instance; + } + + InvenTreeAuth._internal(); + + static final InvenTreeAuth _instance = InvenTreeAuth._internal(); + + final AllauthClient client = const AllauthClient(); + + // Profile which is currently being authenticated + UserProfile? _profile; + + // Username used for the current login - saved against the profile on success + String _username = ""; + + /* + * Start a new login for the provided profile + */ + Future beginLogin(UserProfile profile, AuthMethod method) async { + final InvenTreeAPI api = InvenTreeAPI(); + + _profile = profile; + _username = method.username; + + debug("InvenTreeAuth: Starting login for ${profile.name}"); + + await api.beginAuthentication(profile); + + // Check the server is available, and supports session authentication + if (!await api.checkServer()) { + return AuthResult.failed(""); + } + + final AuthConfig config = await client.getConfig(); + + if (!await client.ensureCsrf()) { + return AuthResult.failed(L10().csrfTokenMissing); + } + + final AuthResult result = await method.authenticate(client, config); + + return _handleResult(result); + } + + /* + * Submit a code (TOTP or recovery code) for a pending MFA flow. + * If the server then asks whether to trust this device, answer with [trustDevice] + */ + Future submitMfaCode( + String code, { + bool trustDevice = false, + }) async { + AuthResult result = await client.authenticateMfa(code); + + if (result.pendingFlow?.id == FLOW_MFA_TRUST) { + result = await client.trustDevice(trustDevice); + } + + return _handleResult(result); + } + + Future _handleResult(AuthResult result) async { + debug("InvenTreeAuth: ${result}"); + + switch (result.status) { + case AuthStatus.authenticated: + if (!await _completeLogin()) { + return AuthResult.failed(L10().sessionSaveFailed); + } + case AuthStatus.flowPending: + break; + case AuthStatus.failed: + // The server already has an authenticated session for these cookies + if (result.statusCode == 409) { + InvenTreeAPI().session.clearAuthCookies(); + return AuthResult.failed(L10().authSessionConflict, statusCode: 409); + } + } + + return result; + } + + /* + * Login completed - persist the session cookies against the profile. + * + * Returns false if the session could not be saved. In that case the login is + * treated as failed: the new session is ended on the server and discarded, + * rather than leaving the user apparently logged in without a stored session. + */ + Future _completeLogin() async { + final UserProfile? profile = _profile; + + if (profile == null) { + return true; + } + + final InvenTreeAPI api = InvenTreeAPI(); + + if (!await UserProfileDBManager().saveSession(profile, api.session)) { + debug( + "InvenTreeAuth: Login succeeded, but the session could not be saved", + ); + + await client.logout(); + api.session.clearAuthCookies(); + + profile.hasSession = false; + _profile = null; + _username = ""; + + return false; + } + + profile.hasSession = api.session.hasSession; + + if (_username.isNotEmpty && _username != profile.username) { + profile.username = _username; + await UserProfileDBManager().updateProfile(profile); + } + + _profile = null; + _username = ""; + + return true; + } + + /* + * Logout the provided profile. + * If the profile is currently connected, the server session is also ended. + * + * Returns false if the stored session could not be removed from the device - + * the profile may still be logged in, and the user must be told. + */ + Future logout(UserProfile profile) async { + final InvenTreeAPI api = InvenTreeAPI(); + + final bool active = api.profile?.key == profile.key; + + if (active && api.session.hasSession) { + await client.logout(); + } + + // Remove the session, but keep any other cookies (e.g. the MFA "trusted device" + // cookie) - as a browser does on logout + final SessionStore session = active + ? api.session + : await UserProfileDBManager().loadSession(profile); + + final bool removed = await UserProfileDBManager().removeStoredSession( + profile, + session, + ); + + if (!removed) { + debug("InvenTreeAuth: Logout - stored session could not be removed"); + } + + profile.hasSession = !removed; + + if (active) { + api.disconnectFromServer(); + } + + return removed; + } +} diff --git a/lib/auth/auth_method.dart b/lib/auth/auth_method.dart new file mode 100644 index 00000000..984bcdf7 --- /dev/null +++ b/lib/auth/auth_method.dart @@ -0,0 +1,43 @@ +import "package:inventree/auth/allauth_client.dart"; +import "package:inventree/auth/auth_result.dart"; + +/* + * A method for starting a login against the server. + * + * Each method only performs the *initial* authentication step - + * any subsequent flows (e.g. MFA) are handled by InvenTreeAuth, + * regardless of how the login was started. + * + * Future SSO support adds a ProviderAuthMethod which obtains a token + * from the provider and calls AllauthClient.loginProviderToken() + */ +abstract class AuthMethod { + const AuthMethod(); + + // Username to remember against the profile once login succeeds (if any) + String get username => ""; + + Future authenticate(AllauthClient client, AuthConfig config); +} + +/* + * Login with username (or email) and password + */ +class PasswordAuthMethod extends AuthMethod { + const PasswordAuthMethod(this.login, this.password); + + final String login; + final String password; + + @override + String get username => login; + + @override + Future authenticate(AllauthClient client, AuthConfig config) { + return client.loginPassword( + login: login, + password: password, + field: config.loginField, + ); + } +} diff --git a/lib/auth/auth_result.dart b/lib/auth/auth_result.dart new file mode 100644 index 00000000..4035fc56 --- /dev/null +++ b/lib/auth/auth_result.dart @@ -0,0 +1,287 @@ +import "package:inventree/api.dart"; + +/* + * Data types for responses from the (allauth headless) authentication API. + * Ref: https://docs.allauth.org/en/latest/headless/openapi-specification/ + */ + +// Flow identifiers (as returned by the server in the "flows" list) +const String FLOW_LOGIN = "login"; +const String FLOW_MFA_AUTHENTICATE = "mfa_authenticate"; +const String FLOW_MFA_TRUST = "mfa_trust"; +const String FLOW_MFA_REGISTER = "mfa_register"; +const String FLOW_PROVIDER_REDIRECT = "provider_redirect"; +const String FLOW_PROVIDER_TOKEN = "provider_token"; +const String FLOW_PROVIDER_SIGNUP = "provider_signup"; +const String FLOW_VERIFY_EMAIL = "verify_email"; + +// MFA authenticator types +const String MFA_TYPE_TOTP = "totp"; +const String MFA_TYPE_RECOVERY_CODES = "recovery_codes"; +const String MFA_TYPE_WEBAUTHN = "webauthn"; + +// MFA types which the app is able to complete +const List SUPPORTED_MFA_TYPES = [ + MFA_TYPE_TOTP, + MFA_TYPE_RECOVERY_CODES, +]; + +enum AuthStatus { + // User is fully authenticated + authenticated, + // Further action is required (see AuthResult.pendingFlow) + flowPending, + // Authentication failed (see AuthResult.errors) + failed, +} + +/* + * An authentication "flow" - e.g. a pending MFA step + */ +class AuthFlow { + AuthFlow({ + required this.id, + this.isPending = false, + this.types = const [], + this.provider = "", + }); + + factory AuthFlow.fromJson(Map json) { + List types = []; + + if (json["types"] is List) { + types = (json["types"] as List).map((t) => t.toString()).toList(); + } + + String provider = ""; + + if (json["provider"] is Map) { + provider = ((json["provider"] as Map)["id"] ?? "").toString(); + } + + return AuthFlow( + id: (json["id"] ?? "").toString(), + isPending: (json["is_pending"] ?? false) == true, + types: types, + provider: provider, + ); + } + + final String id; + final bool isPending; + + // Available authenticator types (for MFA flows) + final List types; + + // Provider ID (for SSO flows) + final String provider; + + // Can the app complete this MFA flow (i.e. supports at least one of the types)? + bool get isSupportedMfa => + id == FLOW_MFA_AUTHENTICATE && + types.any((t) => SUPPORTED_MFA_TYPES.contains(t)); + + bool get supportsRecoveryCodes => types.contains(MFA_TYPE_RECOVERY_CODES); + + @override + String toString() => "AuthFlow(${id}, pending=${isPending}, types=${types})"; +} + +/* + * Result of an authentication request + */ +class AuthResult { + AuthResult({ + required this.status, + this.statusCode = -1, + this.pendingFlow, + this.errors = const [], + this.user = const {}, + }); + + factory AuthResult.failed(String error, {int statusCode = -1}) => AuthResult( + status: AuthStatus.failed, + statusCode: statusCode, + errors: error.isEmpty ? [] : [error], + ); + + /* + * Construct an AuthResult from an allauth API response + */ + factory AuthResult.fromResponse(APIResponse response) { + final int statusCode = response.statusCode; + final Map body = response.asMap(); + + final Map data = body["data"] is Map + ? body["data"] as Map + : {}; + + final Map meta = body["meta"] is Map + ? body["meta"] as Map + : {}; + + if (statusCode == 200 && meta["is_authenticated"] == true) { + return AuthResult( + status: AuthStatus.authenticated, + statusCode: statusCode, + user: data["user"] is Map + ? data["user"] as Map + : {}, + ); + } + + if (statusCode == 401 && data["flows"] is List) { + for (var flow in data["flows"] as List) { + if (flow is Map) { + final AuthFlow f = AuthFlow.fromJson(flow); + + if (f.isPending) { + return AuthResult( + status: AuthStatus.flowPending, + statusCode: statusCode, + pendingFlow: f, + ); + } + } + } + } + + return AuthResult( + status: AuthStatus.failed, + statusCode: statusCode, + errors: extractErrors(body), + ); + } + + final AuthStatus status; + final int statusCode; + final AuthFlow? pendingFlow; + final List errors; + final Map user; + + bool get authenticated => status == AuthStatus.authenticated; + + String get errorMessage => errors.join("\n"); + + @override + String toString() => + "AuthResult(${status.name}, status=${statusCode}, flow=${pendingFlow})"; +} + +/* + * Extract human-readable error messages from an allauth (or DRF) error response + */ +List extractErrors(Map body) { + List errors = []; + + if (body["errors"] is List) { + for (var error in body["errors"] as List) { + if (error is Map && error["message"] != null) { + errors.add(error["message"].toString()); + } + } + } + + for (final key in ["detail", "error", "message"]) { + if (errors.isEmpty && body[key] is String) { + errors.add(body[key] as String); + } + } + + return errors; +} + +/* + * A (social) authentication provider configured on the server. + * Not yet used by the app - provided for future SSO support. + */ +class AuthProvider { + AuthProvider({ + required this.id, + required this.name, + this.flows = const [], + this.clientId = "", + }); + + factory AuthProvider.fromJson(Map json) => AuthProvider( + id: (json["id"] ?? "").toString(), + name: (json["name"] ?? "").toString(), + flows: json["flows"] is List + ? (json["flows"] as List).map((f) => f.toString()).toList() + : [], + clientId: (json["client_id"] ?? "").toString(), + ); + + final String id; + final String name; + final List flows; + final String clientId; + + // Can this provider be used with a native (token based) login? + bool get supportsTokenLogin => flows.contains(FLOW_PROVIDER_TOKEN); +} + +/* + * Server authentication configuration + */ +class AuthConfig { + AuthConfig({ + this.loginMethods = const ["username"], + this.mfaTypes = const [], + this.providers = const [], + }); + + factory AuthConfig.fromResponse(APIResponse response) { + final Map body = response.asMap(); + + if (!response.successful() || body["data"] is! Map) { + return AuthConfig(); + } + + final Map data = body["data"] as Map; + + final Map account = data["account"] is Map + ? data["account"] as Map + : {}; + + final Map mfa = data["mfa"] is Map + ? data["mfa"] as Map + : {}; + + final Map social = + data["socialaccount"] is Map + ? data["socialaccount"] as Map + : {}; + + List loginMethods = []; + + if (account["login_methods"] is List) { + loginMethods = (account["login_methods"] as List) + .map((m) => m.toString()) + .toList(); + } + + return AuthConfig( + loginMethods: loginMethods.isEmpty ? ["username"] : loginMethods, + mfaTypes: mfa["supported_types"] is List + ? (mfa["supported_types"] as List).map((t) => t.toString()).toList() + : [], + providers: social["providers"] is List + ? (social["providers"] as List) + .whereType>() + .map((p) => AuthProvider.fromJson(p)) + .toList() + : [], + ); + } + + final List loginMethods; + final List mfaTypes; + final List providers; + + // Which field should the "login" value be sent as? + String get loginField => + (!loginMethods.contains("username") && loginMethods.contains("email")) + ? "email" + : "username"; +} diff --git a/lib/auth/session_store.dart b/lib/auth/session_store.dart new file mode 100644 index 00000000..4ee60aa9 --- /dev/null +++ b/lib/auth/session_store.dart @@ -0,0 +1,408 @@ +import "dart:convert"; +import "dart:io"; + +// Default Django cookie names (InvenTree does not override these) +const String SESSION_COOKIE_NAME = "sessionid"; +const String CSRF_COOKIE_NAME = "csrftoken"; + +/* + * A single cookie, as received from the server. + */ +class StoredCookie { + StoredCookie({ + required this.name, + required this.value, + required this.domain, + this.hostOnly = true, + this.path = "/", + this.expires, + this.secure = false, + }); + + factory StoredCookie.fromJson(Map json) => StoredCookie( + name: (json["name"] ?? "") as String, + value: (json["value"] ?? "") as String, + domain: (json["domain"] ?? "") as String, + hostOnly: (json["hostOnly"] ?? true) as bool, + path: (json["path"] ?? "/") as String, + expires: json["expires"] == null + ? null + : DateTime.tryParse(json["expires"] as String), + secure: (json["secure"] ?? false) as bool, + ); + + final String name; + final String value; + + // Host (hostOnly) or domain (and subdomains) the cookie applies to + final String domain; + final bool hostOnly; + + final String path; + + // Expiry time - null for a "session" cookie (kept until cleared) + final DateTime? expires; + + // Only send over HTTPS + final bool secure; + + bool get isExpired => expires != null && expires!.isBefore(DateTime.now()); + + // Does this cookie apply to the provided URI? + bool matches(Uri uri) { + if (isExpired) return false; + + if (secure && uri.scheme != "https") return false; + + if (!domainMatches(uri.host, domain, hostOnly: hostOnly)) return false; + + String requestPath = uri.path.isEmpty ? "/" : uri.path; + + if (path == "/" || requestPath == path) return true; + + final String prefix = path.endsWith("/") ? path : "${path}/"; + + return requestPath.startsWith(prefix); + } + + Map toJson() => { + "name": name, + "value": value, + "domain": domain, + "hostOnly": hostOnly, + "path": path, + "expires": expires?.toIso8601String(), + "secure": secure, + }; +} + +/* + * Return true if the request host matches the cookie domain (RFC 6265 5.1.3) + */ +bool domainMatches(String host, String domain, {bool hostOnly = false}) { + host = host.toLowerCase(); + domain = domain.toLowerCase(); + + if (host == domain) return true; + + if (hostOnly) return false; + + // Never domain-match an IP address + if (InternetAddress.tryParse(host) != null) return false; + + return host.endsWith(".${domain}"); +} + +/* + * Split a folded "Set-Cookie" header (as returned by package:http, + * which joins multiple headers with a comma) into individual values. + * Commas also appear inside "Expires" dates, so only split where the + * comma is followed by a new "name=" pair. + */ +List splitSetCookieHeader(String header) { + return header + .split(RegExp(r",(?=\s*[^;,=\s]+=)")) + .map((value) => value.trim()) + .where((value) => value.isNotEmpty) + .toList(); +} + +/* + * Return the origin (scheme, host and port) of the provided server address, + * or an empty string if the address is not valid. + * Default ports are included, so "https://host" and "https://host:443" match. + */ +String serverOrigin(String server) { + final Uri? uri = Uri.tryParse(server); + + if (uri == null || uri.host.isEmpty || uri.scheme.isEmpty) { + return ""; + } + + return "${uri.scheme.toLowerCase()}://${uri.host.toLowerCase()}:${uri.port}"; +} + +/* + * Cookie jar for the session with a single InvenTree server. + * + * Cookies are only accepted from (and sent to) the server origin, + * so that session credentials can never leak to another host. + * The jar can be serialized for storage in secure storage, and records the + * origin which issued the cookies - a stored jar is only ever restored for + * that same origin. + */ +class SessionStore { + SessionStore({String server = ""}) { + _serverUri = Uri.tryParse(server); + } + + /* + * Restore a stored jar for the provided server. + * + * The cookies are discarded (and [rejected] is set) if they were issued by + * a different origin - e.g. the profile server address has since been edited + * (by the user, or by managed configuration). Otherwise the session could be + * sent to a different service on the same host, or over plain HTTP. + */ + factory SessionStore.fromJson(String server, String? data) { + final store = SessionStore(server: server); + + if (data == null || data.isEmpty) { + return store; + } + + try { + final dynamic decoded = json.decode(data); + + // Data stored without an origin cannot be verified (and is never restored) + final String origin = decoded is Map + ? (decoded["origin"] ?? "").toString() + : ""; + + if (origin.isEmpty || origin != store.origin) { + store.rejected = true; + return store; + } + + final List cookies = decoded["cookies"] as List; + + for (var item in cookies) { + final cookie = StoredCookie.fromJson(item as Map); + + if (cookie.name.isNotEmpty && !cookie.isExpired) { + store._cookies[cookie.name] = cookie; + } + } + } catch (error) { + // Corrupt data - start with an empty jar + store._cookies.clear(); + } + + // These cookies are already stored + store._persisted = Map.of(store._cookies); + + return store; + } + + Uri? _serverUri; + + // Origin of the server this jar belongs to + String get origin => serverOrigin(_serverUri?.toString() ?? ""); + + // Set if stored cookies were discarded, as they were issued by a different origin + bool rejected = false; + + final Map _cookies = {}; + + // Cookies as last written to storage (see markPersisted) + Map _persisted = {}; + + // Callback when the contents of the jar change (e.g. to persist it) + void Function()? onChanged; + + void _changed() => onChanged?.call(); + + // Names of all (non-expired) cookies - for debugging, never log values! + List get cookieNames => _cookies.values + .where((cookie) => !cookie.isExpired) + .map((cookie) => cookie.name) + .toList(); + + String _value(String name) { + final StoredCookie? cookie = _cookies[name]; + + if (cookie == null || cookie.isExpired) return ""; + + return cookie.value; + } + + String get csrfToken => _value(CSRF_COOKIE_NAME); + + bool get hasCsrfToken => csrfToken.isNotEmpty; + + // Do we have a session cookie (which may or may not still be valid on the server)? + bool get hasSession => _value(SESSION_COOKIE_NAME).isNotEmpty; + + bool get isEmpty => cookieNames.isEmpty; + + /* + * Return true if the provided URI points at the server this jar belongs to. + * Credentials (cookies / CSRF token) must only ever be sent to this host. + */ + bool isServerUri(Uri uri) { + final Uri? server = _serverUri; + + if (server == null || server.host.isEmpty) return false; + + return uri.host.toLowerCase() == server.host.toLowerCase() && + uri.scheme == server.scheme && + uri.port == server.port; + } + + /* + * Store cookies received from the server in response to a request to [uri] + */ + void capture(Uri uri, List cookies) { + if (cookies.isEmpty || !isServerUri(uri)) return; + + bool changed = false; + + for (final cookie in cookies) { + if (_store(uri, cookie)) changed = true; + } + + if (changed) _changed(); + } + + /* + * Store cookies from raw "Set-Cookie" header values. + * Each value is parsed individually, so one malformed cookie + * does not prevent the others from being stored. + */ + void captureHeaders(Uri uri, List? setCookieHeaders) { + if (setCookieHeaders == null || setCookieHeaders.isEmpty) return; + + List cookies = []; + + for (final header in setCookieHeaders) { + try { + cookies.add(Cookie.fromSetCookieValue(header)); + } catch (error) { + // Ignore malformed cookie + } + } + + capture(uri, cookies); + } + + // Store a single cookie, returning true if the jar changed + bool _store(Uri uri, Cookie cookie) { + String domain = uri.host; + bool hostOnly = true; + + if (cookie.domain != null && cookie.domain!.isNotEmpty) { + String d = cookie.domain!.toLowerCase(); + + if (d.startsWith(".")) d = d.substring(1); + + // Reject cookies for a domain the server does not belong to + if (!domainMatches(uri.host, d)) return false; + + domain = d; + hostOnly = false; + } + + DateTime? expires = cookie.expires; + + // Max-Age takes precedence over Expires + if (cookie.maxAge != null) { + expires = DateTime.now().add(Duration(seconds: cookie.maxAge!)); + } + + // Deleted (or expired) by the server + if (cookie.value.isEmpty || + (expires != null && !expires.isAfter(DateTime.now()))) { + final bool removed = _cookies.remove(cookie.name) != null; + + return removed || _persisted.containsKey(cookie.name); + } + + final stored = StoredCookie( + name: cookie.name, + value: cookie.value, + domain: domain, + hostOnly: hostOnly, + path: (cookie.path == null || cookie.path!.isEmpty) ? "/" : cookie.path!, + expires: expires, + secure: cookie.secure, + ); + + _cookies[cookie.name] = stored; + + return _differsFromPersisted(stored); + } + + /* + * Return true if the cookie differs meaningfully from the copy last persisted. + * + * Compared against the persisted copy (not the previous in-memory value), + * so that small changes accumulate - e.g. a sliding expiry which is extended + * slightly on each request is persisted once it has moved by an hour. + * Expiry changes of less than an hour are ignored, to avoid re-writing + * secure storage on every request. + */ + bool _differsFromPersisted(StoredCookie cookie) { + final StoredCookie? persisted = _persisted[cookie.name]; + + if (persisted == null || + persisted.value != cookie.value || + persisted.domain != cookie.domain || + persisted.hostOnly != cookie.hostOnly || + persisted.path != cookie.path || + persisted.secure != cookie.secure) { + return true; + } + + final DateTime? a = persisted.expires; + final DateTime? b = cookie.expires; + + if ((a == null) != (b == null)) return true; + + return a != null && b != null && a.difference(b).abs().inHours >= 1; + } + + /* + * Return a copy of the current cookies, to pass to markPersisted() + * once they have been written to storage + */ + Map snapshot() => Map.of(_cookies); + + /* + * Record the cookies which have been written to storage. + * Only called once the write succeeds - so after a failed write, the next + * change is reported again (and the write retried) + */ + void markPersisted(Map snapshot) { + _persisted = Map.of(snapshot); + } + + /* + * Construct the "Cookie" header value for a request to [uri] + * Returns an empty string if no cookies apply (or for a foreign host) + */ + String cookieHeader(Uri uri) { + if (!isServerUri(uri)) return ""; + + return _cookies.values + .where((cookie) => cookie.matches(uri)) + .map((cookie) => "${cookie.name}=${cookie.value}") + .join("; "); + } + + /* + * Remove the session and CSRF cookies, but retain any others + * (e.g. the MFA "trusted device" cookie) + */ + void clearAuthCookies() { + final bool removedSession = _cookies.remove(SESSION_COOKIE_NAME) != null; + final bool removedCsrf = _cookies.remove(CSRF_COOKIE_NAME) != null; + + if (removedSession || removedCsrf) _changed(); + } + + // Remove all cookies + void clear() { + if (_cookies.isEmpty) return; + + _cookies.clear(); + _changed(); + } + + String toJson() => json.encode({ + "origin": origin, + "cookies": _cookies.values + .where((cookie) => !cookie.isExpired) + .map((cookie) => cookie.toJson()) + .toList(), + }); +} diff --git a/lib/inventree/redact.dart b/lib/inventree/redact.dart new file mode 100644 index 00000000..c56889ba --- /dev/null +++ b/lib/inventree/redact.dart @@ -0,0 +1,340 @@ +import "dart:io"; + +import "package:sentry_flutter/sentry_flutter.dart"; + +/* + * Removal of credentials (session cookies, CSRF tokens, API tokens, passwords) + * from data which leaves the device - e.g. error reports sent to sentry.io. + * + * Applied to every Sentry event and breadcrumb (see configureSentryPrivacy), + * so credentials are removed regardless of where the data was collected. + */ + +const String REDACTED = ""; + +// Headers which contain credentials, and must never be logged or reported +const List SENSITIVE_HEADERS = [ + "authorization", + "cookie", + "set-cookie", + "x-csrftoken", +]; + +// Any map key containing one of these values is treated as a credential +const List _SENSITIVE_KEY_PARTS = [ + "authorization", + "cookie", + "csrf", + "password", + "passwd", + "secret", + "sessionid", + "token", + "mfa_trusted", + "apikey", + "api_key", + "api-key", +]; + +bool isSensitiveKey(String key) { + final String k = key.toLowerCase(); + + return _SENSITIVE_KEY_PARTS.any(k.contains); +} + +// A complete quoted value, including escaped characters (e.g. "a \"b\" c"). +// An unterminated value (e.g. truncated response data) extends to the end of the text +const String _QUOTED_VALUE = + r'''"(?:[^"\\]|\\.)*(?:"|$)|'(?:[^'\\]|\\.)*(?:'|$)'''; + +// Names of keys whose values are credentials +const String _SENSITIVE_NAMES = + "password|passwd|secret|token|api[_-]?key|access_token|refresh_token|id_token|csrftoken|csrfmiddlewaretoken|sessionid|mfa_trusted"; + +/* + * Replace a value with REDACTED, retaining any surrounding quotes + */ +String _redactedValue(String value) { + if (value.isEmpty) { + return REDACTED; + } + + final String quote = value[0]; + + if (quote == '"' || quote == "'") { + final bool closed = value.length > 1 && value.endsWith(quote); + + return "${quote}${REDACTED}${closed ? quote : ""}"; + } + + return REDACTED; +} + +// Patterns for credentials embedded in free text (log messages, headers, JSON, URLs) +final List<(RegExp, String Function(Match))> _PATTERNS = [ + // Header values: "Cookie: ...", "Authorization: ...", "X-CSRFToken: ..." + // A quoted value is redacted entirely - otherwise, to the end of the line + ( + RegExp( + r"""\b((?:set-)?cookies?|authorization|x-csrftoken)(["']?\s*[:=]\s*)(""" + + _QUOTED_VALUE + + r"""|[^\n]*)""", + caseSensitive: false, + ), + (m) => "${m[1]}${m[2]}${_redactedValue(m[3]!)}", + ), + // Session / CSRF cookies: "sessionid=abc" + ( + RegExp( + r"\b(sessionid|csrftoken|csrfmiddlewaretoken|mfa_trusted)=[^;,\s&" + "']+", + caseSensitive: false, + ), + (m) => "${m[1]}=${REDACTED}", + ), + // Key: value pairs (JSON, Python / Dart maps): "password": "a b", {password: a b, ...} + // A quoted value is redacted entirely. An unquoted value extends to the next + // "key:" pair, closing bracket or end of line (so may include whitespace) + ( + RegExp( + r"""(["']?\b(?:""" + + _SENSITIVE_NAMES + + r""")\b["']?\s*:\s*)(""" + + _QUOTED_VALUE + + r"""|(?:(?!,\s*["']?[\w-]+["']?\s*[:=])[^}\]\n])+)""", + caseSensitive: false, + ), + (m) => "${m[1]}${_redactedValue(m[2]!)}", + ), + // Key=value pairs (form data, cookies, log messages): password=abc, token="a b" + ( + RegExp( + r"""(["']?\b(?:""" + + _SENSITIVE_NAMES + + r""")\b["']?\s*=\s*)(""" + + _QUOTED_VALUE + + r"""|[^\s&;,"'}\]]+)""", + caseSensitive: false, + ), + (m) => "${m[1]}${_redactedValue(m[2]!)}", + ), + // Authorization schemes in free text: "Token abc123..." + ( + RegExp( + r"\b(Token|Bearer|Basic)\s+(?=[A-Za-z0-9._~+/=-]*\d)[A-Za-z0-9._~+/=-]{8,}", + ), + (m) => "${m[1]} ${REDACTED}", + ), + // InvenTree API tokens + ( + RegExp(r"\binv-[0-9a-f]{20,}(?:-\d{8})?\b", caseSensitive: false), + (m) => REDACTED, + ), + // Credentials in a URL: "https://user:password@host" + ( + RegExp( + r"\b([a-z][a-z0-9+.-]*://)[^/\s:@]+:[^/\s@]+@", + caseSensitive: false, + ), + (m) => "${m[1]}${REDACTED}@", + ), + // Credentials in URL query parameters + ( + RegExp( + r"([?&](?:token|access_token|refresh_token|id_token|password|secret|api_?key|key|code|sessionid|csrftoken)=)[^&#\s" + "']+", + caseSensitive: false, + ), + (m) => "${m[1]}${REDACTED}", + ), +]; + +/* + * Remove any credentials from the provided text + */ +String redactString(String text) { + for (final (pattern, replace) in _PATTERNS) { + text = text.replaceAllMapped(pattern, replace); + } + + return text; +} + +/* + * Remove any credentials from the provided value. + * Maps and lists are processed recursively - values for sensitive keys + * are removed entirely, and all strings are scrubbed. + */ +dynamic redactValue(dynamic value) { + if (value is String) { + return redactString(value); + } + + if (value is Map) { + // Keys are always strings in reported (JSON) data + return value.map( + (key, v) => MapEntry( + key.toString(), + isSensitiveKey(key.toString()) ? REDACTED : redactValue(v), + ), + ); + } + + if (value is List) { + return value.map(redactValue).toList(); + } + + return value; +} + +Map _redactHeaderMap(Map headers) => + headers.map( + (key, value) => MapEntry( + key, + SENSITIVE_HEADERS.contains(key.toLowerCase()) + ? REDACTED + : redactString(value), + ), + ); + +/* + * Return a string representation of the provided headers, + * with any credentials removed (e.g. for error reporting) + */ +String redactHeaders(Map headers) { + return _redactHeaderMap( + headers, + ).entries.map((entry) => "${entry.key}: ${entry.value}").join("\n"); +} + +String redactHttpHeaders(HttpHeaders headers) { + Map values = {}; + + headers.forEach((name, value) { + values[name] = value.join(", "); + }); + + return redactHeaders(values); +} + +/* + * Remove credentials from a Sentry breadcrumb (e.g. captured print() output) + */ +Breadcrumb? redactBreadcrumb(Breadcrumb? breadcrumb) { + if (breadcrumb == null) { + return null; + } + + if (breadcrumb.message != null) { + breadcrumb.message = redactString(breadcrumb.message!); + } + + if (breadcrumb.data != null) { + breadcrumb.data = redactValue(breadcrumb.data) as Map; + } + + return breadcrumb; +} + +/* + * Remove credentials from a Sentry event, before it is sent + */ +SentryEvent redactSentryEvent(SentryEvent event) { + final SentryMessage? message = event.message; + + if (message != null) { + message.formatted = redactString(message.formatted); + + if (message.template != null) { + message.template = redactString(message.template!); + } + + if (message.params != null) { + message.params = redactValue(message.params) as List; + } + } + + // Chained exceptions are flattened into this list by the SDK + for (final exception in event.exceptions ?? []) { + if (exception.value != null) { + exception.value = redactString(exception.value!); + } + } + + if (event.tags != null) { + event.tags = event.tags!.map( + (key, value) => + MapEntry(key, isSensitiveKey(key) ? REDACTED : redactString(value)), + ); + } + + // Deprecated by Sentry (not used by the app) - but still sent if present + // ignore: deprecated_member_use + if (event.extra != null) { + // ignore: deprecated_member_use + event.extra = redactValue(event.extra) as Map; + } + + // Context data provided by the app (SDK-provided contexts are typed objects) + for (final key in event.contexts.keys.toList()) { + final dynamic value = event.contexts[key]; + + if (value is String || value is Map || value is List) { + event.contexts[key] = isSensitiveKey(key) ? REDACTED : redactValue(value); + } + } + + event.breadcrumbs = event.breadcrumbs + ?.map(redactBreadcrumb) + .whereType() + .toList(); + + final SentryRequest? request = event.request; + + if (request != null) { + event.request = SentryRequest( + url: request.url == null ? null : redactString(request.url!), + method: request.method, + queryString: request.queryString == null + ? null + : redactString("?${request.queryString!}").substring(1), + cookies: request.cookies == null ? null : REDACTED, + fragment: request.fragment, + apiTarget: request.apiTarget, + data: redactValue(request.data), + headers: _redactHeaderMap(request.headers), + env: request.env, + ); + } + + return event; +} + +/* + * Configure Sentry so that credentials (and other personal information) + * are never sent with error reports. + * + * If redaction fails, Sentry would send the original (unredacted) data - + * so the event or breadcrumb is dropped instead (fail closed). + */ +void configureSentryPrivacy(SentryOptions options) { + options.sendDefaultPii = false; + options.maxRequestBodySize = MaxRequestBodySize.never; + + options.beforeSend = (event, hint) { + try { + return redactSentryEvent(event); + } catch (error) { + print("Error redacting Sentry event - event dropped: ${error}"); + return null; + } + }; + + options.beforeBreadcrumb = (breadcrumb, hint) { + try { + return redactBreadcrumb(breadcrumb); + } catch (error) { + return null; + } + }; +} diff --git a/lib/inventree/sentry.dart b/lib/inventree/sentry.dart index 132974a1..1ab08d8a 100644 --- a/lib/inventree/sentry.dart +++ b/lib/inventree/sentry.dart @@ -8,6 +8,7 @@ import "package:sentry_flutter/sentry_flutter.dart"; import "package:inventree/api.dart"; import "package:inventree/dsn.dart"; +import "package:inventree/inventree/redact.dart"; import "package:inventree/preferences.dart"; Future> getDeviceInfo() async { @@ -109,7 +110,9 @@ Future sentryReportMessage( } } - print("Sending user message to Sentry: ${message}, ${context}"); + print( + "Sending user message to Sentry: ${redactString(message)}, ${redactValue(context)}", + ); if (isInDebugMode()) { print("----- In dev mode. Not sending message to Sentry.io -----"); @@ -162,7 +165,9 @@ Future sentryReportError( return; } - print("----- Sentry Intercepted error: $error -----"); + print( + "----- Sentry Intercepted error: ${redactString(error.toString())} -----", + ); print(stackTrace); // Errors thrown in development mode are unlikely to be interesting. You can diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 7b9a42fb..23e76dad 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -6,6 +6,57 @@ "description": "InvenTree application title string" }, + "authFlowUnsupported": "The server requires an additional login step which is not supported by the app", + "@authFlowUnsupported": {}, + + "authSessionConflict": "A conflicting session existed on the server and has been cleared. Please try again.", + "@authSessionConflict": {}, + + "csrfTokenMissing": "Server did not provide a CSRF token", + "@csrfTokenMissing": {}, + + "insecureConnection": "Insecure Connection", + "@insecureConnection": {}, + + "insecureConnectionDetail": "This server does not use HTTPS. Your password and session are sent without encryption.", + "@insecureConnectionDetail": {}, + + "mfaCode": "Authentication Code", + "@mfaCode": {}, + + "mfaCodeEmpty": "Code cannot be empty", + "@mfaCodeEmpty": {}, + + "mfaEnterCode": "Enter the code from your authenticator app", + "@mfaEnterCode": {}, + + "mfaEnterRecoveryCode": "Enter one of your recovery codes", + "@mfaEnterRecoveryCode": {}, + + "mfaRecoveryCode": "Recovery Code", + "@mfaRecoveryCode": {}, + + "mfaRegistrationRequired": "Multi-Factor Authentication Required", + "@mfaRegistrationRequired": {}, + + "mfaRegistrationRequiredDetail": "This server requires multi-factor authentication. Set up an authenticator using the web interface, then login again.", + "@mfaRegistrationRequiredDetail": {}, + + "mfaTitle": "Multi-Factor Authentication", + "@mfaTitle": {}, + + "mfaTrustDevice": "Trust this device", + "@mfaTrustDevice": {}, + + "mfaTrustDeviceDetail": "Skip multi-factor authentication on this device for a period of time", + "@mfaTrustDeviceDetail": {}, + + "mfaUnsupported": "None of the multi-factor authentication methods for this account are supported by the app. Login using the web interface instead.", + "@mfaUnsupported": {}, + + "mfaUseRecoveryCode": "Use a recovery code", + "@mfaUseRecoveryCode": {}, + "ok": "OK", "@ok": { "description": "OK" @@ -1535,6 +1586,15 @@ "sessionExpiredDetail": "Your session has expired. Please sign in again.", "@sessionExpiredDetail": {}, + "sessionRemoveFailed": "Logout Incomplete", + "@sessionRemoveFailed": {}, + + "sessionRemoveFailedDetail": "The stored login session could not be removed from this device. Please try to log out again.", + "@sessionRemoveFailedDetail": {}, + + "sessionSaveFailed": "Login succeeded, but the session could not be saved on this device. Please try again.", + "@sessionSaveFailed": {}, + "serverCertificateError": "Cerficate Error", "@serverCertificateError": {}, @@ -1833,15 +1893,6 @@ "toggleTorch": "Toggle Torch", "@toggleTorch": {}, - "tokenError": "Token Error", - "@tokenError": {}, - - "tokenMissing": "Missing Token", - "@tokenMissing": {}, - - "tokenMissingFromResponse": "Access token missing from response", - "@tokenMissingFromResponse": {}, - "totalPrice": "Total Price", "@totalPrice": {}, diff --git a/lib/l10n/collect_translations.py b/lib/l10n/collect_translations.py index d47bd65a..a76930fe 100644 --- a/lib/l10n/collect_translations.py +++ b/lib/l10n/collect_translations.py @@ -86,7 +86,9 @@ def generate_locale_list(locales): for importing into the project """ - with open("supported_locales.dart", "w") as output: + here = os.path.abspath(os.path.dirname(__file__)) + + with open(os.path.join(here, "supported_locales.dart"), "w") as output: output.write( "// This file is auto-generated by the 'collect_translations.py' script - do not edit it directly!\n\n" ) @@ -138,7 +140,7 @@ if __name__ == "__main__": f = os.path.join(here, locale) - if os.path.exists(f) and os.path.isdir(locale): + if os.path.exists(f) and os.path.isdir(f): copy_locale_file(f) locales.append(locale) diff --git a/lib/main.dart b/lib/main.dart index 73eba6e6..62903458 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -17,6 +17,7 @@ import "package:inventree/dsn.dart"; import "package:inventree/managed_config.dart"; import "package:inventree/preferences.dart"; +import "package:inventree/inventree/redact.dart"; import "package:inventree/inventree/sentry.dart"; import "package:inventree/l10n/supported_locales.dart"; import "package:inventree/l10n/collected/app_localizations.dart"; @@ -45,6 +46,9 @@ Future main() async { options.environment = isInDebugMode() ? "debug" : "release"; options.diagnosticLevel = SentryLevel.debug; options.attachStacktrace = true; + + // Never send credentials (cookies, tokens, passwords) with error reports + configureSentryPrivacy(options); }); } @@ -164,6 +168,12 @@ class InvenTreeAppState extends State { initGlobalIntentListener(); } + // Remove API tokens stored by earlier (token authentication) versions of the app + await UserProfileDBManager().migrateLegacyTokens(); + + // Discard stored sessions which no longer belong to a profile (e.g. after a reinstall) + await UserProfileDBManager().removeOrphanedSessions(); + // First-run only: seed a demo server profile if none are configured await UserProfileDBManager().seedDemoProfileIfNeeded(); diff --git a/lib/managed_config.dart b/lib/managed_config.dart index 03d809b8..7f9aa457 100644 --- a/lib/managed_config.dart +++ b/lib/managed_config.dart @@ -10,7 +10,6 @@ import "package:inventree/user_profile.dart"; const String MANAGED_CONFIG_SERVER_KEY = "server"; const String MANAGED_CONFIG_NAME_KEY = "name"; -const String MANAGED_CONFIG_TOKEN_KEY = "token"; const String MANAGED_CONFIG_THEME_KEY = "themeMode"; const String MANAGED_CONFIG_LANGUAGE_KEY = "language"; @@ -222,10 +221,6 @@ Future _applyManagedProfile(Map config) async { // Profile name is required if (name.isEmpty) return; - final String token = (config[MANAGED_CONFIG_TOKEN_KEY] ?? "") - .toString() - .trim(); - final String fingerprint = "${name}|${server}"; final String applied = @@ -236,24 +231,21 @@ Future _applyManagedProfile(Map config) async { UserProfile? profile = await manager.getProfileByName(name); - // Compare token against stored token - final bool tokenChanged = token.isNotEmpty && profile?.token != token; - // Check if anything actually changed - if (applied == fingerprint && !tokenChanged) return; + // Note: the user must login to the managed profile themselves - + // the app no longer supports pre-provisioned API tokens + if (applied == fingerprint) return; // No demo profile await InvenTreeSettingsManager().setValue("demo_profile_added", true); if (profile == null) { - profile = UserProfile(name: name, server: server, token: token); + profile = UserProfile(name: name, server: server); await manager.addProfile(profile); } else { profile.server = server; - if (token.isNotEmpty) profile.token = token; - await manager.updateProfile(profile); } diff --git a/lib/settings/login.dart b/lib/settings/login.dart index e94181a7..1b88d047 100644 --- a/lib/settings/login.dart +++ b/lib/settings/login.dart @@ -2,12 +2,72 @@ import "package:flutter/material.dart"; import "package:flutter_tabler_icons/flutter_tabler_icons.dart"; import "package:inventree/app_colors.dart"; +import "package:inventree/auth/auth_manager.dart"; +import "package:inventree/auth/auth_method.dart"; +import "package:inventree/auth/auth_result.dart"; +import "package:inventree/settings/login_mfa.dart"; import "package:inventree/user_profile.dart"; import "package:inventree/l10.dart"; import "package:inventree/api.dart"; import "package:inventree/widget/dialogs.dart"; import "package:inventree/widget/progress.dart"; +/* + * Act on the result of an authentication step (login, MFA, etc). + * Shared between the login and MFA screens. + * + * - Authenticated: connect to the server and return to the home screen + * - MFA required: open the MFA screen + * - Otherwise: report the error via [onError] + */ +Future handleAuthResult( + BuildContext context, + UserProfile profile, + AuthResult result, + void Function(String) onError, +) async { + switch (result.status) { + case AuthStatus.authenticated: + // Connect using the new session, then return directly to the home screen + await InvenTreeAPI().connectToServer(profile); + + hideLoadingOverlay(); + + if (context.mounted) { + Navigator.of(context).popUntil((route) => route.isFirst); + } + case AuthStatus.flowPending: + hideLoadingOverlay(); + + final AuthFlow flow = result.pendingFlow!; + + if (flow.isSupportedMfa) { + if (context.mounted) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => InvenTreeMfaWidget(profile, flow), + ), + ); + } + } else if (flow.id == FLOW_MFA_AUTHENTICATE) { + onError(L10().mfaUnsupported); + } else { + onError("${L10().authFlowUnsupported} (${flow.id})"); + } + case AuthStatus.failed: + hideLoadingOverlay(); + + String err = result.errorMessage; + + if (err.isEmpty && result.statusCode >= 0) { + err = statusCodeToString(result.statusCode); + } + + onError(err); + } +} + class InvenTreeLoginWidget extends StatefulWidget { const InvenTreeLoginWidget(this.profile) : super(); @@ -44,41 +104,27 @@ class _InvenTreeLoginState extends State { showLoadingOverlay(); - // Attempt login - suppress the generic error dialog, since this screen - // shows its own contextual inline error message below - final response = await InvenTreeAPI().fetchToken( + setState(() { + error = ""; + }); + + final AuthResult result = await InvenTreeAuth().beginLogin( widget.profile, - username, - password, - showDialog: false, + PasswordAuthMethod(username, password), ); - if (response.successful()) { - // A token was issued - immediately connect using it, then return - // directly to the home screen (rather than leaving the user on the - // server-selector screen to navigate back manually) - await InvenTreeAPI().connectToServer(widget.profile); - + if (!context.mounted) { hideLoadingOverlay(); - - if (context.mounted) { - Navigator.of(context).popUntil((route) => route.isFirst); - } - } else { - hideLoadingOverlay(); - var data = response.asMap(); - - String err; - - if (data.containsKey("detail")) { - err = (data["detail"] ?? "") as String; - } else { - err = statusCodeToString(response.statusCode); - } - setState(() { - error = err; - }); + return; } + + await handleAuthResult(context, widget.profile, result, (String err) { + if (mounted) { + setState(() { + error = err; + }); + } + }); } } @@ -95,6 +141,15 @@ class _InvenTreeLoginState extends State { subtitle: Text(widget.profile.server), leading: Icon(TablerIcons.server), ), + if (Uri.tryParse(widget.profile.server)?.scheme == "http") + ListTile( + title: Text( + L10().insecureConnection, + style: TextStyle(color: COLOR_WARNING), + ), + subtitle: Text(L10().insecureConnectionDetail), + leading: Icon(TablerIcons.lock_open, color: COLOR_WARNING), + ), Divider(), ]; @@ -111,17 +166,7 @@ class _InvenTreeLoginState extends State { ); } return Scaffold( - appBar: AppBar( - title: Text(L10().login), - actions: [ - IconButton( - icon: Icon(TablerIcons.transition_right, color: COLOR_SUCCESS), - onPressed: () async { - _doLogin(context); - }, - ), - ], - ), + appBar: AppBar(title: Text(L10().login)), body: Form( key: formKey, child: SingleChildScrollView( @@ -137,8 +182,11 @@ class _InvenTreeLoginState extends State { labelStyle: TextStyle(fontWeight: FontWeight.bold), hintText: L10().enterUsername, ), - initialValue: "", + initialValue: widget.profile.username, + autofocus: widget.profile.username.isEmpty, + autocorrect: false, keyboardType: TextInputType.text, + autofillHints: [AutofillHints.username], onSaved: (value) { username = value?.trim() ?? ""; }, @@ -167,19 +215,43 @@ class _InvenTreeLoginState extends State { ), ), initialValue: "", + autofocus: widget.profile.username.isNotEmpty, keyboardType: TextInputType.visiblePassword, + autofillHints: [AutofillHints.password], obscureText: _obscured, + textInputAction: TextInputAction.done, + onFieldSubmitted: (value) { + _doLogin(context); + }, onSaved: (value) { - password = value?.trim() ?? ""; + // Do not trim - whitespace is a valid password character + password = value ?? ""; }, validator: (value) { - if (value == null || value.trim().isEmpty) { + if (value == null || value.isEmpty) { return L10().passwordEmpty; } return null; }, ), + const SizedBox(height: 24), + SizedBox( + width: double.infinity, + child: ElevatedButton.icon( + style: ElevatedButton.styleFrom( + minimumSize: const Size.fromHeight(52), + backgroundColor: COLOR_SUCCESS, + foregroundColor: Colors.black87, + textStyle: Theme.of(context).textTheme.titleMedium, + ), + icon: Icon(TablerIcons.login), + label: Text(L10().login), + onPressed: () async { + _doLogin(context); + }, + ), + ), ...after, ], ), diff --git a/lib/settings/login_mfa.dart b/lib/settings/login_mfa.dart new file mode 100644 index 00000000..1dc1ea20 --- /dev/null +++ b/lib/settings/login_mfa.dart @@ -0,0 +1,205 @@ +import "package:flutter/material.dart"; +import "package:flutter/services.dart"; +import "package:flutter_tabler_icons/flutter_tabler_icons.dart"; + +import "package:inventree/app_colors.dart"; +import "package:inventree/auth/auth_manager.dart"; +import "package:inventree/auth/auth_result.dart"; +import "package:inventree/l10.dart"; +import "package:inventree/settings/login.dart"; +import "package:inventree/user_profile.dart"; +import "package:inventree/widget/progress.dart"; + +/* + * Second login step - enter a TOTP (or recovery) code + */ +class InvenTreeMfaWidget extends StatefulWidget { + const InvenTreeMfaWidget(this.profile, this.flow) : super(); + + final UserProfile profile; + + // The pending MFA flow (provides the available authenticator types) + final AuthFlow flow; + + @override + _InvenTreeMfaState createState() => _InvenTreeMfaState(); +} + +class _InvenTreeMfaState extends State { + final formKey = GlobalKey(); + + String code = ""; + + // Enter a recovery code, rather than a TOTP code + bool _useRecoveryCode = false; + + // Ask the server to skip MFA on this device in future + bool _trustDevice = false; + + String error = ""; + + bool get _supportsTotp => widget.flow.types.contains(MFA_TYPE_TOTP); + + @override + void initState() { + super.initState(); + + // Only recovery codes available + _useRecoveryCode = !_supportsTotp; + } + + Future _submit(BuildContext context) async { + formKey.currentState?.save(); + + bool valid = formKey.currentState?.validate() ?? false; + + if (!valid) { + return; + } + + FocusScopeNode currentFocus = FocusScope.of(context); + + if (!currentFocus.hasPrimaryFocus) { + currentFocus.unfocus(); + } + + showLoadingOverlay(); + + setState(() { + error = ""; + }); + + final AuthResult result = await InvenTreeAuth().submitMfaCode( + code, + trustDevice: _trustDevice, + ); + + if (!context.mounted) { + hideLoadingOverlay(); + return; + } + + await handleAuthResult(context, widget.profile, result, (String err) { + if (mounted) { + setState(() { + error = err; + }); + } + }); + } + + @override + Widget build(BuildContext context) { + List after = []; + + if (error.isNotEmpty) { + after.add(Divider()); + after.add( + ListTile( + leading: Icon(TablerIcons.exclamation_circle, color: COLOR_DANGER), + title: Text(L10().error, style: TextStyle(color: COLOR_DANGER)), + subtitle: Text(error, style: TextStyle(color: COLOR_DANGER)), + ), + ); + } + + return Scaffold( + appBar: AppBar( + title: Text(L10().mfaTitle), + actions: [ + IconButton( + icon: Icon(TablerIcons.transition_right, color: COLOR_SUCCESS), + onPressed: () async { + _submit(context); + }, + ), + ], + ), + body: Form( + key: formKey, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ListTile( + title: Text(L10().mfaTitle), + subtitle: Text( + _useRecoveryCode + ? L10().mfaEnterRecoveryCode + : L10().mfaEnterCode, + ), + leading: Icon(TablerIcons.shield_lock), + ), + ListTile( + title: Text(L10().server), + subtitle: Text(widget.profile.server), + leading: Icon(TablerIcons.server), + ), + Divider(), + TextFormField( + // Rebuild the field when switching code type + key: ValueKey(_useRecoveryCode), + decoration: InputDecoration( + labelText: _useRecoveryCode + ? L10().mfaRecoveryCode + : L10().mfaCode, + labelStyle: TextStyle(fontWeight: FontWeight.bold), + ), + initialValue: "", + autofocus: true, + autocorrect: false, + enableSuggestions: false, + autofillHints: _useRecoveryCode + ? null + : [AutofillHints.oneTimeCode], + keyboardType: _useRecoveryCode + ? TextInputType.visiblePassword + : TextInputType.number, + inputFormatters: _useRecoveryCode + ? null + : [FilteringTextInputFormatter.digitsOnly], + onSaved: (value) { + code = value?.trim() ?? ""; + }, + onFieldSubmitted: (value) { + _submit(context); + }, + validator: (value) { + if (value == null || value.trim().isEmpty) { + return L10().mfaCodeEmpty; + } + + return null; + }, + ), + if (_supportsTotp && widget.flow.supportsRecoveryCodes) + SwitchListTile( + title: Text(L10().mfaUseRecoveryCode), + value: _useRecoveryCode, + onChanged: (value) { + setState(() { + _useRecoveryCode = value; + }); + }, + ), + CheckboxListTile( + title: Text(L10().mfaTrustDevice), + subtitle: Text(L10().mfaTrustDeviceDetail), + value: _trustDevice, + onChanged: (value) { + setState(() { + _trustDevice = value ?? false; + }); + }, + ), + ...after, + ], + ), + padding: EdgeInsets.all(16), + ), + ), + ); + } +} diff --git a/lib/settings/select_server.dart b/lib/settings/select_server.dart index f0190c76..cbc52601 100644 --- a/lib/settings/select_server.dart +++ b/lib/settings/select_server.dart @@ -8,6 +8,7 @@ import "package:inventree/app_colors.dart"; import "package:inventree/widget/dialogs.dart"; import "package:inventree/l10.dart"; import "package:inventree/api.dart"; +import "package:inventree/auth/auth_manager.dart"; import "package:inventree/user_profile.dart"; class InvenTreeSelectServerWidget extends StatefulWidget { @@ -36,20 +37,25 @@ class _InvenTreeSelectServerState extends State { } /* - * Logout the selected profile (delete the stored token) + * Logout the selected profile (end the session, and delete the stored cookies) */ Future _logoutProfile( BuildContext context, { UserProfile? userProfile, }) async { if (userProfile != null) { - userProfile.token = ""; - await UserProfileDBManager().updateProfile(userProfile); - - _reload(); + // The stored session could not be removed - the profile may still be logged in + if (!await InvenTreeAuth().logout(userProfile)) { + showErrorDialog( + L10().sessionRemoveFailed, + description: L10().sessionRemoveFailedDetail, + icon: TablerIcons.lock_exclamation, + ); + } + } else { + InvenTreeAPI().disconnectFromServer(); } - InvenTreeAPI().disconnectFromServer(); _reload(); } @@ -114,8 +120,8 @@ class _InvenTreeSelectServerState extends State { return; } - // First check if the profile has an associate token - if (!prf.hasToken) { + // First check if the profile has a stored session + if (!prf.hasSession) { // Redirect user to the login screen - it connects on success itself await Navigator.push( context, @@ -130,7 +136,7 @@ class _InvenTreeSelectServerState extends State { return; } - // Attempt server connection using the existing token + // Attempt server connection using the existing session await InvenTreeAPI().connectToServer(prf); _reload(); @@ -259,7 +265,7 @@ class _InvenTreeSelectServerState extends State { ? Theme.of(context).secondaryHeaderColor : null, subtitle: Text("${profile.server}"), - leading: profile.hasToken + leading: profile.hasSession ? Icon(TablerIcons.user_check, color: COLOR_SUCCESS) : Icon(TablerIcons.user_cancel, color: COLOR_WARNING), trailing: Row( diff --git a/lib/user_profile.dart b/lib/user_profile.dart index 8e81131d..9fdc3df1 100644 --- a/lib/user_profile.dart +++ b/lib/user_profile.dart @@ -1,6 +1,7 @@ import "package:flutter_secure_storage/flutter_secure_storage.dart"; import "package:sembast/sembast.dart"; +import "package:inventree/auth/session_store.dart"; import "package:inventree/helpers.dart"; import "package:inventree/preferences.dart"; @@ -9,7 +10,7 @@ class UserProfile { this.key, this.name = "", this.server = "", - this.token = "", + this.username = "", this.selected = false, this.trustedCertificate = false, }); @@ -22,16 +23,11 @@ class UserProfile { key: key, name: (json["name"] ?? "") as String, server: (json["server"] ?? "") as String, - // Legacy field - profiles saved before the token moved to secure storage - // may still have it here. UserProfileDBManager migrates this on read. - token: (json["token"] ?? "") as String, + username: (json["username"] ?? "") as String, selected: isSelected, trustedCertificate: (json["trustedCertificate"] ?? false) as bool, ); - // Return true if this profile has a token - bool get hasToken => token.isNotEmpty; - // ID of the profile int? key; @@ -41,9 +37,13 @@ class UserProfile { // Base address of the InvenTree server String server = ""; - // API token - held in memory only; persisted separately in secure storage - // (see UserProfileDBManager), never written to the plain profile record - String token = ""; + // Username (or email) used for the last successful login - pre-fills the login form. + // Kept on logout. The password is never stored + String username = ""; + + // Does this profile have a stored session (populated from secure storage + // by UserProfileDBManager). The session itself is never held on the profile + bool hasSession = false; bool selected = false; @@ -57,6 +57,7 @@ class UserProfile { Map toJson() => { "name": name, "server": server, + "username": username, "trustedCertificate": trustedCertificate, }; @@ -72,56 +73,247 @@ class UserProfile { class UserProfileDBManager { final store = StoreRef("profiles"); - static const _secureStorage = FlutterSecureStorage(); + // Session cookies are only accessible on this device (not synced or restored to another device): + // - iOS: keychain item, "this device only" and not synchronizable + // - Android: AES-GCM, with the key wrapped by a non-exportable KeyStore key. + // The storage files are excluded from backup (see res/xml/*_rules.xml) + static const _secureStorage = FlutterSecureStorage( + iOptions: IOSOptions( + accessibility: KeychainAccessibility.first_unlock_this_device, + ), + ); Future get _db async => InvenTreePreferencesDB.instance.database; - // Key used to store a profile's API token in secure storage - String _tokenStorageKey(int key) => "profile_token_${key}"; + // Key used to store a profile's session cookies in secure storage + String _sessionStorageKey(int key) => "profile_session_${key}"; + + // Key used to store a profile's API token (legacy - removed by migrateLegacyTokens) + String _legacyTokenStorageKey(int key) => "profile_token_${key}"; /* - * Persist (or clear) a profile's token in secure storage, keyed by its - * database record id. The token never lives in the plain Sembast record. + * Load the stored session cookies for the provided profile */ - Future _saveToken(int key, String token) async { - if (token.isEmpty) { - await _secureStorage.delete(key: _tokenStorageKey(key)); - } else { - await _secureStorage.write(key: _tokenStorageKey(key), value: token); - } - } - - /* - * Populate a profile's in-memory token from secure storage. - * If secure storage has nothing for this profile, but the (legacy) - * Sembast record still has a plaintext token from before this migration, - * adopt it once and move it into secure storage. - */ - Future _loadToken(UserProfile profile) async { + Future loadSession(UserProfile profile) async { final int? key = profile.key; if (key == null) { - return profile; + return SessionStore(server: profile.server); } - final String? secureToken = await _secureStorage.read( - key: _tokenStorageKey(key), - ); + String? data; - if (secureToken != null) { - profile.token = secureToken; - } else if (profile.token.isNotEmpty) { - // Legacy profile - migrate its plaintext token into secure storage, - // and strip it from the Sembast record now. Must use put() (full - // replace) rather than update() (merge), otherwise the stale legacy - // "token" field survives and gets re-migrated on every future read. - await _saveToken(key, profile.token); - await store.record(key).put(await _db, profile.toJson()); + try { + data = await _secureStorage.read(key: _sessionStorageKey(key)); + } catch (error) { + debug("loadSession() : Error reading secure storage - ${error}"); } + final SessionStore session = SessionStore.fromJson(profile.server, data); + + // Stored cookies belong to a different server address - remove them + if (session.rejected) { + debug( + "loadSession() : Stored session discarded - server address changed", + ); + await clearSession(profile); + } + + return session; + } + + /* + * Persist the session cookies for the provided profile. + * The cookies are only ever stored in secure storage, never in the profile record. + */ + Future saveSession(UserProfile profile, SessionStore session) async { + final int? key = profile.key; + + // Profile is not stored - so there is nowhere to store the session + if (key == null) { + return false; + } + + // Cookies being written - taken before the (asynchronous) write, + // in case the jar changes in the meantime + final snapshot = session.snapshot(); + + try { + if (session.isEmpty) { + await _secureStorage.delete(key: _sessionStorageKey(key)); + } else { + await _secureStorage.write( + key: _sessionStorageKey(key), + value: session.toJson(), + ); + } + } catch (error) { + debug("saveSession() : Error writing secure storage - ${error}"); + return false; + } + + session.markPersisted(snapshot); + + return true; + } + + /* + * Remove all stored session cookies for the provided profile. + * Returns false if the stored cookies could not be removed. + */ + Future clearSession(UserProfile profile) async { + final int? key = profile.key; + + if (key == null) { + return true; + } + + try { + await _secureStorage.delete(key: _sessionStorageKey(key)); + } catch (error) { + debug("clearSession() : Error writing secure storage - ${error}"); + return false; + } + + return true; + } + + /* + * Remove the session (and CSRF) cookies from storage for the provided profile. + * Other cookies (e.g. MFA "trusted device") are retained where possible. + * + * Returns false if a stored session may remain - the caller must not report + * the session as removed (e.g. on logout). + */ + Future removeStoredSession( + UserProfile profile, + SessionStore session, + ) async { + session.clearAuthCookies(); + + if (await saveSession(profile, session)) { + return true; + } + + // Could not update the stored cookies - remove them all instead + return clearSession(profile); + } + + // Populate the "hasSession" flag for the provided profile + Future _loadSessionState(UserProfile profile) async { + profile.hasSession = (await loadSession(profile)).hasSession; return profile; } + /* + * One-time removal of API tokens stored by earlier versions of the app, + * which used token authentication (now replaced by session authentication). + * Tokens are removed from secure storage, and any (older) plaintext + * token is stripped from the profile record. + */ + Future migrateLegacyTokens() async { + const String MIGRATION_KEY = "legacy_tokens_removed"; + + if (await InvenTreeSettingsManager().getBool(MIGRATION_KEY, false)) { + return; + } + + final db = await _db; + final records = await store.find(db); + + // Only mark the migration as complete if every token was removed + bool complete = true; + + for (final record in records) { + if (record.key is! int) { + continue; + } + + final int key = record.key! as int; + + try { + await _secureStorage.delete(key: _legacyTokenStorageKey(key)); + } catch (error) { + debug( + "migrateLegacyTokens() : Error writing secure storage - ${error}", + ); + + // Continue with the remaining profiles - but retry on next startup + complete = false; + } + + final value = record.value; + + if (value is Map && value.containsKey("token")) { + // put() (full replace) rather than update() (merge), so the field is removed + await store + .record(key) + .put(db, UserProfile.fromJson(key, value, false).toJson()); + } + } + + if (!complete) { + debug("migrateLegacyTokens() : Incomplete - will retry on next startup"); + return; + } + + await InvenTreeSettingsManager().setValue(MIGRATION_KEY, true); + } + + /* + * Remove any secure storage entries which do not belong to an existing profile. + * + * Secure storage can outlive the profile database - e.g. iOS keychain items + * survive an app uninstall. Profile keys restart after a reinstall, so a new + * profile could otherwise inherit the session of an old (unrelated) profile. + * Legacy API tokens are also removed (for any profile). + * Must be called before any profiles are created on startup. + */ + Future removeOrphanedSessions() async { + final db = await _db; + final Set profileKeys = (await store.findKeys( + db, + )).whereType().toSet(); + + // Session (and legacy token) entries - see _sessionStorageKey() + final RegExp keyPattern = RegExp(r"^profile_(session|token)_(\d+)$"); + + List names = []; + + try { + names = (await _secureStorage.readAll()).keys.toList(); + } catch (error) { + debug( + "removeOrphanedSessions() : Error accessing secure storage - ${error}", + ); + } + + for (final String name in names) { + final match = keyPattern.firstMatch(name); + + if (match == null) { + continue; + } + + // Legacy API tokens are never used, so are always removed (even if + // migrateLegacyTokens() could not remove them for an existing profile) + final bool legacyToken = match.group(1) == "token"; + + if (!legacyToken && profileKeys.contains(int.tryParse(match.group(2)!))) { + continue; + } + + // Each entry is removed separately, so one failure does not prevent the rest + try { + await _secureStorage.delete(key: name); + } catch (error) { + debug( + "removeOrphanedSessions() : Error writing secure storage - ${error}", + ); + } + } + } + /* * Check if a profile with the specified name exists in the database */ @@ -164,10 +356,6 @@ class UserProfileDBManager { // Record the key profile.key = key; - if (key != null) { - await _saveToken(key, profile.token); - } - return true; } @@ -187,11 +375,9 @@ class UserProfileDBManager { return result; } - // put() (full replace) rather than update() (merge) - a legacy record's - // stale "token" field must not survive a write, or it will be - // re-migrated into secure storage on the next read (see _loadToken) + // put() (full replace) rather than update() (merge), so that any stale + // fields (e.g. a legacy "token") do not survive a write await store.record(profile.key).put(await _db, profile.toJson()); - await _saveToken(profile.key!, profile.token); return true; } @@ -204,9 +390,7 @@ class UserProfileDBManager { await store.record(profile.key).delete(await _db); - if (profile.key != null) { - await _secureStorage.delete(key: _tokenStorageKey(profile.key!)); - } + await clearSession(profile); } /* @@ -230,7 +414,7 @@ class UserProfileDBManager { profiles[idx].key == selected, ); - return _loadToken(profile); + return _loadSessionState(profile); } } @@ -255,7 +439,7 @@ class UserProfileDBManager { profiles[idx].key == selected, ); - profileList.add(await _loadToken(profile)); + profileList.add(await _loadSessionState(profile)); } } diff --git a/lib/widget/dialogs.dart b/lib/widget/dialogs.dart index 0c084095..6449dbc7 100644 --- a/lib/widget/dialogs.dart +++ b/lib/widget/dialogs.dart @@ -244,6 +244,12 @@ Future showErrorDialog( Color? color, Function? onDismissed, }) async { + // Server response rejected because the user must login again - see showServerError + if (response != null && InvenTreeAPI().suppressServerErrors) { + debug("showErrorDialog: suppressed '${title}'"); + return; + } + if (!hasContext()) { return; } @@ -290,6 +296,15 @@ Future showServerError( String title, String description, ) async { + // The user has been directed to login (e.g. session expired) - errors caused + // by the expired session are not displayed + if (InvenTreeAPI().suppressServerErrors) { + debug("showServerError: suppressed '${title}'"); + return; + } + + debug("showServerError: '${title}'"); + if (!hasContext()) { return; } diff --git a/lib/widget/notes_list_widget.dart b/lib/widget/notes_list_widget.dart index a630647d..49962a1a 100644 --- a/lib/widget/notes_list_widget.dart +++ b/lib/widget/notes_list_widget.dart @@ -110,7 +110,7 @@ class _NoteWidgetFactory extends WidgetFactory { return CachedNetworkImageProvider( url, - headers: InvenTreeAPI().defaultHeaders(), + headers: InvenTreeAPI().defaultHeaders(url: url), cacheManager: InvenTreeAPI().imageCacheManager, ); } diff --git a/pubspec.lock b/pubspec.lock index 7e5df9f2..c6f7a157 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -197,10 +197,10 @@ packages: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" checked_yaml: dependency: transitive description: @@ -274,13 +274,13 @@ packages: source: hosted version: "0.3.4+2" crypto: - dependency: transitive + dependency: "direct dev" description: name: crypto - sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" + sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4 url: "https://pub.dev" source: hosted - version: "3.0.6" + version: "3.0.8" csslib: dependency: transitive description: @@ -797,14 +797,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.14.2" - js: - dependency: transitive - description: - name: js - sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" - url: "https://pub.dev" - source: hosted - version: "0.7.2" json_annotation: dependency: transitive description: @@ -889,18 +881,18 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.19" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "0.13.0" meta: dependency: transitive description: @@ -1374,26 +1366,26 @@ packages: dependency: "direct dev" description: name: test - sha256: "75906bf273541b676716d1ca7627a17e4c4070a3a16272b7a3dc7da3b9f3f6b7" + sha256: "280d6d890011ca966ad08df7e8a4ddfab0fb3aa49f96ed6de56e3521347a9ae7" url: "https://pub.dev" source: hosted - version: "1.26.3" + version: "1.30.0" test_api: dependency: transitive description: name: test_api - sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" url: "https://pub.dev" source: hosted - version: "0.7.7" + version: "0.7.10" test_core: dependency: transitive description: name: test_core - sha256: "0cc24b5ff94b38d2ae73e1eb43cc302b77964fbf67abad1e296025b78deb53d0" + sha256: "0381bd1585d1a924763c308100f2138205252fb90c9d4eeaf28489ee65ccde51" url: "https://pub.dev" source: hosted - version: "0.6.12" + version: "0.6.16" typed_data: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 42832025..1633680c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: inventree description: InvenTree stock management -version: 0.26.0+127 +version: 1.0.0+128 environment: sdk: ^3.8.1 @@ -49,6 +49,7 @@ dependencies: wakelock_plus: ^1.3.2 # Prevent device from sleeping dev_dependencies: + crypto: ^3.0.8 flutter_launcher_icons: ^0.14.1 flutter_test: sdk: flutter diff --git a/test/api_test.dart b/test/api_test.dart index 515bad80..6847dab0 100644 --- a/test/api_test.dart +++ b/test/api_test.dart @@ -2,9 +2,14 @@ * Unit tests for the InvenTree API code */ +import "dart:io"; + import "package:flutter_test/flutter_test.dart"; import "package:inventree/api.dart"; +import "package:inventree/auth/auth_manager.dart"; +import "package:inventree/auth/auth_method.dart"; +import "package:inventree/auth/session_store.dart"; import "package:inventree/helpers.dart"; import "package:inventree/user_profile.dart"; @@ -54,7 +59,7 @@ void main() { // Check expected values expect(api.isConnected(), equals(false)); expect(api.isConnecting(), equals(false)); - expect(api.hasToken, equals(false)); + expect(api.hasSession, equals(false)); }); test("Login Failure", () async { @@ -74,44 +79,56 @@ void main() { // Test incorrect login details profile.server = testServerAddress; - final response = await api.fetchToken(profile, "baduser", "badpassword"); - assert(!response.successful()); - - debugContains("Token request failed"); + final authResult = await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod("baduser", "badpassword"), + ); + assert(!authResult.authenticated); + assert(authResult.errors.isNotEmpty); assert(!api.checkConnection()); - debugContains("Token request failed: STATUS 401"); + debugContains("InvenTreeAuth: AuthResult(failed, status=400"); debugContains("showSnackIcon: 'Not Connected'"); }); - test("Bad Token", () async { - // Test that login fails with a bad token + test("Bad Session", () async { + // Test that connection fails with an invalid session cookie var profile = await setupServerProfile(); - profile.token = "bad-token"; + final session = SessionStore(server: profile.server); + + session.capture(Uri.parse(profile.server), [ + Cookie(SESSION_COOKIE_NAME, "bad-session"), + ]); + + await UserProfileDBManager().saveSession(profile, session); bool result = await InvenTreeAPI().connectToServer(profile); assert(!result); + + // The invalid session should have been discarded + final stored = await UserProfileDBManager().loadSession(profile); + assert(!stored.hasSession); }); test("Login Success", () async { // Test that we can login to the server successfully var api = InvenTreeAPI(); - final profile = await setupServerProfile(select: true, fetchToken: true); - assert(profile.hasToken); + final profile = await setupServerProfile(select: true, login: true); + assert(profile.hasSession); // Now, connect to the server bool result = await api.connectToServer(profile); // Check expected values assert(result); - assert(api.hasToken); + assert(api.hasSession); expect(api.baseUrl, equals(testServerAddress)); - assert(api.hasToken); + assert(api.hasSession); assert(api.isConnected()); assert(!api.isConnecting()); assert(api.checkConnection()); @@ -121,7 +138,7 @@ void main() { // Test server version information var api = InvenTreeAPI(); - final profile = await setupServerProfile(fetchToken: true); + final profile = await setupServerProfile(login: true); assert(await api.connectToServer(profile)); // Check supported functions @@ -141,7 +158,6 @@ void main() { // Pricing role (or legacy server with no pricing role) assert(api.canViewPricing); - debugContains("Received token from server"); debugContains("showSnackIcon: 'Connected to Server'"); }); }); diff --git a/test/auth_flow_test.dart b/test/auth_flow_test.dart new file mode 100644 index 00000000..2c5fe355 --- /dev/null +++ b/test/auth_flow_test.dart @@ -0,0 +1,1469 @@ +/* + * Authentication flow tests against an in-process fake server (see fake_server.dart). + * + * These cover error paths and edge cases which are difficult (or impossible) + * to reproduce against a real InvenTree server. No running server is required. + */ + +import "dart:async"; +import "dart:io"; + +import "package:flutter_secure_storage/flutter_secure_storage.dart"; +import "package:flutter_test/flutter_test.dart"; + +import "package:inventree/api.dart"; +import "package:inventree/auth/auth_manager.dart"; +import "package:inventree/auth/auth_method.dart"; +import "package:inventree/auth/auth_result.dart"; +import "package:inventree/auth/session_store.dart"; +import "package:inventree/helpers.dart"; +import "package:inventree/inventree/part.dart"; +import "package:inventree/inventree/stock.dart"; +import "package:inventree/l10.dart"; +import "package:inventree/managed_config.dart"; +import "package:inventree/user_profile.dart"; +import "package:inventree/widget/dialogs.dart"; + +import "fake_server.dart"; +import "setup.dart"; + +const String profileName = "Auth Flow Test"; + +late FakeInvenTreeServer server; + +// Profiles created by the current test (removed in tearDown) +final List _profiles = []; + +InvenTreeAPI get api => InvenTreeAPI(); + +UserProfileDBManager get manager => UserProfileDBManager(); + +/* + * Create a new profile pointing at the provided fake server + */ +Future fakeProfile( + FakeInvenTreeServer fake, { + String name = profileName, +}) async { + final UserProfile? existing = await manager.getProfileByName(name); + + if (existing != null) { + await manager.deleteProfile(existing); + } + + expect( + await manager.addProfile(UserProfile(name: name, server: fake.url)), + equals(true), + ); + + _profiles.add(name); + + return (await manager.getProfileByName(name))!; +} + +Future login( + UserProfile profile, { + String username = "user", + String password = "password", +}) => + InvenTreeAuth().beginLogin(profile, PasswordAuthMethod(username, password)); + +/* + * Login and connect, then wait for background requests (status codes) to finish + */ +Future loginAndConnect(UserProfile profile) async { + expect((await login(profile)).authenticated, equals(true)); + expect(await api.connectToServer(profile), equals(true)); + + await Future.delayed(Duration(milliseconds: 200)); +} + +Future stored(UserProfile profile) => + manager.loadSession(profile); + +// Wait for an asynchronous condition (e.g. a session being persisted) +Future eventually(Future Function() check) async { + for (int i = 0; i < 50; i++) { + if (await check()) return; + await Future.delayed(Duration(milliseconds: 20)); + } + + fail("Condition not met"); +} + +bool logged(String msg) => debugContains(msg, raiseAssert: false); + +/* + * Run [body], returning everything printed (including by asynchronous + * work started within it, e.g. error reports) + */ +Future> capturePrints(Future Function() body) async { + final List printed = []; + + await runZoned( + () async { + await body(); + + // Allow error reports (not awaited by the API) to complete + await Future.delayed(Duration(milliseconds: 200)); + }, + zoneSpecification: ZoneSpecification( + print: (self, parent, zone, line) { + printed.add(line); + parent.print(zone, line); + }, + ), + ); + + return printed; +} + +FakeResponse unauthorized(FakeRequest _) => FakeResponse( + 401, + body: {"detail": "Authentication credentials were not provided."}, +); + +void main() { + setupTestEnv(); + + setUp(() async { + clearDebugMessage(); + server = await FakeInvenTreeServer.start(); + }); + + tearDown(() async { + secureStorageFailures.clear(); + + api.disconnectFromServer(); + + for (final name in _profiles) { + final profile = await manager.getProfileByName(name); + + if (profile != null) { + await manager.deleteProfile(profile); + } + } + + _profiles.clear(); + + await server.close(); + }); + + group("Login:", () { + test("Password login", () async { + final profile = await fakeProfile(server); + + final AuthResult result = await login(profile); + expect(result.authenticated, equals(true)); + + // CSRF token was requested before the login POST + final List sequence = server.requests + .map((r) => r.toString()) + .toList(); + expect( + sequence.indexOf("GET /api/auth/v1/auth/session"), + lessThan(sequence.indexOf("POST /api/auth/v1/auth/login")), + ); + + expect((await stored(profile)).hasSession, equals(true)); + expect(profile.username, equals("user")); + }); + + test("Email-only login sends the email field", () async { + server.loginMethods = ["email"]; + server.users["user@example.com"] = "password"; + + final profile = await fakeProfile(server); + + final AuthResult result = await login( + profile, + username: "user@example.com", + ); + expect(result.authenticated, equals(true)); + + final Map body = server + .received("POST", "api/auth/v1/auth/login") + .single + .json; + expect(body["email"], equals("user@example.com")); + expect(body.containsKey("username"), equals(false)); + }); + + test("MFA code", () async { + final profile = await fakeProfile(server); + + AuthResult result = await login(profile, username: "mfa"); + expect(result.status, equals(AuthStatus.flowPending)); + expect(result.pendingFlow!.id, equals(FLOW_MFA_AUTHENTICATE)); + expect((await stored(profile)).hasSession, equals(false)); + + result = await InvenTreeAuth().submitMfaCode("000000"); + expect(result.status, equals(AuthStatus.failed)); + expect(result.errorMessage, equals("Incorrect code.")); + + result = await InvenTreeAuth().submitMfaCode(server.validCode); + expect(result.authenticated, equals(true)); + expect((await stored(profile)).hasSession, equals(true)); + }); + + test("Session conflict (409)", () async { + final profile = await fakeProfile(server); + + server.once( + "POST", + "api/auth/v1/auth/login", + (_) => FakeResponse(409, body: {"status": 409}), + ); + + final AuthResult result = await login(profile); + + expect(result.status, equals(AuthStatus.failed)); + expect(result.statusCode, equals(409)); + expect(result.errorMessage, equals(L10().authSessionConflict)); + + // Auth cookies are discarded, so the next attempt starts afresh + expect(api.session.hasSession, equals(false)); + expect(api.session.hasCsrfToken, equals(false)); + + expect((await login(profile)).authenticated, equals(true)); + }); + + test("Server does not provide a CSRF token", () async { + final profile = await fakeProfile(server); + + server.always( + "GET", + "api/auth/v1/auth/session", + (_) => FakeResponse(401, body: {"status": 401}), + ); + + final AuthResult result = await login(profile); + + expect(result.status, equals(AuthStatus.failed)); + expect(result.errorMessage, equals(L10().csrfTokenMissing)); + + // Credentials are never sent without CSRF protection + expect(server.received("POST", "api/auth/v1/auth/login"), isEmpty); + }); + + test("Too many failed login attempts", () async { + final profile = await fakeProfile(server); + + // Failed-login rate limit - reported by allauth as a form error + server.once( + "POST", + "api/auth/v1/auth/login", + (_) => FakeResponse( + 400, + body: { + "status": 400, + "errors": [ + { + "message": "Too many failed login attempts. Try again later.", + "code": "too_many_login_attempts", + }, + ], + }, + ), + ); + + AuthResult result = await login(profile); + expect(result.statusCode, equals(400)); + expect( + result.errorMessage, + equals("Too many failed login attempts. Try again later."), + ); + + // Generic rate limit - no error message, so the UI falls back to the status code + server.once( + "POST", + "api/auth/v1/auth/login", + (_) => FakeResponse(429, body: {"status": 429}), + ); + + result = await login(profile); + expect(result.status, equals(AuthStatus.failed)); + expect(result.statusCode, equals(429)); + expect(result.errorMessage, isEmpty); + expect(statusCodeToString(429), equals(L10().response429)); + }); + + test("Server API version too old", () async { + final FakeInvenTreeServer old = await FakeInvenTreeServer.start( + apiVersion: 300, + ); + + try { + final profile = await fakeProfile(old); + + final AuthResult result = await login(profile); + + expect(result.status, equals(AuthStatus.failed)); + expect(logged("showServerError: '${L10().serverOld}'"), equals(true)); + + // No authentication is attempted + expect(old.received("GET", "api/auth/v1/config"), isEmpty); + expect(old.received("POST", "api/auth/v1/auth/login"), isEmpty); + } finally { + await old.close(); + } + }); + }); + + group("Connect:", () { + test("Expired session shows message and login screen", () async { + final profile = await fakeProfile(server); + + // A session the server does not know about + final session = SessionStore(server: server.url); + session.captureHeaders(Uri.parse(server.url), [ + "sessionid=stale; Path=/", + ]); + await manager.saveSession(profile, session); + + expect(await api.connectToServer(profile), equals(false)); + + expect((await stored(profile)).hasSession, equals(false)); + expect( + logged("showServerError: '${L10().sessionExpired}'"), + equals(true), + ); + expect(logged("Opening login screen for '${profileName}'"), equals(true)); + }); + + test("MFA registration required", () async { + final profile = await fakeProfile(server); + + expect((await login(profile)).authenticated, equals(true)); + + // Server enforces MFA, which this user has not configured + server.always( + "GET", + "api/user/me/", + (_) => FakeResponse( + 401, + body: { + "id": "mfa_register", + "error": "You must enable two-factor authentication", + }, + ), + ); + + expect(await api.connectToServer(profile), equals(false)); + + // The restricted server session is ended, and discarded locally + expect(server.received("DELETE", "api/auth/v1/auth/session").length, 1); + expect(server.sessions, isEmpty); + expect((await stored(profile)).hasSession, equals(false)); + + expect( + logged("showServerError: '${L10().mfaRegistrationRequired}'"), + equals(true), + ); + + // Login would not help - so the login screen is not opened + expect(logged("Opening login screen"), equals(false)); + }); + + final Map failures = { + "Service unavailable (503)": FakeResponse(503), + "Connection dropped": FakeResponse.drop(), + }; + + for (final failure in failures.entries) { + test("${failure.key} keeps the session", () async { + final profile = await fakeProfile(server); + + expect((await login(profile)).authenticated, equals(true)); + + server.once("GET", "api/user/me/", (_) => failure.value); + + expect(await api.connectToServer(profile), equals(false)); + + // Session retained - and still valid once the server recovers + expect(profile.hasSession, equals(true)); + expect((await stored(profile)).hasSession, equals(true)); + expect(logged("Opening login screen"), equals(false)); + + expect(await api.connectToServer(profile), equals(true)); + }); + } + }); + + group("While connected:", () { + late UserProfile profile; + + setUp(() async { + profile = await fakeProfile(server); + await loginAndConnect(profile); + clearDebugMessage(); + }); + + int userChecks() => server.received("GET", "api/user/me/").length; + + test("Session expiry opens the login screen", () async { + server.endAllSessions(); + + final response = await api.get("part/", expectedStatusCode: null); + expect(response.statusCode, equals(401)); + + expect(api.isConnected(), equals(false)); + expect((await stored(profile)).hasSession, equals(false)); + expect(profile.username, equals("user")); + + expect( + logged("showServerError: '${L10().sessionExpired}'"), + equals(true), + ); + expect(logged("Opening login screen for '${profileName}'"), equals(true)); + }); + + int loginPrompts() => + debug_messages.where((m) => m.contains("Opening login screen")).length; + + // Errors displayed to the user, other than the "session expired" message + List displayedErrors() => debug_messages + .where( + (m) => + m.startsWith("showServerError: '") && + !m.contains(L10().sessionExpired), + ) + .toList(); + + test("Model requests redirect to login without errors", () async { + server.endAllSessions(); + + // As made by list views (paginator) and detail views + await Future.wait([ + InvenTreePart().listPaginated(10, 0), + InvenTreePart().get(1), + InvenTreeStockItem().listPaginated(10, 0), + ]); + + expect(api.isConnected(), equals(false)); + expect(displayedErrors(), isEmpty); + expect(loginPrompts(), equals(1)); + + // Errors were suppressed (not just missing) + expect(logged("showServerError: suppressed"), equals(true)); + }); + + test("Requests after expiry redirect to login without errors", () async { + server.endAllSessions(); + + await InvenTreePart().listPaginated(10, 0); + expect(api.isConnected(), equals(false)); + expect(loginPrompts(), equals(1)); + + // Screens which are still open continue to make requests + await InvenTreePart().get(1); + await api.post("part/", body: {"name": "A"}); + + final File file = File( + "${Directory.systemTemp.path}/inventree-auth-upload.txt", + )..writeAsStringSync("test"); + + try { + await api.uploadFile("part/attachment/", file); + } finally { + file.deleteSync(); + } + + expect(displayedErrors(), isEmpty); + + // The login screen is already open - it is not opened again + expect(loginPrompts(), equals(1)); + }); + + test("Login screen dismissed - next request opens it again", () async { + server.endAllSessions(); + + await InvenTreePart().listPaginated(10, 0); + expect(loginPrompts(), equals(1)); + + // User leaves the login screen without logging in + api.onLoginScreenClosed(); + expect(api.suppressServerErrors, equals(false)); + + // ... and continues to use a screen which is still open + await InvenTreePart().listPaginated(10, 0); + + expect(loginPrompts(), equals(2)); + expect(displayedErrors(), isEmpty); + }); + + test("Rejected requests are marked as handled", () async { + server.endAllSessions(); + + final response = await api.get("part/"); + + expect(response.statusCode, equals(401)); + expect(response.errorDetail, isNotEmpty); + }); + + test("Download with an expired session", () async { + server.endAllSessions(); + + await api.downloadFile( + "${server.url}media/inventree-auth-expired.txt", + openOnDownload: false, + ); + + expect(api.isConnected(), equals(false)); + expect(displayedErrors(), isEmpty); + expect(loginPrompts(), equals(1)); + }); + + test("Errors are displayed again after login", () async { + server.endAllSessions(); + await api.get("part/"); + expect(api.isConnected(), equals(false)); + + await loginAndConnect(profile); + clearDebugMessage(); + + // An unrelated error is displayed as normal + server.once( + "GET", + "api/part/", + (_) => FakeResponse(400, body: {"detail": "Bad request"}), + ); + await InvenTreePart().listPaginated(10, 0); + + expect(displayedErrors(), isNotEmpty); + expect(loginPrompts(), equals(0)); + }); + + /* + * Start a request which is rejected (triggering a session check), and hold + * the session check response until [release] completes. A second request + * is then rejected while the check is still running (overlapping). + * + * Returns the overlapping request's response. + */ + Future<(APIResponse, APIResponse)> overlapping({ + required Completer release, + required FutureOr Function() checkResponse, + }) async { + final int checks = userChecks(); + + server.once("GET", "api/part/", unauthorized); + server.once("PATCH", "api/part/1/", unauthorized); + + server.once("GET", "api/user/me/", (_) async { + await release.future; + return checkResponse(); + }); + + // First request - starts the session check + final Future first = api.get("part/"); + await eventually(() async => userChecks() == checks + 1); + + // Second request - rejected while the check is running. + // (PATCH reports an unexpected status code itself, unlike GET) + final Future second = api.patch( + "part/1/", + body: {"name": "A"}, + expectedStatusCode: 200, + ); + await eventually( + () async => server.received("PATCH", "api/part/1/").isNotEmpty, + ); + + // Allow the second response to be processed, then complete the check + await Future.delayed(Duration(milliseconds: 50)); + release.complete(); + + return (await first, await second); + } + + test("Overlapping 401 - session valid", () async { + final (_, second) = await overlapping( + release: Completer(), + checkResponse: () => + FakeResponse(200, body: {"pk": 1, "username": "user"}), + ); + + // The session is valid, so the overlapping request is a real error + expect(second.statusCode, equals(401)); + expect(second.errorDetail, isEmpty); + expect(api.isConnected(), equals(true)); + expect(api.suppressServerErrors, equals(false)); + + // ... and is reported as such + expect(logged("showServerError: '${L10().response401}'"), equals(true)); + expect(logged("showServerError: suppressed"), equals(false)); + expect(loginPrompts(), equals(0)); + }); + + test("Overlapping 401 - session check fails (transient)", () async { + final (_, second) = await overlapping( + release: Completer(), + checkResponse: () => FakeResponse(503), + ); + + // Unable to determine the session state - the session is retained, + // and the overlapping request's error is not hidden + expect(second.errorDetail, isEmpty); + expect(api.isConnected(), equals(true)); + expect((await stored(profile)).hasSession, equals(true)); + expect(logged("showServerError: '${L10().response401}'"), equals(true)); + expect(loginPrompts(), equals(0)); + }); + + test("Overlapping 401 - session expired", () async { + server.endAllSessions(); + + final (first, second) = await overlapping( + release: Completer(), + checkResponse: () => unauthorized( + FakeRequest( + method: "GET", + path: "/api/user/me/", + query: {}, + rawQuery: "", + headers: {}, + cookies: {}, + body: "", + ), + ), + ); + + // Both requests are handled by directing the user to login + expect(first.errorDetail, isNotEmpty); + expect(second.errorDetail, isNotEmpty); + expect(api.isConnected(), equals(false)); + expect(displayedErrors(), isEmpty); + expect(loginPrompts(), equals(1)); + }); + + test("Other errors are displayed while the session is checked", () async { + final Completer release = Completer(); + final int checks = userChecks(); + + server.once("GET", "api/part/", unauthorized); + server.once("GET", "api/user/me/", (_) async { + await release.future; + return FakeResponse(200, body: {"pk": 1, "username": "user"}); + }); + + final Future first = api.get("part/"); + await eventually(() async => userChecks() == checks + 1); + + // An unrelated error, while the session check is running + server.once( + "GET", + "api/stock/", + (_) => FakeResponse(400, body: {"detail": "Bad request"}), + ); + await InvenTreeStockItem().listPaginated(10, 0); + + expect(api.suppressServerErrors, equals(false)); + expect(logged("showServerError: '${L10().response400}'"), equals(true)); + + release.complete(); + await first; + }); + + // 401 responses without a JSON body (e.g. from a proxy) + final Map nonJson = { + "HTML": "

401 Unauthorized

", + "Empty": "", + }; + + bool formatError() => logged("showServerError: '${L10().formatException}'"); + + Future upload() async { + final File file = File( + "${Directory.systemTemp.path}/inventree-auth-upload.txt", + )..writeAsStringSync("test"); + + try { + return await api.uploadFile("part/attachment/", file); + } finally { + file.deleteSync(); + } + } + + for (final body in nonJson.entries) { + test("Upload - ${body.key} 401 with an expired session", () async { + server.endAllSessions(); + server.once( + "POST", + "api/part/attachment/", + (_) => FakeResponse(401, rawBody: body.value), + ); + + final response = await upload(); + + expect(response.statusCode, equals(401)); + expect(response.errorDetail, isNotEmpty); + expect(api.isConnected(), equals(false)); + expect(loginPrompts(), equals(1)); + expect(formatError(), equals(false)); + }); + + test("Request - ${body.key} 401 with an expired session", () async { + server.endAllSessions(); + server.once( + "GET", + "api/part/", + (_) => FakeResponse(401, rawBody: body.value), + ); + + final response = await api.get("part/"); + + expect(response.statusCode, equals(401)); + expect(response.errorDetail, isNotEmpty); + expect(api.isConnected(), equals(false)); + expect(loginPrompts(), equals(1)); + expect(formatError(), equals(false)); + }); + } + + test("Upload - HTML 401 with a valid session", () async { + server.once( + "POST", + "api/part/attachment/", + (_) => FakeResponse(401, rawBody: nonJson["HTML"]), + ); + + final response = await upload(); + + // Session checked and found valid - reported as a 401 (not a format error) + expect(response.statusCode, equals(401)); + expect(response.errorDetail, isEmpty); + expect(api.isConnected(), equals(true)); + expect(loginPrompts(), equals(0)); + expect(formatError(), equals(false)); + }); + + test("Upload - other non-JSON responses are still reported", () async { + server.once( + "POST", + "api/part/attachment/", + (_) => FakeResponse(400, rawBody: nonJson["HTML"]), + ); + + await upload(); + + expect(formatError(), equals(true)); + expect(api.isConnected(), equals(true)); + }); + + test("Failed session check keeps the user identity", () async { + expect(api.userId, equals(1)); + expect(api.username, equals("user")); + + for (final failure in [FakeResponse(503), FakeResponse.drop()]) { + server.once("GET", "api/part/", unauthorized); + server.once("GET", "api/user/me/", (_) => failure); + + await api.get("part/"); + + // Session retained - so the identity must be too + // (e.g. used as "checked_by" when checking a shipment) + expect(api.isConnected(), equals(true)); + expect(api.userId, equals(1)); + expect(api.username, equals("user")); + } + }); + + test("Successful session check refreshes the user identity", () async { + server.once("GET", "api/part/", unauthorized); + server.once( + "GET", + "api/user/me/", + (_) => FakeResponse(200, body: {"pk": 1, "username": "renamed"}), + ); + + await api.get("part/"); + + expect(api.isConnected(), equals(true)); + expect(api.username, equals("renamed")); + }); + + test("Expired session clears the user identity", () async { + server.endAllSessions(); + + await api.get("part/"); + + expect(api.isConnected(), equals(false)); + expect(api.userId, equals(-1)); + expect(api.username, isEmpty); + }); + + test("Disconnect clears the user identity", () async { + expect(api.userId, equals(1)); + + api.disconnectFromServer(); + + expect(api.userId, equals(-1)); + expect(api.username, isEmpty); + }); + + test("Concurrent requests check the session once", () async { + final int before = userChecks(); + + server.endAllSessions(); + + await Future.wait([ + api.get("part/", expectedStatusCode: null), + api.get("stock/", expectedStatusCode: null), + api.get("company/", expectedStatusCode: null), + ]); + + expect(userChecks(), equals(before + 1)); + expect(api.isConnected(), equals(false)); + }); + + test("Rejected request with a valid session keeps the session", () async { + final int before = userChecks(); + + server.once("GET", "api/part/", unauthorized); + + final response = await api.get("part/", expectedStatusCode: null); + expect(response.statusCode, equals(401)); + + // Session was checked and found to be valid - so the response is not + // treated as handled, and is reported by the caller as normal + expect(userChecks(), equals(before + 1)); + expect(api.isConnected(), equals(true)); + expect((await stored(profile)).hasSession, equals(true)); + expect(response.errorDetail, isEmpty); + expect(api.suppressServerErrors, equals(false)); + expect(logged("Opening login screen"), equals(false)); + }); + + test("401 from an auth endpoint does not check the session", () async { + final int before = userChecks(); + + server.once( + "GET", + "api/auth/v1/auth/session", + (_) => FakeResponse(401, body: {"status": 401}), + ); + + await api.get("auth/v1/auth/session", expectedStatusCode: null); + + expect(userChecks(), equals(before)); + expect(api.isConnected(), equals(true)); + }); + + test("403 does not expire the session", () async { + final int before = userChecks(); + + for (final detail in [ + "You do not have permission to perform this action.", + "CSRF Failed: CSRF token missing.", + ]) { + server.once( + "GET", + "api/part/", + (_) => FakeResponse(403, body: {"detail": detail}), + ); + + await api.get("part/", expectedStatusCode: null); + } + + expect(userChecks(), equals(before)); + expect(api.isConnected(), equals(true)); + expect((await stored(profile)).hasSession, equals(true)); + }); + + test("MFA registration required while connected", () async { + server.once("GET", "api/part/", unauthorized); + server.once( + "GET", + "api/user/me/", + (_) => FakeResponse(401, body: {"id": "mfa_register"}), + ); + + await api.get("part/", expectedStatusCode: null); + + expect(api.isConnected(), equals(false)); + expect(server.received("DELETE", "api/auth/v1/auth/session").length, 1); + expect( + logged("showServerError: '${L10().mfaRegistrationRequired}'"), + equals(true), + ); + }); + + test("Upload with an expired session", () async { + final File file = File( + "${Directory.systemTemp.path}/inventree-auth-upload.txt", + )..writeAsStringSync("test"); + + try { + server.endAllSessions(); + + final response = await api.uploadFile("part/attachment/", file); + expect(response.statusCode, equals(401)); + + expect(api.isConnected(), equals(false)); + expect((await stored(profile)).hasSession, equals(false)); + } finally { + file.deleteSync(); + } + }); + }); + + group("Requests:", () { + late UserProfile profile; + + setUp(() async { + profile = await fakeProfile(server); + await loginAndConnect(profile); + }); + + test("Query parameters are URL encoded", () async { + final Map params = { + "search": "M3 & M4 C++ #1?", + "name": "a=b", + "unicode": "Ø 10µF", + }; + + await api.get("part/", params: params); + + final FakeRequest request = server.received("GET", "api/part/").last; + expect(request.query, equals(params)); + }); + + test("Query parameters are merged with an existing query", () async { + await api.get("part/?category=1", params: {"search": "x y"}); + + final FakeRequest request = server.received("GET", "api/part/").last; + expect(request.query, equals({"category": "1", "search": "x y"})); + }); + + test("No query string without parameters", () async { + await api.get("part/"); + + expect(server.received("GET", "api/part/").last.rawQuery, isEmpty); + }); + + test("Server error response is read and reported", () async { + server.once( + "GET", + "api/part/1/", + (_) => FakeResponse(500, body: {"detail": "Database unavailable"}), + ); + + late APIResponse response; + + final List printed = await capturePrints(() async { + response = await api.get("part/1/"); + }); + + expect(response.statusCode, equals(500)); + expect(response.asMap()["detail"], equals("Database unavailable")); + + // The error is displayed, including the server's description + expect(logged("showServerError: '${L10().response500}'"), equals(true)); + + // ... and reported, including the response data + final String report = printed.firstWhere( + (line) => + line.startsWith("Sending user message to Sentry: Server error"), + ); + expect(report, contains("Database unavailable")); + }); + + test("Server error page (not JSON) is reported once", () async { + const String page = "

Internal Server Error

"; + + server.once( + "GET", + "api/part/1/", + (_) => FakeResponse(500, rawBody: page), + ); + + final File file = File( + "${Directory.systemTemp.path}/inventree-auth-upload.txt", + )..writeAsStringSync("test"); + + server.once( + "POST", + "api/part/attachment/", + (_) => FakeResponse(500, rawBody: page), + ); + + late APIResponse response; + + final List printed = await capturePrints(() async { + response = await api.get("part/1/"); + await api.uploadFile("part/attachment/", file); + }); + + file.deleteSync(); + + expect(response.statusCode, equals(500)); + expect(response.asMap(), isEmpty); + + final List reports = printed + .where((line) => line.startsWith("Sending user message to Sentry")) + .toList(); + + expect(reports.length, equals(2)); + expect(reports[0], contains("Server error")); + expect(reports[0], contains("Internal Server Error")); + expect(reports[1], contains("Server error in uploadFile()")); + expect(reports[1], contains("Internal Server Error")); + }); + + test("CSRF headers on unsafe requests", () async { + expect((await api.post("part/", body: {"name": "A"})).statusCode, 201); + expect( + (await api.patch("part/1/", body: {"name": "B"})).statusCode, + equals(200), + ); + expect((await api.delete("part/1/")).statusCode, equals(200)); + + final String origin = Uri.parse(server.url).origin; + + for (final method in ["POST", "PATCH", "DELETE"]) { + final FakeRequest request = server.requests.lastWhere( + (r) => r.method == method && r.path.startsWith("/api/part/"), + ); + + expect(request.cookies["sessionid"], isNotEmpty); + expect(request.headers["x-csrftoken"], equals(api.session.csrfToken)); + expect(request.headers["origin"], equals(origin)); + expect(request.headers["referer"], startsWith(server.url)); + expect(request.headers.containsKey("authorization"), equals(false)); + } + + // Safe requests do not include CSRF headers + await api.get("part/"); + + final FakeRequest get = server.received("GET", "api/part/").last; + expect(get.cookies["sessionid"], isNotEmpty); + expect(get.headers.containsKey("x-csrftoken"), equals(false)); + }); + + test("Upload sends credentials and captures cookies", () async { + final File file = File( + "${Directory.systemTemp.path}/inventree-auth-upload.txt", + )..writeAsStringSync("test"); + + // Multiple cookies - folded into a single header by package:http + server.once( + "POST", + "api/part/attachment/", + (_) => FakeResponse( + 201, + body: {"pk": 1}, + setCookies: [ + "csrftoken=rotated-upload; Path=/", + "extra=1; Expires=Wed, 21 Oct 2037 07:28:00 GMT; Path=/", + ], + ), + ); + + try { + final response = await api.uploadFile("part/attachment/", file); + expect(response.statusCode, equals(201)); + } finally { + file.deleteSync(); + } + + final FakeRequest request = server + .received("POST", "api/part/attachment/") + .single; + expect(request.cookies["sessionid"], isNotEmpty); + expect( + request.headers["x-csrftoken"], + equals(request.cookies["csrftoken"]), + ); + + expect(api.session.csrfToken, equals("rotated-upload")); + expect(api.session.cookieNames, contains("extra")); + }); + + test("Cookies rotated by the server are persisted", () async { + server.once( + "GET", + "api/part/", + (_) => FakeResponse( + 200, + body: [], + setCookies: ["csrftoken=rotated; Path=/"], + ), + ); + + await api.get("part/"); + + await eventually( + () async => (await stored(profile)).csrfToken == "rotated", + ); + }); + + test("Downloads only send credentials to the server", () async { + final FakeInvenTreeServer foreign = await FakeInvenTreeServer.start(); + + // getTemporaryDirectory() is mocked to the working directory + final List files = [ + "inventree-auth-own.txt", + "inventree-auth-foreign.txt", + ]; + + try { + await api.downloadFile( + "${server.url}media/${files[0]}", + openOnDownload: false, + ); + await api.downloadFile( + "${foreign.url}media/${files[1]}", + openOnDownload: false, + ); + + final FakeRequest own = server + .received("GET", "media/${files[0]}") + .single; + expect(own.cookies["sessionid"], isNotEmpty); + + final FakeRequest other = foreign + .received("GET", "media/${files[1]}") + .single; + expect(other.cookies, isEmpty); + expect(other.headers.containsKey("x-csrftoken"), equals(false)); + expect(other.headers.containsKey("authorization"), equals(false)); + } finally { + await foreign.close(); + + for (final name in files) { + final file = File(name); + if (file.existsSync()) file.deleteSync(); + } + } + }); + }); + + group("Profiles:", () { + test("Switching profiles keeps sessions separate", () async { + final FakeInvenTreeServer other = await FakeInvenTreeServer.start(); + + try { + final a = await fakeProfile(server, name: "${profileName} A"); + final b = await fakeProfile(other, name: "${profileName} B"); + + await loginAndConnect(a); + final String sessionA = server.sessions.keys.single; + + await loginAndConnect(b); + final String sessionB = other.sessions.keys.single; + + expect(sessionA, isNot(equals(sessionB))); + + // Each profile retains its own session + expect( + (await stored(a)).cookieHeader(Uri.parse(server.url)), + contains(sessionA), + ); + expect( + (await stored(b)).cookieHeader(Uri.parse(other.url)), + contains(sessionB), + ); + + // Switch back to A, without logging in again + final int before = server.requests.length; + expect(await api.connectToServer(a), equals(true)); + await Future.delayed(Duration(milliseconds: 200)); + + for (final request in server.requests.skip(before)) { + expect(request.cookies["sessionid"], equals(sessionA)); + } + + // B's session never reached server A (and vice versa) + expect( + server.requests.where((r) => r.cookies["sessionid"] == sessionB), + isEmpty, + ); + expect( + other.requests.where((r) => r.cookies["sessionid"] == sessionA), + isEmpty, + ); + } finally { + await other.close(); + } + }); + + test("Editing the server address discards the session", () async { + // Another service on the same host, at a different port + final FakeInvenTreeServer other = await FakeInvenTreeServer.start(); + + try { + final profile = await fakeProfile(server); + await loginAndConnect(profile); + api.disconnectFromServer(); + + final String key = "profile_session_${profile.key}"; + + profile.server = other.url; + await manager.updateProfile(profile); + + final UserProfile edited = (await manager.getProfileByName( + profileName, + ))!; + expect(edited.hasSession, equals(false)); + + // Stored cookies have been removed + expect(await const FlutterSecureStorage().read(key: key), isNull); + + // ... and are never sent to the new address + expect(await api.connectToServer(edited), equals(false)); + + for (final request in other.requests) { + expect(request.cookies, isEmpty, reason: request.toString()); + expect(request.headers.containsKey("cookie"), equals(false)); + } + } finally { + await other.close(); + } + }); + + test( + "Managed configuration changing the server discards the session", + () async { + final FakeInvenTreeServer other = await FakeInvenTreeServer.start(); + + const String name = "${profileName} Managed Move"; + _profiles.add(name); + + try { + await applyManagedConfiguration({"server": server.url, "name": name}); + + UserProfile profile = (await manager.getProfileByName(name))!; + expect((await login(profile)).authenticated, equals(true)); + expect((await stored(profile)).hasSession, equals(true)); + + // Administrator moves the managed profile to a different address + await applyManagedConfiguration({"server": other.url, "name": name}); + + profile = (await manager.getProfileByName(name))!; + expect(profile.server, equals(other.url)); + expect(profile.hasSession, equals(false)); + + await api.beginAuthentication(profile); + await api.connectToServer(profile); + + for (final request in other.requests) { + expect(request.cookies, isEmpty, reason: request.toString()); + } + } finally { + await other.close(); + } + }, + ); + + test("Deleting a profile removes its secure storage", () async { + final profile = await fakeProfile(server); + expect((await login(profile)).authenticated, equals(true)); + + final String key = "profile_session_${profile.key}"; + expect(await const FlutterSecureStorage().read(key: key), isNotNull); + + await manager.deleteProfile(profile); + + expect(await const FlutterSecureStorage().read(key: key), isNull); + }); + + test("Logout of an inactive profile", () async { + final profile = await fakeProfile(server); + expect((await login(profile)).authenticated, equals(true)); + + // Add a "trusted device" cookie + final session = await stored(profile); + session.captureHeaders(Uri.parse(server.url), [ + "mfa_trusted=trusted; Path=/", + ]); + await manager.saveSession(profile, session); + + api.disconnectFromServer(); + + await InvenTreeAuth().logout(profile); + + // Local only - the server is not contacted for an inactive profile + expect(server.received("DELETE", "api/auth/v1/auth/session"), isEmpty); + + final SessionStore after = await stored(profile); + expect(after.hasSession, equals(false)); + expect(after.hasCsrfToken, equals(false)); + expect(after.cookieNames, contains("mfa_trusted")); + expect(profile.hasSession, equals(false)); + + expect((await manager.getProfileByName(profileName))!.username, "user"); + }); + + test("Logout with the server unreachable", () async { + final profile = await fakeProfile(server); + await loginAndConnect(profile); + + await server.close(); + + await InvenTreeAuth().logout(profile); + + expect(api.isConnected(), equals(false)); + expect(profile.hasSession, equals(false)); + expect((await stored(profile)).hasSession, equals(false)); + }); + + test("Managed configuration profile", () async { + const String name = "${profileName} Managed"; + _profiles.add(name); + + await applyManagedConfiguration({ + "server": server.url, + "name": name, + // Pre-provisioned tokens are no longer supported, and must be ignored + "token": "managed-token", + }); + + final UserProfile? profile = await manager.getProfileByName(name); + expect(profile, isNotNull); + expect(profile!.server, equals(server.url)); + expect(profile.hasSession, equals(false)); + expect(profile.toJson().containsKey("token"), equals(false)); + + final Map secure = await const FlutterSecureStorage() + .readAll(); + expect(secure.values, isNot(contains("managed-token"))); + + // The user must login themselves + expect(await api.connectToServer(profile), equals(false)); + expect((await login(profile)).authenticated, equals(true)); + }); + }); + + group("Storage failures:", () { + test("Login fails if the session cannot be saved", () async { + final profile = await fakeProfile(server); + + secureStorageFailures.addAll(["write", "delete"]); + + final AuthResult result = await login(profile); + + expect(result.status, equals(AuthStatus.failed)); + expect(result.errorMessage, equals(L10().sessionSaveFailed)); + expect(profile.hasSession, equals(false)); + + // The new session is ended on the server, and discarded in memory + expect(server.received("DELETE", "api/auth/v1/auth/session").length, 1); + expect(server.sessions, isEmpty); + expect(api.session.hasSession, equals(false)); + + // The username is only remembered for a successful login + expect((await manager.getProfileByName(profileName))!.username, isEmpty); + + // Once storage is available again, login succeeds + secureStorageFailures.clear(); + expect((await login(profile)).authenticated, equals(true)); + expect((await stored(profile)).hasSession, equals(true)); + }); + + test("MFA login fails if the session cannot be saved", () async { + final profile = await fakeProfile(server); + + expect( + (await login(profile, username: "mfa")).status, + equals(AuthStatus.flowPending), + ); + + secureStorageFailures.addAll(["write", "delete"]); + + final AuthResult result = await InvenTreeAuth().submitMfaCode( + server.validCode, + ); + + expect(result.status, equals(AuthStatus.failed)); + expect(result.errorMessage, equals(L10().sessionSaveFailed)); + expect(profile.hasSession, equals(false)); + expect(server.sessions, isEmpty); + }); + + test("Successful logout reports success", () async { + final profile = await fakeProfile(server); + await loginAndConnect(profile); + + expect(await InvenTreeAuth().logout(profile), equals(true)); + expect(profile.hasSession, equals(false)); + }); + + test("Inactive profile logout reports failure", () async { + final profile = await fakeProfile(server); + expect((await login(profile)).authenticated, equals(true)); + api.disconnectFromServer(); + + secureStorageFailures.addAll(["write", "delete"]); + + expect(await InvenTreeAuth().logout(profile), equals(false)); + + // The (still valid) session remains stored - so is not reported as removed + expect(profile.hasSession, equals(true)); + + secureStorageFailures.clear(); + expect((await stored(profile)).hasSession, equals(true)); + + // Retry succeeds + expect(await InvenTreeAuth().logout(profile), equals(true)); + expect(profile.hasSession, equals(false)); + expect((await stored(profile)).hasSession, equals(false)); + }); + + test("Offline logout reports failure", () async { + final profile = await fakeProfile(server); + await loginAndConnect(profile); + + await server.close(); + secureStorageFailures.addAll(["write", "delete"]); + + expect(await InvenTreeAuth().logout(profile), equals(false)); + expect(profile.hasSession, equals(true)); + expect(api.isConnected(), equals(false)); + + secureStorageFailures.clear(); + expect((await stored(profile)).hasSession, equals(true)); + }); + + test("Logout falls back to deleting all stored cookies", () async { + final profile = await fakeProfile(server); + expect((await login(profile)).authenticated, equals(true)); + + // Add a "trusted device" cookie, so the jar is not empty after logout + final session = await stored(profile); + session.captureHeaders(Uri.parse(server.url), [ + "mfa_trusted=trusted; Path=/", + ]); + expect(await manager.saveSession(profile, session), equals(true)); + + api.disconnectFromServer(); + + // Cookies cannot be re-written, but can be deleted + secureStorageFailures.add("write"); + + expect(await InvenTreeAuth().logout(profile), equals(true)); + expect(profile.hasSession, equals(false)); + + secureStorageFailures.clear(); + expect((await stored(profile)).isEmpty, equals(true)); + }); + + test("Session expiry with storage failure", () async { + final profile = await fakeProfile(server); + await loginAndConnect(profile); + + server.endAllSessions(); + secureStorageFailures.addAll(["write", "delete"]); + + await api.get("part/"); + + // The user is still directed to login - the stored copy is no longer valid + expect(api.isConnected(), equals(false)); + expect(logged("Opening login screen"), equals(true)); + expect( + logged("Expired session could not be removed from storage"), + equals(true), + ); + }); + }); +} diff --git a/test/auth_server_test.dart b/test/auth_server_test.dart new file mode 100644 index 00000000..fecbd43b --- /dev/null +++ b/test/auth_server_test.dart @@ -0,0 +1,558 @@ +/* + * Login flow tests against a running InvenTree server. + * + * Requires a server (with the demo dataset) at INVENTREE_TEST_SERVER, + * and an MFA (TOTP) enabled account. Credentials can be overridden with + * environment variables - see the constants below. + * + * Note: the server rate-limits failed logins (5 per minute per account), + * so avoid re-running this file in quick succession. + */ + +import "dart:io"; +import "dart:typed_data"; + +import "package:crypto/crypto.dart"; +import "package:flutter_test/flutter_test.dart"; + +import "package:inventree/api.dart"; +import "package:inventree/auth/allauth_client.dart"; +import "package:inventree/auth/auth_manager.dart"; +import "package:inventree/auth/auth_method.dart"; +import "package:inventree/auth/auth_result.dart"; +import "package:inventree/auth/session_store.dart"; +import "package:inventree/user_profile.dart"; + +import "setup.dart"; + +String _env(String name, String fallback) => + Platform.environment[name] ?? fallback; + +final String authServer = _env( + "INVENTREE_TEST_SERVER", + "http://127.0.0.1:8000/", +); + +final String basicUsername = _env("INVENTREE_TEST_USERNAME", "allaccess"); +final String basicPassword = _env("INVENTREE_TEST_PASSWORD", "nolimits"); + +final String mfaUsername = _env("INVENTREE_TEST_MFA_USERNAME", "mfauser"); +final String mfaPassword = _env( + "INVENTREE_TEST_MFA_PASSWORD", + "mfauserpassword", +); +final String mfaSecret = _env( + "INVENTREE_TEST_MFA_SECRET", + "TFFPZIB4VAOKMNMYWIYVMPGBE24RZIHF", +); + +const String basicProfileName = "Auth Test - Basic"; +const String mfaProfileName = "Auth Test - MFA"; + +/* + * TOTP (RFC 6238) code generation - SHA1, 6 digits, 30 second period + */ +const int _totpPeriod = 30; + +Uint8List _base32Decode(String input) { + const String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + + final List bytes = []; + int buffer = 0; + int bits = 0; + + for (final String c in input.toUpperCase().replaceAll("=", "").split("")) { + final int value = alphabet.indexOf(c); + + if (value < 0) { + throw FormatException("Invalid base32 character: ${c}"); + } + + buffer = (buffer << 5) | value; + bits += 5; + + if (bits >= 8) { + bits -= 8; + bytes.add((buffer >> bits) & 0xff); + } + } + + return Uint8List.fromList(bytes); +} + +int _totpWindow([DateTime? time]) => + (time ?? DateTime.now()).millisecondsSinceEpoch ~/ 1000 ~/ _totpPeriod; + +String totpCode(String secret, int window) { + final counter = ByteData(8)..setInt64(0, window); + + final List hash = Hmac( + sha1, + _base32Decode(secret), + ).convert(counter.buffer.asUint8List()).bytes; + + final int offset = hash.last & 0x0f; + + final int value = + ((hash[offset] & 0x7f) << 24) | + (hash[offset + 1] << 16) | + (hash[offset + 2] << 8) | + hash[offset + 3]; + + return (value % 1000000).toString().padLeft(6, "0"); +} + +// Most recent TOTP window used in this test run +int _lastWindow = -1; + +/* + * Return a TOTP code which has not been used yet in this run. + * The server rejects re-use of a code, so wait for the next window if required + * (or if the current window is about to expire) + */ +Future freshTotpCode() async { + while (true) { + final DateTime now = DateTime.now(); + final int window = _totpWindow(now); + final int remaining = + _totpPeriod - (now.millisecondsSinceEpoch ~/ 1000) % _totpPeriod; + + if (window > _lastWindow && remaining > 3) { + _lastWindow = window; + return totpCode(mfaSecret, window); + } + + await Future.delayed(Duration(seconds: remaining, milliseconds: 200)); + } +} + +/* + * Submit a valid TOTP code for the pending MFA flow. + * A code may have been used by a previous test run (within the same window), + * in which case it is rejected - so retry once with the next code. + */ +Future submitValidMfaCode({bool trustDevice = false}) async { + AuthResult result = await InvenTreeAuth().submitMfaCode( + await freshTotpCode(), + trustDevice: trustDevice, + ); + + if (result.status == AuthStatus.failed && result.statusCode == 400) { + result = await InvenTreeAuth().submitMfaCode( + await freshTotpCode(), + trustDevice: trustDevice, + ); + } + + return result; +} + +/* + * Create (or reset) a profile pointing at the test server + */ +Future authProfile(String name) async { + final manager = UserProfileDBManager(); + + UserProfile? profile = await manager.getProfileByName(name); + + if (profile != null) { + await manager.deleteProfile(profile); + } + + expect( + await manager.addProfile(UserProfile(name: name, server: authServer)), + equals(true), + ); + + profile = await manager.getProfileByName(name); + expect(profile, isNotNull); + + return profile!; +} + +/* + * Request the current user with only the provided session cookie + * (independent of the app's API client) and return the status code + */ +Future userStatusWithSession(String sessionId) async { + final client = HttpClient(); + + try { + final request = await client.getUrl( + Uri.parse(authServer).resolve("api/user/me/"), + ); + request.headers.set(HttpHeaders.acceptHeader, "application/json"); + request.headers.set( + HttpHeaders.cookieHeader, + "${SESSION_COOKIE_NAME}=${sessionId}", + ); + + final response = await request.close(); + await response.drain(); + + return response.statusCode; + } finally { + client.close(force: true); + } +} + +/* + * End the provided session on the server, independent of the app's API client + * (e.g. as if the session was ended from another device, or the web interface) + */ +Future endSessionExternally(SessionStore session) async { + final Uri server = Uri.parse(authServer); + final Uri url = server.resolve("api/auth/v1/auth/session"); + final client = HttpClient(); + + try { + final request = await client.deleteUrl(url); + request.headers.set(HttpHeaders.acceptHeader, "application/json"); + request.headers.set(HttpHeaders.cookieHeader, session.cookieHeader(url)); + request.headers.set("X-CSRFToken", session.csrfToken); + request.headers.set("Origin", server.origin); + request.headers.set(HttpHeaders.refererHeader, authServer); + + final response = await request.close(); + await response.drain(); + + // allauth responds with 401 once the session has ended + expect(response.statusCode, equals(401)); + } finally { + client.close(force: true); + } +} + +String storedSessionId(SessionStore session) { + final RegExp pattern = RegExp("${SESSION_COOKIE_NAME}=([^;]+)"); + + return pattern + .firstMatch(session.cookieHeader(Uri.parse(authServer))) + ?.group(1) ?? + ""; +} + +void main() { + setupTestEnv(); + + test("TOTP code generation (RFC 6238 test vector)", () { + // RFC 6238 Appendix B - SHA1, T = 59s, secret "12345678901234567890" + const String rfcSecret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"; + + expect(totpCode(rfcSecret, 59 ~/ 30), equals("287082")); + expect(totpCode(rfcSecret, 1111111109 ~/ 30), equals("081804")); + }); + + tearDownAll(() async { + InvenTreeAPI().disconnectFromServer(); + + for (final name in [basicProfileName, mfaProfileName]) { + final profile = await UserProfileDBManager().getProfileByName(name); + + if (profile != null) { + await UserProfileDBManager().deleteProfile(profile); + } + } + }); + + group("Server config:", () { + test("Auth configuration", () async { + final UserProfile profile = await authProfile(basicProfileName); + + await InvenTreeAPI().beginAuthentication(profile); + + expect(await InvenTreeAPI().checkServer(), equals(true)); + + final AuthConfig config = await const AllauthClient().getConfig(); + + expect(config.loginField, equals("username")); + expect(config.mfaTypes, contains(MFA_TYPE_TOTP)); + }); + }); + + group("Basic auth:", () { + late UserProfile profile; + + setUpAll(() async { + profile = await authProfile(basicProfileName); + }); + + test("Invalid password", () async { + final AuthResult result = await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod(basicUsername, "${basicPassword}-wrong"), + ); + + expect(result.status, equals(AuthStatus.failed)); + expect(result.statusCode, equals(400)); + expect(result.errorMessage, isNotEmpty); + + expect(profile.hasSession, equals(false)); + expect( + (await UserProfileDBManager().loadSession(profile)).hasSession, + equals(false), + ); + + // A failed login does not remember the username + expect(profile.username, isEmpty); + }); + + test("Login", () async { + final AuthResult result = await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod(basicUsername, basicPassword), + ); + + expect(result.status, equals(AuthStatus.authenticated)); + expect(profile.hasSession, equals(true)); + + // Session and CSRF cookies are persisted to secure storage + final SessionStore stored = await UserProfileDBManager().loadSession( + profile, + ); + expect(stored.hasSession, equals(true)); + expect(stored.hasCsrfToken, equals(true)); + + // Username is remembered against the profile + final UserProfile? saved = await UserProfileDBManager().getProfileByName( + basicProfileName, + ); + expect(saved!.username, equals(basicUsername)); + }); + + test("Connect with stored session", () async { + final api = InvenTreeAPI(); + + // Start from a clean API state - the session is loaded from storage + api.disconnectFromServer(); + + expect(await api.connectToServer(profile), equals(true)); + expect(api.isConnected(), equals(true)); + expect(api.username, equals(basicUsername)); + + // No API token is ever used + final headers = api.defaultHeaders(method: "POST"); + expect( + headers.containsKey(HttpHeaders.authorizationHeader), + equals(false), + ); + expect(headers["X-CSRFToken"], isNotEmpty); + }); + + test("Logout", () async { + final api = InvenTreeAPI(); + + expect(await api.connectToServer(profile), equals(true)); + + final String sessionId = storedSessionId(api.session); + expect(sessionId, isNotEmpty); + expect(await userStatusWithSession(sessionId), equals(200)); + + // Copy of the full cookie jar (session + CSRF) from before logout + final String sessionCopy = api.session.toJson(); + + await InvenTreeAuth().logout(profile); + + expect(api.isConnected(), equals(false)); + expect(profile.hasSession, equals(false)); + expect( + (await UserProfileDBManager().loadSession(profile)).hasSession, + equals(false), + ); + + // The session has been ended on the server + expect(await userStatusWithSession(sessionId), isIn([401, 403])); + + // Restoring the old session must not log the user back in + await UserProfileDBManager().saveSession( + profile, + SessionStore.fromJson(authServer, sessionCopy), + ); + expect( + (await UserProfileDBManager().loadSession(profile)).hasSession, + equals(true), + ); + + expect(await api.connectToServer(profile), equals(false)); + expect(api.isConnected(), equals(false)); + + // ... and the rejected session is discarded + expect( + (await UserProfileDBManager().loadSession(profile)).hasSession, + equals(false), + ); + + // Username is retained after logout + final UserProfile? saved = await UserProfileDBManager().getProfileByName( + basicProfileName, + ); + expect(saved!.username, equals(basicUsername)); + }); + + test("Invalid stored session", () async { + // A session cookie which the server does not recognise + final session = SessionStore(server: authServer); + session.captureHeaders(Uri.parse(authServer).resolve("api/"), [ + "${SESSION_COOKIE_NAME}=not-a-valid-session; Path=/", + ]); + await UserProfileDBManager().saveSession(profile, session); + + expect(await InvenTreeAPI().connectToServer(profile), equals(false)); + + // The invalid session is discarded + expect( + (await UserProfileDBManager().loadSession(profile)).hasSession, + equals(false), + ); + }); + + test("Session expires while connected", () async { + final api = InvenTreeAPI(); + + final AuthResult result = await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod(basicUsername, basicPassword), + ); + expect(result.status, equals(AuthStatus.authenticated)); + + expect(await api.connectToServer(profile), equals(true)); + + // Requests succeed while the session is valid + expect((await api.get("part/", params: {"limit": "1"})).statusCode, 200); + + // The session is ended elsewhere + await endSessionExternally(api.session); + + // The next request detects the expired session + final response = await api.get("part/", params: {"limit": "1"}); + expect(response.statusCode, equals(401)); + + expect(api.isConnected(), equals(false)); + expect(profile.hasSession, equals(false)); + expect( + (await UserProfileDBManager().loadSession(profile)).hasSession, + equals(false), + ); + + // Username is retained, ready to login again + final UserProfile? saved = await UserProfileDBManager().getProfileByName( + basicProfileName, + ); + expect(saved!.username, equals(basicUsername)); + + // ... and logging in again restores the connection + expect( + (await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod(basicUsername, basicPassword), + )).authenticated, + equals(true), + ); + expect(await api.connectToServer(profile), equals(true)); + + await InvenTreeAuth().logout(profile); + }); + }); + + group("MFA:", () { + late UserProfile profile; + + setUpAll(() async { + profile = await authProfile(mfaProfileName); + }); + + test("Password login requires MFA", () async { + final AuthResult result = await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod(mfaUsername, mfaPassword), + ); + + expect(result.status, equals(AuthStatus.flowPending)); + expect(result.pendingFlow!.id, equals(FLOW_MFA_AUTHENTICATE)); + expect(result.pendingFlow!.isSupportedMfa, equals(true)); + expect(result.pendingFlow!.types, contains(MFA_TYPE_TOTP)); + + // Nothing is persisted until the login is complete + expect(profile.hasSession, equals(false)); + expect( + (await UserProfileDBManager().loadSession(profile)).hasSession, + equals(false), + ); + }); + + test("Invalid code, then valid code", () async { + AuthResult result = await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod(mfaUsername, mfaPassword), + ); + expect(result.status, equals(AuthStatus.flowPending)); + + // A code which is (almost certainly) not valid for the current window + final String current = totpCode(mfaSecret, _totpWindow()); + final String invalid = ((int.parse(current) + 1) % 1000000) + .toString() + .padLeft(6, "0"); + + result = await InvenTreeAuth().submitMfaCode(invalid); + + expect(result.status, equals(AuthStatus.failed)); + expect(result.statusCode, equals(400)); + expect(result.errorMessage, isNotEmpty); + expect(profile.hasSession, equals(false)); + + // The pending login can be completed with a valid code + result = await submitValidMfaCode(); + + expect(result.status, equals(AuthStatus.authenticated)); + expect(profile.hasSession, equals(true)); + + expect(await InvenTreeAPI().connectToServer(profile), equals(true)); + expect(InvenTreeAPI().username, equals(mfaUsername)); + + await InvenTreeAuth().logout(profile); + expect(profile.hasSession, equals(false)); + }, timeout: Timeout(Duration(minutes: 2))); + + test("Trusted device skips MFA", () async { + AuthResult result = await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod(mfaUsername, mfaPassword), + ); + expect(result.status, equals(AuthStatus.flowPending)); + + result = await submitValidMfaCode(trustDevice: true); + expect(result.status, equals(AuthStatus.authenticated)); + + SessionStore stored = await UserProfileDBManager().loadSession(profile); + expect(stored.cookieNames, contains("mfa_trusted")); + + expect(await InvenTreeAPI().connectToServer(profile), equals(true)); + await InvenTreeAuth().logout(profile); + + // The trusted device cookie survives logout + stored = await UserProfileDBManager().loadSession(profile); + expect(stored.hasSession, equals(false)); + expect(stored.cookieNames, contains("mfa_trusted")); + + // ... so the next login does not require MFA + result = await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod(mfaUsername, mfaPassword), + ); + expect(result.status, equals(AuthStatus.authenticated)); + + expect(await InvenTreeAPI().connectToServer(profile), equals(true)); + await InvenTreeAuth().logout(profile); + + // Without the trusted device cookie, MFA is required again + await UserProfileDBManager().clearSession(profile); + + result = await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod(mfaUsername, mfaPassword), + ); + expect(result.status, equals(AuthStatus.flowPending)); + expect(result.pendingFlow!.id, equals(FLOW_MFA_AUTHENTICATE)); + }, timeout: Timeout(Duration(minutes: 2))); + }); +} diff --git a/test/auth_test.dart b/test/auth_test.dart new file mode 100644 index 00000000..f93792ff --- /dev/null +++ b/test/auth_test.dart @@ -0,0 +1,844 @@ +/* + * Unit tests for session authentication (no server required) + */ + +import "dart:io"; + +import "package:flutter_secure_storage/flutter_secure_storage.dart"; +import "package:flutter_test/flutter_test.dart"; +import "package:sembast/sembast.dart"; + +import "package:inventree/api.dart"; +import "package:inventree/auth/auth_manager.dart"; +import "package:inventree/auth/auth_result.dart"; +import "package:inventree/auth/session_store.dart"; +import "package:inventree/inventree/redact.dart"; +import "package:inventree/preferences.dart"; +import "package:inventree/user_profile.dart"; + +import "setup.dart"; + +const String server = "https://inventree.example.com"; + +Cookie _cookie( + String name, + String value, { + String? domain, + String? path, + int? maxAge, + DateTime? expires, + bool secure = false, +}) { + final cookie = Cookie(name, value); + cookie.domain = domain; + cookie.path = path; + cookie.maxAge = maxAge; + cookie.expires = expires; + cookie.secure = secure; + return cookie; +} + +void main() { + setupTestEnv(); + + final Uri serverUri = Uri.parse("${server}/api/part/"); + + group("SessionStore:", () { + test("Capture and send cookies", () { + final store = SessionStore(server: server); + + store.capture(serverUri, [ + _cookie(SESSION_COOKIE_NAME, "abc", path: "/"), + _cookie(CSRF_COOKIE_NAME, "xyz", path: "/"), + ]); + + expect(store.hasSession, equals(true)); + expect(store.csrfToken, equals("xyz")); + + final String header = store.cookieHeader(serverUri); + expect(header, contains("sessionid=abc")); + expect(header, contains("csrftoken=xyz")); + }); + + test("Cookies are never accepted from or sent to another host", () { + final store = SessionStore(server: server); + + // Cookie received from a different host + store.capture(Uri.parse("https://evil.example.org/"), [ + _cookie(SESSION_COOKIE_NAME, "abc"), + ]); + + expect(store.hasSession, equals(false)); + + // Cookie for a domain the server does not belong to + store.capture(serverUri, [ + _cookie(SESSION_COOKIE_NAME, "abc", domain: "other.com"), + ]); + + expect(store.hasSession, equals(false)); + + store.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "abc")]); + expect(store.hasSession, equals(true)); + + expect(store.cookieHeader(Uri.parse("https://evil.example.org/")), ""); + + // Same host, different scheme / port + expect( + store.cookieHeader(Uri.parse("http://inventree.example.com/")), + "", + ); + expect( + store.cookieHeader(Uri.parse("https://inventree.example.com:8443/")), + "", + ); + }); + + test("Expiry and deletion", () { + final store = SessionStore(server: server); + + store.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "abc")]); + expect(store.hasSession, equals(true)); + + // Max-Age=0 deletes the cookie + store.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "", maxAge: 0)]); + expect(store.hasSession, equals(false)); + + // Expires in the past deletes the cookie + store.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "abc")]); + store.capture(serverUri, [ + _cookie(SESSION_COOKIE_NAME, "abc", expires: DateTime(1970)), + ]); + expect(store.hasSession, equals(false)); + }); + + test("Secure cookies are not sent over HTTP", () { + final store = SessionStore(server: "http://inventree.local"); + final uri = Uri.parse("http://inventree.local/api/"); + + store.capture(uri, [ + _cookie(SESSION_COOKIE_NAME, "abc", secure: true), + _cookie(CSRF_COOKIE_NAME, "xyz"), + ]); + + expect(store.cookieHeader(uri), equals("csrftoken=xyz")); + }); + + test("Path matching", () { + final store = SessionStore(server: server); + + store.capture(serverUri, [_cookie("scoped", "1", path: "/api")]); + + expect(store.cookieHeader(Uri.parse("${server}/api/part/")), "scoped=1"); + expect(store.cookieHeader(Uri.parse("${server}/api")), "scoped=1"); + expect(store.cookieHeader(Uri.parse("${server}/apix/")), ""); + expect(store.cookieHeader(Uri.parse("${server}/web/")), ""); + }); + + // A store which counts change notifications, and simulates each one being + // persisted successfully (as saveSession() does) + (SessionStore, int Function()) persistingStore() { + final store = SessionStore(server: server); + + int changes = 0; + + store.onChanged = () { + changes++; + store.markPersisted(store.snapshot()); + }; + + return (store, () => changes); + } + + test("Change notification", () { + final (store, changes) = persistingStore(); + + store.capture(serverUri, [_cookie(CSRF_COOKIE_NAME, "xyz", maxAge: 60)]); + expect(changes(), equals(1)); + + // Same value (and similar expiry) - no change reported + store.capture(serverUri, [_cookie(CSRF_COOKIE_NAME, "xyz", maxAge: 61)]); + expect(changes(), equals(1)); + + // New value + store.capture(serverUri, [_cookie(CSRF_COOKIE_NAME, "abc", maxAge: 60)]); + expect(changes(), equals(2)); + + // Deleted + store.capture(serverUri, [_cookie(CSRF_COOKIE_NAME, "", maxAge: 0)]); + expect(changes(), equals(3)); + }); + + test("Sliding expiry is persisted once it has moved by an hour", () { + final (store, changes) = persistingStore(); + final DateTime base = DateTime.now().add(Duration(days: 14)); + + store.capture(serverUri, [ + _cookie(SESSION_COOKIE_NAME, "abc", expires: base), + ]); + expect(changes(), equals(1)); + + // Each renewal is less than an hour after the previous one... + store.capture(serverUri, [ + _cookie( + SESSION_COOKIE_NAME, + "abc", + expires: base.add(Duration(minutes: 40)), + ), + ]); + expect(changes(), equals(1)); + + // ... but more than an hour after the persisted expiry + store.capture(serverUri, [ + _cookie( + SESSION_COOKIE_NAME, + "abc", + expires: base.add(Duration(minutes: 80)), + ), + ]); + expect(changes(), equals(2)); + + // Now compared against the new persisted expiry + store.capture(serverUri, [ + _cookie( + SESSION_COOKIE_NAME, + "abc", + expires: base.add(Duration(minutes: 120)), + ), + ]); + expect(changes(), equals(2)); + }); + + test("Cookie attribute changes are persisted", () { + for (final changed in [ + _cookie(CSRF_COOKIE_NAME, "xyz", path: "/api/"), + _cookie(CSRF_COOKIE_NAME, "xyz", secure: true), + _cookie(CSRF_COOKIE_NAME, "xyz", domain: "example.com"), + ]) { + final (store, changes) = persistingStore(); + + store.capture(serverUri, [_cookie(CSRF_COOKIE_NAME, "xyz")]); + expect(changes(), equals(1)); + + // Same value - but different path / secure / domain + store.capture(serverUri, [changed]); + expect(changes(), equals(2), reason: changed.toString()); + } + }); + + test("Changes are reported again after a failed write", () { + final store = SessionStore(server: server); + + int changes = 0; + bool writeSucceeds = false; + + store.onChanged = () { + changes++; + + if (writeSucceeds) { + store.markPersisted(store.snapshot()); + } + }; + + store.capture(serverUri, [_cookie(CSRF_COOKIE_NAME, "xyz")]); + expect(changes, equals(1)); + + // Not persisted - so the same cookie is reported again (write retried) + writeSucceeds = true; + store.capture(serverUri, [_cookie(CSRF_COOKIE_NAME, "xyz")]); + expect(changes, equals(2)); + + // Persisted - no further change + store.capture(serverUri, [_cookie(CSRF_COOKIE_NAME, "xyz")]); + expect(changes, equals(2)); + }); + + test("Restored cookies are treated as persisted", () { + final (original, _) = persistingStore(); + original.capture(serverUri, [ + _cookie(SESSION_COOKIE_NAME, "abc", maxAge: 3600), + ]); + + final restored = SessionStore.fromJson(server, original.toJson()); + + int changes = 0; + restored.onChanged = () => changes++; + + // Same cookie as stored - no write required + restored.capture(serverUri, [ + _cookie(SESSION_COOKIE_NAME, "abc", maxAge: 3600), + ]); + expect(changes, equals(0)); + }); + + test("saveSession records the persisted cookies", () async { + final manager = UserProfileDBManager(); + + final profile = UserProfile(name: "Persist Test", server: server); + await manager.addProfile(profile); + final loaded = (await manager.getProfileByName("Persist Test"))!; + + final session = SessionStore(server: server); + int changes = 0; + session.onChanged = () => changes++; + + session.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "abc")]); + expect(changes, equals(1)); + + // Failed write - still reported as changed + secureStorageFailures.add("write"); + expect(await manager.saveSession(loaded, session), equals(false)); + secureStorageFailures.clear(); + + session.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "abc")]); + expect(changes, equals(2)); + + // Successful write - no longer reported + expect(await manager.saveSession(loaded, session), equals(true)); + + session.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "abc")]); + expect(changes, equals(2)); + + await manager.deleteProfile(loaded); + }); + + test("Clear auth cookies retains other cookies", () { + final store = SessionStore(server: server); + + store.capture(serverUri, [ + _cookie(SESSION_COOKIE_NAME, "abc"), + _cookie(CSRF_COOKIE_NAME, "xyz"), + _cookie("mfa_trusted", "trusted"), + ]); + + store.clearAuthCookies(); + + expect(store.hasSession, equals(false)); + expect(store.hasCsrfToken, equals(false)); + expect(store.cookieHeader(serverUri), equals("mfa_trusted=trusted")); + + store.clear(); + expect(store.isEmpty, equals(true)); + }); + + test("Serialization", () { + final store = SessionStore(server: server); + + store.capture(serverUri, [ + _cookie(SESSION_COOKIE_NAME, "abc", maxAge: 3600), + _cookie(CSRF_COOKIE_NAME, "xyz", secure: true), + _cookie("expired", "old", expires: DateTime(1970)), + ]); + + final restored = SessionStore.fromJson(server, store.toJson()); + + expect(restored.hasSession, equals(true)); + expect(restored.csrfToken, equals("xyz")); + expect(restored.cookieNames.length, equals(2)); + + // Corrupt data results in an empty store + expect(SessionStore.fromJson(server, "not-json").isEmpty, equals(true)); + expect(SessionStore.fromJson(server, null).isEmpty, equals(true)); + }); + + test("Server origin", () { + expect( + serverOrigin("https://inventree.example.com"), + equals("https://inventree.example.com:443"), + ); + expect( + serverOrigin("HTTPS://InvenTree.Example.com:443/inventree/"), + equals("https://inventree.example.com:443"), + ); + expect( + serverOrigin("http://127.0.0.1:8000/"), + equals("http://127.0.0.1:8000"), + ); + expect(serverOrigin("not a url"), isEmpty); + expect(serverOrigin(""), isEmpty); + }); + + test("Stored cookies are only restored for the issuing origin", () { + final store = SessionStore(server: server); + store.capture(serverUri, [ + _cookie(SESSION_COOKIE_NAME, "abc"), + _cookie(CSRF_COOKIE_NAME, "xyz"), + _cookie("mfa_trusted", "trusted"), + ]); + + final String data = store.toJson(); + + // Same origin - including an explicit default port, a different path or case + for (final address in [ + server, + "https://inventree.example.com:443", + "https://inventree.example.com/inventree/", + "https://INVENTREE.example.com/", + ]) { + final restored = SessionStore.fromJson(address, data); + expect(restored.rejected, equals(false), reason: address); + expect(restored.hasSession, equals(true), reason: address); + } + + // Different origin - no cookies at all are restored (including MFA trust) + for (final address in [ + "http://inventree.example.com", + "https://inventree.example.com:8443", + "http://inventree.example.com:443", + "https://other.example.com", + "https://example.com", + "", + ]) { + final restored = SessionStore.fromJson(address, data); + expect(restored.rejected, equals(true), reason: address); + expect(restored.isEmpty, equals(true), reason: address); + expect( + restored.cookieHeader(Uri.parse("${address}/api/")), + isEmpty, + reason: address, + ); + } + }); + + test("Stored cookies without an origin are not restored", () { + // Format used before the origin was recorded + const String legacy = + '[{"name": "sessionid", "value": "abc", "domain": "inventree.example.com"}]'; + + final restored = SessionStore.fromJson(server, legacy); + + expect(restored.rejected, equals(true)); + expect(restored.isEmpty, equals(true)); + + expect( + SessionStore.fromJson(server, '{"cookies": []}').rejected, + equals(true), + ); + }); + + test("Set-Cookie header parsing", () { + // package:http folds multiple headers into one, separated by a comma + final values = splitSetCookieHeader( + [ + "sessionid=abc; expires=Thu, 01 Jan 2099 00:00:00 GMT; HttpOnly; Path=/", + "csrftoken=xyz; expires=Fri, 02 Jan 2099 00:00:00 GMT; Path=/", + ].join(","), + ); + + expect(values.length, equals(2)); + expect(values[0], startsWith("sessionid=abc")); + expect(values[1], startsWith("csrftoken=xyz")); + + final store = SessionStore(server: server); + + // A malformed cookie does not prevent the others from being stored + store.captureHeaders(serverUri, [...values, "=bad=;;"]); + + expect(store.hasSession, equals(true)); + expect(store.csrfToken, equals("xyz")); + }); + }); + + group("Request headers:", () { + final api = InvenTreeAPI(); + + setUp(() { + api.profile = UserProfile(name: "Test", server: server); + + api.session = SessionStore(server: server); + api.session.capture(serverUri, [ + _cookie(SESSION_COOKIE_NAME, "abc"), + _cookie(CSRF_COOKIE_NAME, "xyz"), + ]); + }); + + tearDown(() { + api.disconnectFromServer(); + }); + + test("Safe requests include cookies but not CSRF headers", () { + final headers = api.defaultHeaders(url: "part/"); + + expect(headers[HttpHeaders.cookieHeader], contains("sessionid=abc")); + expect(headers.containsKey("X-CSRFToken"), equals(false)); + expect(headers.containsKey(HttpHeaders.authorizationHeader), false); + }); + + test("Unsafe requests include CSRF headers", () { + for (final method in ["POST", "PUT", "PATCH", "DELETE"]) { + final headers = api.defaultHeaders(method: method, url: "part/"); + + expect(headers["X-CSRFToken"], equals("xyz")); + expect(headers["Origin"], equals(server)); + expect(headers[HttpHeaders.refererHeader], equals("${server}/")); + } + }); + + test("No credentials for other hosts", () { + final headers = api.defaultHeaders( + method: "POST", + url: "https://images.example.org/image.png", + ); + + expect(headers.containsKey(HttpHeaders.cookieHeader), equals(false)); + expect(headers.containsKey("X-CSRFToken"), equals(false)); + expect(headers.containsKey("Origin"), equals(false)); + }); + }); + + group("Error reporting:", () { + test("Credentials are redacted", () { + final String result = redactHeaders({ + "Cookie": "sessionid=abc", + "set-cookie": "sessionid=abc", + "X-CSRFToken": "xyz", + "Authorization": "Token 123", + "Accept": "application/json", + }); + + expect(result, isNot(contains("abc"))); + expect(result, isNot(contains("xyz"))); + expect(result, isNot(contains("123"))); + expect(result, contains("application/json")); + }); + }); + + group("AuthResult:", () { + APIResponse response(int status, Map data) => + APIResponse(statusCode: status, data: data); + + test("Authenticated", () { + final result = AuthResult.fromResponse( + response(200, { + "status": 200, + "data": { + "user": {"id": 1, "username": "admin"}, + }, + "meta": {"is_authenticated": true}, + }), + ); + + expect(result.status, equals(AuthStatus.authenticated)); + expect(result.user["username"], equals("admin")); + }); + + test("MFA required", () { + final result = AuthResult.fromResponse( + response(401, { + "status": 401, + "data": { + "flows": [ + {"id": "login"}, + { + "id": "mfa_authenticate", + "is_pending": true, + "types": ["totp", "recovery_codes"], + }, + ], + }, + "meta": {"is_authenticated": false}, + }), + ); + + expect(result.status, equals(AuthStatus.flowPending)); + expect(result.pendingFlow!.id, equals(FLOW_MFA_AUTHENTICATE)); + expect(result.pendingFlow!.isSupportedMfa, equals(true)); + expect(result.pendingFlow!.supportsRecoveryCodes, equals(true)); + }); + + test("Unsupported MFA types", () { + final flow = AuthFlow.fromJson({ + "id": "mfa_authenticate", + "is_pending": true, + "types": ["webauthn"], + }); + + expect(flow.isSupportedMfa, equals(false)); + }); + + test("Invalid credentials", () { + final result = AuthResult.fromResponse( + response(400, { + "status": 400, + "errors": [ + { + "message": + "The username and/or password you specified are not correct.", + "code": "username_password_mismatch", + }, + ], + }), + ); + + expect(result.status, equals(AuthStatus.failed)); + expect(result.errorMessage, contains("not correct")); + }); + + test("Not authenticated, no pending flow", () { + final result = AuthResult.fromResponse( + response(401, { + "status": 401, + "data": { + "flows": [ + {"id": "login"}, + ], + }, + "meta": {"is_authenticated": false}, + }), + ); + + expect(result.status, equals(AuthStatus.failed)); + }); + + test("No response", () { + final result = AuthResult.fromResponse(APIResponse()); + + expect(result.status, equals(AuthStatus.failed)); + expect(result.statusCode, equals(-1)); + }); + + test("Config", () { + final config = AuthConfig.fromResponse( + response(200, { + "status": 200, + "data": { + "account": { + "login_methods": ["email"], + }, + "mfa": { + "supported_types": ["totp", "recovery_codes", "webauthn"], + }, + "socialaccount": { + "providers": [ + { + "id": "google", + "name": "Google", + "flows": ["provider_redirect", "provider_token"], + "client_id": "123.apps.googleusercontent.com", + }, + ], + }, + }, + }), + ); + + expect(config.loginField, equals("email")); + expect(config.mfaTypes.length, equals(3)); + expect(config.providers.first.supportsTokenLogin, equals(true)); + + // Fallback to username for an invalid response + expect(AuthConfig.fromResponse(APIResponse()).loginField, "username"); + }); + }); + + group("UserProfile session storage:", () { + test("Save, load and clear", () async { + final manager = UserProfileDBManager(); + + final profile = UserProfile(name: "Session Test", server: server); + await manager.addProfile(profile); + + final session = SessionStore(server: server); + session.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "abc")]); + + await manager.saveSession(profile, session); + + final loaded = await manager.getProfileByName("Session Test"); + expect(loaded!.hasSession, equals(true)); + expect((await manager.loadSession(loaded)).hasSession, equals(true)); + + // The session must never be stored in the plain profile record + expect(loaded.toJson().toString(), isNot(contains("abc"))); + + await manager.clearSession(loaded); + expect((await manager.loadSession(loaded)).hasSession, equals(false)); + + await manager.deleteProfile(loaded); + }); + + test("Legacy API tokens are removed", () async { + final manager = UserProfileDBManager(); + final db = await InvenTreePreferencesDB.instance.database; + const storage = FlutterSecureStorage(); + + // Profile as stored by an older version of the app + final int key = + (await manager.store.add(db, { + "name": "Legacy Profile", + "server": server, + "token": "legacy-plaintext-token", + }))! + as int; + + await storage.write(key: "profile_token_${key}", value: "legacy-token"); + + await InvenTreeSettingsManager().setValue("legacy_tokens_removed", false); + await manager.migrateLegacyTokens(); + + expect(await storage.read(key: "profile_token_${key}"), isNull); + + final record = (await manager.store.record(key).get(db))! as Map; + expect(record.containsKey("token"), equals(false)); + expect(record["name"], equals("Legacy Profile")); + + await manager.store.record(key).delete(db); + }); + + test("Legacy token migration retries after a storage failure", () async { + final manager = UserProfileDBManager(); + final db = await InvenTreePreferencesDB.instance.database; + const storage = FlutterSecureStorage(); + + final List keys = []; + + for (final name in ["Legacy Retry A", "Legacy Retry B"]) { + keys.add( + (await manager.store.add(db, { + "name": name, + "server": server, + "token": "legacy-plaintext-token", + }))! + as int, + ); + } + + for (final key in keys) { + await storage.write(key: "profile_token_${key}", value: "legacy-token"); + } + + await InvenTreeSettingsManager().setValue("legacy_tokens_removed", false); + + // Secure storage deletion fails + secureStorageFailures.add("delete"); + + try { + await manager.migrateLegacyTokens(); + } finally { + secureStorageFailures.clear(); + } + + // Migration is not marked complete, so runs again on next startup + expect( + await InvenTreeSettingsManager().getBool( + "legacy_tokens_removed", + false, + ), + equals(false), + ); + + // Plaintext tokens are still stripped from *all* profiles in the meantime + for (final key in keys) { + final record = (await manager.store.record(key).get(db))! as Map; + expect(record.containsKey("token"), equals(false)); + expect(await storage.read(key: "profile_token_${key}"), isNotNull); + } + + // Next startup - storage is available again + await manager.migrateLegacyTokens(); + + for (final key in keys) { + expect(await storage.read(key: "profile_token_${key}"), isNull); + } + + expect( + await InvenTreeSettingsManager().getBool( + "legacy_tokens_removed", + false, + ), + equals(true), + ); + + for (final key in keys) { + await manager.store.record(key).delete(db); + } + }); + + test("Startup cleanup removes legacy tokens for existing profiles", () async { + final manager = UserProfileDBManager(); + const storage = FlutterSecureStorage(); + + final profile = UserProfile(name: "Legacy Cleanup", server: server); + await manager.addProfile(profile); + + final loaded = (await manager.getProfileByName("Legacy Cleanup"))!; + + // Token left behind for an existing profile (e.g. migration could not remove it) + await storage.write( + key: "profile_token_${loaded.key}", + value: "legacy-token", + ); + + // ... alongside the profile's (valid) session + final session = SessionStore(server: server); + session.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "abc")]); + await manager.saveSession(loaded, session); + + // Token for a profile which no longer exists + await storage.write(key: "profile_token_99998", value: "legacy-token"); + + await manager.removeOrphanedSessions(); + + expect(await storage.read(key: "profile_token_${loaded.key}"), isNull); + expect(await storage.read(key: "profile_token_99998"), isNull); + + // The session for the existing profile is retained + expect((await manager.loadSession(loaded)).hasSession, equals(true)); + + await manager.deleteProfile(loaded); + }); + + test("Logout keeps the username", () async { + final manager = UserProfileDBManager(); + + final profile = UserProfile( + name: "Username Test", + server: server, + username: "alice", + ); + await manager.addProfile(profile); + + final session = SessionStore(server: server); + session.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "abc")]); + await manager.saveSession(profile, session); + + await InvenTreeAuth().logout(profile); + + final loaded = await manager.getProfileByName("Username Test"); + expect(loaded!.username, equals("alice")); + expect(loaded.hasSession, equals(false)); + + // The password is never part of the profile + expect(loaded.toJson().keys, isNot(contains("password"))); + + await manager.deleteProfile(loaded); + }); + + test("Orphaned sessions are removed", () async { + final manager = UserProfileDBManager(); + const storage = FlutterSecureStorage(); + + final profile = UserProfile(name: "Orphan Test", server: server); + await manager.addProfile(profile); + + final session = SessionStore(server: server); + session.capture(serverUri, [_cookie(SESSION_COOKIE_NAME, "abc")]); + await manager.saveSession(profile, session); + + // Left behind by a profile which no longer exists (e.g. before a reinstall) + await storage.write(key: "profile_session_99999", value: "[]"); + await storage.write(key: "profile_token_99999", value: "legacy-token"); + + // Unrelated entries are not touched + await storage.write(key: "other_value", value: "keep"); + + await manager.removeOrphanedSessions(); + + expect(await storage.read(key: "profile_session_99999"), isNull); + expect(await storage.read(key: "profile_token_99999"), isNull); + expect(await storage.read(key: "other_value"), equals("keep")); + expect((await manager.loadSession(profile)).hasSession, equals(true)); + + await storage.delete(key: "other_value"); + await manager.deleteProfile(profile); + }); + }); +} diff --git a/test/fake_server.dart b/test/fake_server.dart new file mode 100644 index 00000000..3abc2525 --- /dev/null +++ b/test/fake_server.dart @@ -0,0 +1,429 @@ +/* + * A minimal in-process InvenTree server, for testing authentication + * without a running server. + * + * Implements just enough of the InvenTree API and the allauth "headless" + * (browser client) API to connect, login (optionally with MFA) and logout, + * including session and CSRF cookie handling. + * + * Individual endpoints can be overridden (once, or always) to simulate + * error conditions, and all received requests are recorded. + */ + +import "dart:async"; +import "dart:convert"; +import "dart:io"; + +class FakeRequest { + FakeRequest({ + required this.method, + required this.path, + required this.query, + required this.rawQuery, + required this.headers, + required this.cookies, + required this.body, + }); + + final String method; + final String path; + + // Decoded query parameters, and the query string as received + final Map query; + final String rawQuery; + + // Header names are lower case + final Map headers; + final Map cookies; + final String body; + + Map get json { + try { + return jsonDecode(body) as Map; + } catch (_) { + return {}; + } + } + + @override + String toString() => "${method} ${path}"; +} + +class FakeResponse { + FakeResponse( + this.status, { + this.body, + this.rawBody, + this.setCookies = const [], + this.dropConnection = false, + }); + + // Close the connection without sending a response + FakeResponse.drop() : this(0, dropConnection: true); + + final int status; + final Object? body; + + // Raw (non-JSON) response body, e.g. an HTML error page + final String? rawBody; + final List setCookies; + final bool dropConnection; +} + +typedef FakeHandler = FutureOr Function(FakeRequest request); + +class FakeInvenTreeServer { + FakeInvenTreeServer._(this._server, this.apiVersion); + + static Future start({int apiVersion = 568}) async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final fake = FakeInvenTreeServer._(server, apiVersion); + + server.listen(fake._handle); + + return fake; + } + + final HttpServer _server; + + final int apiVersion; + + String get url => "http://127.0.0.1:${_server.port}/"; + + // Accepted credentials (username -> password) + final Map users = {"user": "password", "mfa": "password"}; + + // Users which require a TOTP code after their password + final Set mfaUsers = {"mfa"}; + + // TOTP code accepted for MFA users + String validCode = "123456"; + + // Authenticator types offered in the pending MFA flow + List mfaTypes = ["totp", "recovery_codes"]; + + // After a valid MFA code, ask whether to trust the device (mfa_trust flow) + bool offerTrust = false; + + // Login methods reported by auth/v1/config + List loginMethods = ["username"]; + + // Requests received, in order + final List requests = []; + + // Active sessions (session ID -> username) + final Map sessions = {}; + + // Partially authenticated sessions, waiting for an MFA code + final Map _pending = {}; + + // Pending sessions which have entered a valid code, waiting for mfa_trust + final Set _trustPending = {}; + + int _counter = 0; + + final Map> _once = {}; + final Map _always = {}; + + Future close() => _server.close(force: true); + + // Override the next request for [method] [path] (path relative to the server root) + void once(String method, String path, FakeHandler handler) { + _once.putIfAbsent("${method} /${path}", () => []).add(handler); + } + + // Override all requests for [method] [path] + void always(String method, String path, FakeHandler handler) { + _always["${method} /${path}"] = handler; + } + + // Requests received for [method] [path] + List received(String method, String path) => requests + .where((r) => r.method == method && r.path == "/${path}") + .toList(); + + // End all sessions (e.g. expired, or ended from another device) + void endAllSessions() { + sessions.clear(); + _pending.clear(); + } + + String _newId(String prefix) { + _counter++; + return "${prefix}-${_server.port}-${_counter}"; + } + + Future _handle(HttpRequest request) async { + final Map headers = {}; + + request.headers.forEach((name, values) { + headers[name.toLowerCase()] = values.join(", "); + }); + + final Map cookies = {}; + + for (final cookie in request.cookies) { + cookies[cookie.name] = cookie.value; + } + + final fake = FakeRequest( + method: request.method, + path: request.uri.path, + query: request.uri.queryParameters, + rawQuery: request.uri.query, + headers: headers, + cookies: cookies, + body: await utf8.decoder.bind(request).join(), + ); + + requests.add(fake); + + final String key = "${fake.method} ${fake.path}"; + + FakeResponse response; + + if (_once[key]?.isNotEmpty ?? false) { + response = await _once[key]!.removeAt(0)(fake); + } else if (_always.containsKey(key)) { + response = await _always[key]!(fake); + } else { + response = _default(fake); + } + + if (response.dropConnection) { + final socket = await request.response.detachSocket(writeHeaders: false); + socket.destroy(); + return; + } + + request.response.statusCode = response.status; + request.response.headers.contentType = response.rawBody == null + ? ContentType.json + : ContentType.html; + + for (final cookie in response.setCookies) { + request.response.headers.add(HttpHeaders.setCookieHeader, cookie); + } + + if (response.rawBody != null) { + request.response.write(response.rawBody); + } else if (response.body != null) { + request.response.write(jsonEncode(response.body)); + } + + await request.response.close(); + } + + String? _user(FakeRequest request) => + sessions[request.cookies["sessionid"] ?? ""]; + + // Django CSRF check for "unsafe" requests + bool _csrfValid(FakeRequest request) { + final String cookie = request.cookies["csrftoken"] ?? ""; + + return cookie.isNotEmpty && + request.headers["x-csrftoken"] == cookie && + request.headers["origin"] == Uri.parse(url).origin; + } + + Map _authenticated(String username) => { + "status": 200, + "data": { + "user": {"username": username}, + "methods": [], + }, + "meta": {"is_authenticated": true}, + }; + + Map _flows({ + bool mfaPending = false, + bool trustPending = false, + }) => { + "status": 401, + "data": { + "flows": [ + {"id": "login"}, + if (mfaPending) + {"id": "mfa_authenticate", "is_pending": true, "types": mfaTypes}, + if (trustPending) {"id": "mfa_trust", "is_pending": true}, + ], + }, + "meta": {"is_authenticated": false}, + }; + + // Start a new (authenticated) session, rotating the CSRF token as Django does + FakeResponse _login(String username) { + final String sessionId = _newId("session"); + sessions[sessionId] = username; + + return FakeResponse( + 200, + body: _authenticated(username), + setCookies: [ + "sessionid=${sessionId}; HttpOnly; Path=/; SameSite=Lax", + "csrftoken=${_newId("csrf")}; Path=/; SameSite=Lax", + ], + ); + } + + FakeResponse _default(FakeRequest request) { + final bool unsafe = !["GET", "HEAD", "OPTIONS"].contains(request.method); + + if (unsafe && !_csrfValid(request)) { + return FakeResponse( + 403, + body: {"detail": "CSRF Failed: CSRF token missing."}, + ); + } + + final String? user = _user(request); + + switch ("${request.method} ${request.path}") { + case "GET /api/": + return FakeResponse( + 200, + body: { + "server": "InvenTree", + "version": "1.0.0", + "instance": "Fake Server", + "apiVersion": apiVersion, + }, + ); + case "GET /api/auth/v1/config": + return FakeResponse( + 200, + body: { + "status": 200, + "data": { + "account": {"login_methods": loginMethods}, + "socialaccount": {"providers": []}, + "mfa": { + "supported_types": ["totp", "recovery_codes"], + }, + }, + }, + ); + case "GET /api/auth/v1/auth/session": + if (user != null) { + return FakeResponse(200, body: _authenticated(user)); + } + + // Issue a CSRF token, if the client does not already have one + return FakeResponse( + 401, + body: _flows(), + setCookies: request.cookies.containsKey("csrftoken") + ? [] + : ["csrftoken=${_newId("csrf")}; Path=/; SameSite=Lax"], + ); + case "DELETE /api/auth/v1/auth/session": + sessions.remove(request.cookies["sessionid"]); + + return FakeResponse( + 401, + body: _flows(), + setCookies: [ + "sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/", + ], + ); + case "POST /api/auth/v1/auth/login": + final Map data = request.json; + final String login = (data["username"] ?? data["email"] ?? "") + .toString(); + + if (!users.containsKey(login) || users[login] != data["password"]) { + return FakeResponse( + 400, + body: { + "status": 400, + "errors": [ + { + "message": + "The username and/or password you specified are not correct.", + "code": "username_password_mismatch", + "param": "password", + }, + ], + }, + ); + } + + if (mfaUsers.contains(login)) { + final String pendingId = _newId("pending"); + _pending[pendingId] = login; + + return FakeResponse( + 401, + body: _flows(mfaPending: true), + setCookies: ["sessionid=${pendingId}; HttpOnly; Path=/"], + ); + } + + return _login(login); + case "POST /api/auth/v1/auth/2fa/authenticate": + final String? pendingUser = _pending[request.cookies["sessionid"]]; + + if (pendingUser == null) { + return FakeResponse(409, body: {"status": 409}); + } + + if (request.json["code"] != validCode) { + return FakeResponse( + 400, + body: { + "status": 400, + "errors": [ + {"message": "Incorrect code.", "code": "incorrect_code"}, + ], + }, + ); + } + + if (offerTrust) { + _trustPending.add(request.cookies["sessionid"]!); + return FakeResponse(401, body: _flows(trustPending: true)); + } + + _pending.remove(request.cookies["sessionid"]); + + return _login(pendingUser); + case "POST /api/auth/v1/auth/2fa/trust": + final String sessionId = request.cookies["sessionid"] ?? ""; + + if (!_trustPending.remove(sessionId)) { + return FakeResponse(409, body: {"status": 409}); + } + + return _login(_pending.remove(sessionId)!); + case "GET /api/user/me/": + if (user == null) { + return _unauthenticated(); + } + + return FakeResponse(200, body: {"pk": 1, "username": user}); + case "GET /api/user/me/roles/": + if (user == null) { + return _unauthenticated(); + } + + return FakeResponse(200, body: {"roles": {}, "permissions": {}}); + case "GET /api/plugins/": + return FakeResponse(200, body: []); + } + + if (user == null) { + return _unauthenticated(); + } + + // Any other (authenticated) request - echo back the request data + return FakeResponse( + request.method == "POST" ? 201 : 200, + body: {"method": request.method, "path": request.path}, + ); + } + + FakeResponse _unauthenticated() => FakeResponse( + 401, + body: {"detail": "Authentication credentials were not provided."}, + ); +} diff --git a/test/redact_test.dart b/test/redact_test.dart new file mode 100644 index 00000000..e02ec6f8 --- /dev/null +++ b/test/redact_test.dart @@ -0,0 +1,279 @@ +/* + * Tests for removal of credentials from error reports (sentry.io) + */ + +import "dart:convert"; + +import "package:flutter_test/flutter_test.dart"; +import "package:sentry_flutter/sentry_flutter.dart"; + +import "package:inventree/inventree/redact.dart"; + +// Credentials which must never appear in an error report +const List secrets = [ + "SESSION-SECRET-1", + "CSRF-SECRET-2", + "hunter2-password", + "inv-0123456789abcdef0123456789abcdef01234567-20261101", + "TRUST-SECRET-3", + "url-pass-4", + "query-token-5", + // Second word of a password containing whitespace + "SECOND-WORD-6", + // Password with a leading space + "LEADING-SPACE-7", +]; + +/* + * Captures (serialized) envelopes instead of sending them to sentry.io + */ +class CapturingTransport implements Transport { + CapturingTransport(this.options); + + final SentryOptions options; + + final List sent = []; + + @override + Future send(SentryEnvelope envelope) async { + final bytes = []; + + await for (final chunk in envelope.envelopeStream(options)) { + bytes.addAll(chunk); + } + + sent.add(utf8.decode(bytes)); + + return SentryId.newId(); + } +} + +void expectNoSecrets(String text) { + for (final secret in secrets) { + expect(text, isNot(contains(secret)), reason: "Leaked: ${secret}"); + } +} + +void main() { + group("redactString:", () { + final Map cases = { + "Cookie: sessionid=SESSION-SECRET-1; csrftoken=CSRF-SECRET-2": + "Cookie: ", + "set-cookie: sessionid=SESSION-SECRET-1; Path=/": + "set-cookie: ", + "Authorization: Token inv-0123456789abcdef0123456789abcdef01234567-20261101": + "Authorization: ", + "X-CSRFToken: CSRF-SECRET-2": "X-CSRFToken: ", + "sent sessionid=SESSION-SECRET-1 to server": + "sent sessionid= to server", + "mfa_trusted=TRUST-SECRET-3": "mfa_trusted=", + '{"username": "user", "password": "hunter2-password"}': + '{"username": "user", "password": ""}', + "{username: user, password: hunter2-password}": + "{username: user, password: }", + "header Bearer abc123def456ghi": "header Bearer ", + "token inv-0123456789abcdef0123456789abcdef01234567-20261101 used": + "token used", + "https://admin:url-pass-4@example.com/api/": + "https://@example.com/api/", + "https://example.com/api/?limit=10&token=query-token-5&offset=0": + "https://example.com/api/?limit=10&token=&offset=0", + }; + + for (final entry in cases.entries) { + test(entry.key, () { + expect(redactString(entry.key), equals(entry.value)); + }); + } + + // Values containing whitespace, delimiters or escaped quotes must be + // redacted entirely - not just up to the first space / delimiter + final Map quoted = { + // Whitespace + '{"password": "first second"}': '{"password": ""}', + '{"password": " leading-space"}': '{"password": ""}', + '{"password": "trailing-space "}': '{"password": ""}', + '{"password": " "}': '{"password": ""}', + '{"password": "tab\tand\nnewline"}': '{"password": ""}', + // Delimiters + '{"password": "a,b;c&d}e]f", "username": "user"}': + '{"password": "", "username": "user"}', + '{"password": "key: value, other: 1"}': '{"password": ""}', + // Escaped quotes and backslashes + r'{"password": "a\"b c\"d", "username": "user"}': + '{"password": "", "username": "user"}', + r'{"password": "ends with backslash\\", "username": "user"}': + '{"password": "", "username": "user"}', + // Single quotes (e.g. Python repr) + "{'password': 'first second', 'username': 'user'}": + "{'password': '', 'username': 'user'}", + r"{'password': 'it\'s a secret'}": "{'password': ''}", + // Unquoted (e.g. Dart Map.toString()) + "{password: first second, username: user}": + "{password: , username: user}", + "{username: user, password: first second}": + "{username: user, password: }", + // Pretty-printed JSON + '{\n "password": "first second",\n "username": "user"\n}': + '{\n "password": "",\n "username": "user"\n}', + // Truncated data - unterminated value is redacted to the end + '{"username": "user", "password": "first second third': + '{"username": "user", "password": "', + // key=value forms + 'password="first second" next=1': 'password="" next=1', + "token='a b' next=1": "token='' next=1", + "password=first+second&next=1": "password=&next=1", + // Headers with quoted values + r'"Cookie": "a=\"b c\"; sessionid=SESSION-SECRET-1", "Accept": "json"': + '"Cookie": "", "Accept": "json"', + '"Authorization": "Token abc def", "Accept": "json"': + '"Authorization": "", "Accept": "json"', + }; + + for (final entry in quoted.entries) { + test("Quoted: ${entry.key}", () { + expect(redactString(entry.key), equals(entry.value)); + }); + } + + test("Ordinary text is unchanged", () { + for (final text in [ + "Server error at http://127.0.0.1:8000/api/part/?limit=10&offset=20", + "Session expired - please login again", + "Token authentication has been removed", + "SocketException: Connection refused (OS Error: errno = 111)", + "API : Opening login screen for 'My Server'", + ]) { + expect(redactString(text), equals(text)); + } + }); + }); + + test("redactValue removes sensitive keys", () { + final dynamic result = redactValue({ + "url": "/api/part/", + "requestHeaders": "Cookie: sessionid=SESSION-SECRET-1", + "csrfToken": "CSRF-SECRET-2", + "nested": { + "password": "hunter2-password", + "items": [ + "ok", + {"sessionid": "SESSION-SECRET-1"}, + ], + }, + "statusCode": 500, + }); + + expectNoSecrets(result.toString()); + expect(result["url"], equals("/api/part/")); + expect(result["statusCode"], equals(500)); + expect(result["nested"]["items"][0], equals("ok")); + }); + + test("redactHeaders", () { + final String result = redactHeaders({ + "Cookie": "sessionid=SESSION-SECRET-1", + "X-CSRFToken": "CSRF-SECRET-2", + "Accept": "application/json", + }); + + expectNoSecrets(result); + expect(result, contains("Accept: application/json")); + }); + + test("redactSentryEvent", () { + final event = SentryEvent( + message: SentryMessage("Login failed: password=hunter2-password"), + exceptions: [ + SentryException( + type: "HttpException", + value: "Cookie: sessionid=SESSION-SECRET-1", + ), + ], + tags: {"csrftoken": "CSRF-SECRET-2", "server": "example.com"}, + breadcrumbs: [ + Breadcrumb(message: "DEBUG: mfa_trusted=TRUST-SECRET-3"), + Breadcrumb(data: {"token": "query-token-5"}), + ], + request: SentryRequest( + url: "https://admin:url-pass-4@example.com/api/", + queryString: "token=query-token-5", + headers: { + "Cookie": "sessionid=SESSION-SECRET-1", + "Accept": "application/json", + }, + data: {"password": "hunter2-password"}, + ), + ); + + event.contexts["context"] = { + "requestHeaders": "X-CSRFToken: CSRF-SECRET-2", + "responseData": '{"detail": "error", "token": "query-token-5"}', + "url": "/api/part/", + }; + event.contexts["stacktrace"] = "at login (sessionid=SESSION-SECRET-1)"; + + final SentryEvent result = redactSentryEvent(event); + + expectNoSecrets(jsonEncode(result.toJson())); + + // Useful information is retained + expect(result.tags!["server"], equals("example.com")); + expect(result.request!.headers["Accept"], equals("application/json")); + expect((result.contexts["context"] as Map)["url"], equals("/api/part/")); + }); + + test("Nothing sent to sentry.io contains credentials", () async { + late CapturingTransport transport; + + await Sentry.init((options) { + options.dsn = "https://public@sentry.example.com/1"; + + transport = CapturingTransport(options); + options.transport = transport; + + configureSentryPrivacy(options); + }); + + try { + // As reported by the app (see sentryReportMessage / sentryReportError) + Sentry.configureScope((scope) { + scope.setContexts("context", { + "requestHeaders": + "Cookie: sessionid=SESSION-SECRET-1; csrftoken=CSRF-SECRET-2", + "responseHeaders": "set-cookie: mfa_trusted=TRUST-SECRET-3; Path=/", + "responseData": + '{"password": "hunter2-password", "secret": "first SECOND-WORD-6"}', + "url": "https://example.com/api/?token=query-token-5", + }); + }); + + Sentry.addBreadcrumb( + Breadcrumb( + message: + "DEBUG: Authorization: Token inv-0123456789abcdef0123456789abcdef01234567-20261101", + ), + ); + + await Sentry.captureMessage( + "Server error at https://admin:url-pass-4@example.com/", + ); + + await Sentry.captureException( + Exception( + 'Request failed - Cookie: sessionid=SESSION-SECRET-1 - {"password": " LEADING-SPACE-7"}', + ), + stackTrace: StackTrace.current, + ); + + expect(transport.sent.length, equals(2)); + + for (final envelope in transport.sent) { + expectNoSecrets(envelope); + expect(envelope, contains(REDACTED)); + } + } finally { + await Sentry.close(); + } + }); +} diff --git a/test/setup.dart b/test/setup.dart index b27f3e2d..370b96c7 100644 --- a/test/setup.dart +++ b/test/setup.dart @@ -1,6 +1,9 @@ import "package:flutter/services.dart"; import "package:flutter_test/flutter_test.dart"; +import "package:package_info_plus/package_info_plus.dart"; import "package:inventree/api.dart"; +import "package:inventree/auth/auth_manager.dart"; +import "package:inventree/auth/auth_method.dart"; import "package:inventree/user_profile.dart"; // This is the same as the following issue except it keeps the http client @@ -10,10 +13,23 @@ class CustomBinding extends AutomatedTestWidgetsFlutterBinding { bool get overrideHttpClient => false; } +// Secure storage operations (e.g. "write", "delete") which should fail, +// to test handling of storage errors +final Set secureStorageFailures = {}; + void setupTestEnv() { // Uses custom binding to not override the http client CustomBinding(); + // Package information is used when building error reports + PackageInfo.setMockInitialValues( + appName: "InvenTree", + packageName: "inventree.inventree_app", + version: "0.0.0", + buildNumber: "0", + buildSignature: "", + ); + // Mock the path provider const MethodChannel channel = MethodChannel( "plugins.flutter.io/path_provider", @@ -23,7 +39,7 @@ void setupTestEnv() { return "."; }); - // Mock secure storage (used for storing profile API tokens) with a + // Mock secure storage (used for storing profile session cookies) with a // simple in-memory map, since there's no real platform keychain available // in the test harness final Map secureStorageMock = {}; @@ -34,6 +50,13 @@ void setupTestEnv() { .setMockMethodCallHandler(secureStorageChannel, ( MethodCall methodCall, ) async { + if (secureStorageFailures.contains(methodCall.method)) { + throw PlatformException( + code: "SecureStorageFailure", + message: "Simulated secure storage failure", + ); + } + final Map args = (methodCall.arguments as Map?) ?? {}; final String? key = args["key"] as String?; @@ -67,9 +90,9 @@ const String testUsername = "admin"; const String testPassword = "inventree"; /* - * Request an API token for the given profile + * Login to the server with the given profile (establishing a session) */ -Future fetchProfileToken({ +Future loginProfile({ UserProfile? profile, String username = testUsername, String password = testPassword, @@ -78,12 +101,12 @@ Future fetchProfileToken({ assert(profile != null); - final response = await InvenTreeAPI().fetchToken( + final result = await InvenTreeAuth().beginLogin( profile!, - username, - password, + PasswordAuthMethod(username, password), ); - return response.successful(); + + return result.authenticated; } /* @@ -91,7 +114,7 @@ Future fetchProfileToken({ */ Future setupServerProfile({ bool select = true, - bool fetchToken = false, + bool login = false, }) async { // Setup a valid server profile @@ -115,10 +138,10 @@ Future setupServerProfile({ assert(await UserProfileDBManager().selectProfileByName(testServerName)); } - if (fetchToken && !profile!.hasToken) { - final bool result = await fetchProfileToken(profile: profile); + if (login && !profile!.hasSession) { + final bool result = await loginProfile(profile: profile); assert(result); - assert(profile.hasToken); + assert(profile.hasSession); } return profile!; @@ -128,8 +151,8 @@ Future setupServerProfile({ * Complete all steps necessary to login to the server */ Future connectToTestServer() async { - // Setup profile, and fetch user token as necessary - final profile = await setupServerProfile(fetchToken: true); + // Setup profile, and login as necessary + final profile = await setupServerProfile(login: true); // Connect to the server assert(await InvenTreeAPI().connectToServer(profile)); diff --git a/test/widget/login_test.dart b/test/widget/login_test.dart new file mode 100644 index 00000000..41ba82ae --- /dev/null +++ b/test/widget/login_test.dart @@ -0,0 +1,721 @@ +/* + * Widget tests for the login and MFA screens, handleAuthResult(), + * and opening the login screen when the session expires. + * + * Network requests go to an in-process fake server (see fake_server.dart), + * so any interaction which sends a request runs inside tester.runAsync() + */ + +import "package:flutter/material.dart"; +import "package:flutter_tabler_icons/flutter_tabler_icons.dart"; +import "package:flutter_test/flutter_test.dart"; +import "package:one_context/one_context.dart"; + +import "package:inventree/api.dart"; +import "package:inventree/auth/auth_manager.dart"; +import "package:inventree/auth/auth_method.dart"; +import "package:inventree/auth/auth_result.dart"; +import "package:inventree/l10.dart"; +import "package:inventree/settings/login.dart"; +import "package:inventree/settings/login_mfa.dart"; +import "package:inventree/user_profile.dart"; +import "package:inventree/widget/dialogs.dart"; + +import "../fake_server.dart"; +import "../setup.dart"; + +const String profileName = "Login Widget Test"; +const String homeText = "Home screen"; + +late FakeInvenTreeServer server; + +late GlobalKey navigatorKey; + +InvenTreeAPI get api => InvenTreeAPI(); + +UserProfileDBManager get manager => UserProfileDBManager(); + +/* + * Create a profile pointing at the fake server + */ +Future fakeProfile() async { + final UserProfile? existing = await manager.getProfileByName(profileName); + + if (existing != null) { + await manager.deleteProfile(existing); + } + + await manager.addProfile(UserProfile(name: profileName, server: server.url)); + + return (await manager.getProfileByName(profileName))!; +} + +/* + * Show the home screen, and optionally push [screen] on top of it + * (so that returning "home" can be checked) + */ +Future pumpApp(WidgetTester tester, {Widget? screen}) async { + // Tall enough to show the whole login form + tester.view.physicalSize = const Size(800, 1600); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await tester.pumpWidget( + MaterialApp( + builder: OneContext().builder, + navigatorKey: navigatorKey, + home: const Scaffold(body: Text(homeText)), + ), + ); + + if (screen != null) { + navigatorKey.currentState!.push( + MaterialPageRoute(builder: (context) => screen), + ); + await tester.pumpAndSettle(); + } +} + +/* + * Perform [action] with real async (network) operations, + * waiting until [done] (or a timeout), then rebuild the widget tree + */ +Future runAndWait( + WidgetTester tester, + Future Function() action, { + required bool Function() done, +}) async { + await tester.runAsync(() async { + await action(); + + for (int i = 0; i < 100 && !done(); i++) { + await Future.delayed(const Duration(milliseconds: 20)); + } + + // Allow any work following the condition to complete (e.g. navigation) + await Future.delayed(const Duration(milliseconds: 50)); + }); + + await tester.pumpAndSettle(); +} + +Finder get usernameField => find.widgetWithText(TextFormField, L10().username); + +Finder get passwordField => find.widgetWithText(TextFormField, L10().password); + +Finder get loginButton => find.byIcon(TablerIcons.login); + +Finder get mfaSubmitButton => find.byIcon(TablerIcons.transition_right); + +Finder codeField(String label) => find.widgetWithText(TextFormField, label); + +EditableText editable(WidgetTester tester, Finder field) => + tester.widget( + find.descendant(of: field, matching: find.byType(EditableText)), + ); + +void main() { + setupTestEnv(); + + setUp(() async { + server = await FakeInvenTreeServer.start(); + // As in the app - OneContext (used to resolve colors) uses this navigator. + // A new key for each test, so no state carries over + OneContext().key = GlobalKey(); + navigatorKey = OneContext().key; + }); + + tearDown(() async { + api.testNavigatorKey = null; + api.disconnectFromServer(); + + final UserProfile? profile = await manager.getProfileByName(profileName); + + if (profile != null) { + await manager.deleteProfile(profile); + } + + await server.close(); + }); + + group("Login screen:", () { + testWidgets("Empty fields fail validation without sending a request", ( + tester, + ) async { + await pumpApp( + tester, + screen: InvenTreeLoginWidget( + UserProfile(name: profileName, server: server.url), + ), + ); + + // Whitespace is not a username + await tester.enterText(usernameField, " "); + + await tester.tap(loginButton); + await tester.pumpAndSettle(); + + expect(find.text(L10().usernameEmpty), findsOneWidget); + expect(find.text(L10().passwordEmpty), findsOneWidget); + expect(server.requests, isEmpty); + + // Still on the login screen + expect(find.byType(InvenTreeLoginWidget), findsOneWidget); + }); + + testWidgets("Username is pre-filled, with focus on the password", ( + tester, + ) async { + await pumpApp( + tester, + screen: InvenTreeLoginWidget( + UserProfile(name: profileName, server: server.url, username: "bob"), + ), + ); + + expect(editable(tester, usernameField).controller.text, equals("bob")); + expect(editable(tester, passwordField).controller.text, isEmpty); + + expect(editable(tester, passwordField).focusNode.hasFocus, isTrue); + expect(editable(tester, usernameField).focusNode.hasFocus, isFalse); + }); + + testWidgets("Focus starts on the username when none is stored", ( + tester, + ) async { + await pumpApp( + tester, + screen: InvenTreeLoginWidget( + UserProfile(name: profileName, server: server.url), + ), + ); + + expect(editable(tester, usernameField).controller.text, isEmpty); + expect(editable(tester, usernameField).focusNode.hasFocus, isTrue); + expect(editable(tester, passwordField).focusNode.hasFocus, isFalse); + }); + + testWidgets("Insecure connection warning is only shown for HTTP", ( + tester, + ) async { + await pumpApp( + tester, + screen: InvenTreeLoginWidget( + UserProfile(name: profileName, server: "http://example.com/"), + ), + ); + + expect(find.text(L10().insecureConnection), findsOneWidget); + expect(find.text("http://example.com/"), findsOneWidget); + + await pumpApp( + tester, + screen: InvenTreeLoginWidget( + UserProfile(name: profileName, server: "https://example.com/"), + ), + ); + + expect(find.text(L10().insecureConnection), findsNothing); + expect(find.text("https://example.com/"), findsOneWidget); + }); + + testWidgets("Password visibility can be toggled", (tester) async { + await pumpApp( + tester, + screen: InvenTreeLoginWidget( + UserProfile(name: profileName, server: server.url), + ), + ); + + expect(editable(tester, passwordField).obscureText, isTrue); + + await tester.tap(find.byIcon(TablerIcons.eye)); + await tester.pump(); + + expect(editable(tester, passwordField).obscureText, isFalse); + + await tester.tap(find.byIcon(TablerIcons.eye_off)); + await tester.pump(); + + expect(editable(tester, passwordField).obscureText, isTrue); + }); + + testWidgets("Login error is displayed", (tester) async { + final profile = (await tester.runAsync(fakeProfile))!; + + await pumpApp(tester, screen: InvenTreeLoginWidget(profile)); + + await tester.enterText(usernameField, "user"); + await tester.enterText(passwordField, "wrong"); + + await runAndWait( + tester, + () => tester.tap(loginButton), + done: () => + server.received("POST", "api/auth/v1/auth/login").isNotEmpty, + ); + + expect(find.text(L10().error), findsOneWidget); + expect( + find.text( + "The username and/or password you specified are not correct.", + ), + findsOneWidget, + ); + + expect(find.byType(InvenTreeLoginWidget), findsOneWidget); + expect(api.isConnected(), isFalse); + expect(profile.hasSession, isFalse); + }); + + testWidgets("Keyboard 'done' on the password field logs in", ( + tester, + ) async { + final profile = (await tester.runAsync(fakeProfile))!; + + await pumpApp(tester, screen: InvenTreeLoginWidget(profile)); + + await tester.enterText(usernameField, "user"); + await tester.enterText(passwordField, "password"); + + await runAndWait( + tester, + () => tester.testTextInput.receiveAction(TextInputAction.done), + done: () => api.isConnected(), + ); + + expect(api.isConnected(), isTrue); + expect(find.byType(InvenTreeLoginWidget), findsNothing); + expect(find.text(homeText), findsOneWidget); + }); + }); + + group("MFA screen:", () { + AuthFlow mfaFlow(List types) => + AuthFlow(id: FLOW_MFA_AUTHENTICATE, isPending: true, types: types); + + Future pumpMfa(WidgetTester tester, List types) => pumpApp( + tester, + screen: InvenTreeMfaWidget( + UserProfile(name: profileName, server: server.url), + mfaFlow(types), + ), + ); + + testWidgets( + "Recovery code switch is offered with TOTP and recovery codes", + (tester) async { + await pumpMfa(tester, [MFA_TYPE_TOTP, MFA_TYPE_RECOVERY_CODES]); + + expect(find.text(L10().mfaEnterCode), findsOneWidget); + expect(codeField(L10().mfaCode), findsOneWidget); + expect( + editable(tester, codeField(L10().mfaCode)).keyboardType, + equals(TextInputType.number), + ); + + await tester.tap(find.text(L10().mfaUseRecoveryCode)); + await tester.pumpAndSettle(); + + expect(find.text(L10().mfaEnterRecoveryCode), findsOneWidget); + expect(codeField(L10().mfaRecoveryCode), findsOneWidget); + expect(codeField(L10().mfaCode), findsNothing); + expect( + editable(tester, codeField(L10().mfaRecoveryCode)).keyboardType, + equals(TextInputType.visiblePassword), + ); + + // ...and back again + await tester.tap(find.text(L10().mfaUseRecoveryCode)); + await tester.pumpAndSettle(); + + expect(codeField(L10().mfaCode), findsOneWidget); + }, + ); + + testWidgets("No recovery code switch with TOTP only", (tester) async { + await pumpMfa(tester, [MFA_TYPE_TOTP]); + + expect(find.text(L10().mfaUseRecoveryCode), findsNothing); + expect(codeField(L10().mfaCode), findsOneWidget); + }); + + testWidgets("Recovery codes only asks for a recovery code", (tester) async { + await pumpMfa(tester, [MFA_TYPE_RECOVERY_CODES]); + + expect(find.text(L10().mfaUseRecoveryCode), findsNothing); + expect(find.text(L10().mfaEnterRecoveryCode), findsOneWidget); + expect(codeField(L10().mfaRecoveryCode), findsOneWidget); + }); + + testWidgets("TOTP code accepts digits only", (tester) async { + await pumpMfa(tester, [MFA_TYPE_TOTP, MFA_TYPE_RECOVERY_CODES]); + + await tester.enterText(codeField(L10().mfaCode), "12ab34"); + + expect( + editable(tester, codeField(L10().mfaCode)).controller.text, + equals("1234"), + ); + + // Recovery codes are not restricted + await tester.tap(find.text(L10().mfaUseRecoveryCode)); + await tester.pumpAndSettle(); + + await tester.enterText(codeField(L10().mfaRecoveryCode), "ab12-cd34"); + + expect( + editable(tester, codeField(L10().mfaRecoveryCode)).controller.text, + equals("ab12-cd34"), + ); + }); + + testWidgets("Empty code fails validation without sending a request", ( + tester, + ) async { + await pumpMfa(tester, [MFA_TYPE_TOTP]); + + await tester.tap(mfaSubmitButton); + await tester.pumpAndSettle(); + + expect(find.text(L10().mfaCodeEmpty), findsOneWidget); + + // Whitespace is not a code + await pumpMfa(tester, [MFA_TYPE_RECOVERY_CODES]); + + await tester.enterText(codeField(L10().mfaRecoveryCode), " "); + await tester.tap(mfaSubmitButton); + await tester.pumpAndSettle(); + + expect(find.text(L10().mfaCodeEmpty), findsOneWidget); + expect(server.requests, isEmpty); + }); + + Future beginMfaLogin(WidgetTester tester) async { + final UserProfile profile = (await tester.runAsync(() async { + final UserProfile profile = await fakeProfile(); + + final AuthResult result = await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod("mfa", "password"), + ); + + expect(result.status, equals(AuthStatus.flowPending)); + + return profile; + }))!; + + await pumpApp( + tester, + screen: InvenTreeMfaWidget(profile, mfaFlow(server.mfaTypes)), + ); + + return profile; + } + + testWidgets("Incorrect code is displayed", (tester) async { + await beginMfaLogin(tester); + + await tester.enterText(codeField(L10().mfaCode), "000000"); + + await runAndWait( + tester, + () => tester.tap(mfaSubmitButton), + done: () => server + .received("POST", "api/auth/v1/auth/2fa/authenticate") + .isNotEmpty, + ); + + expect(find.text("Incorrect code."), findsOneWidget); + expect(find.byType(InvenTreeMfaWidget), findsOneWidget); + expect(api.isConnected(), isFalse); + }); + + for (final bool trust in [true, false]) { + testWidgets("Trust device checkbox is sent to the server (${trust})", ( + tester, + ) async { + server.offerTrust = true; + + final profile = await beginMfaLogin(tester); + + // Unchecked by default + expect( + tester.widget(find.byType(CheckboxListTile)).value, + isFalse, + ); + + if (trust) { + await tester.tap(find.text(L10().mfaTrustDevice)); + await tester.pump(); + + expect( + tester + .widget(find.byType(CheckboxListTile)) + .value, + isTrue, + ); + } + + await tester.enterText(codeField(L10().mfaCode), server.validCode); + + await runAndWait( + tester, + () => tester.tap(mfaSubmitButton), + done: () => api.isConnected(), + ); + + final requests = server.received("POST", "api/auth/v1/auth/2fa/trust"); + expect(requests.length, equals(1)); + expect(requests.single.json["trust"], equals(trust)); + + expect(api.isConnected(), isTrue); + expect(profile.hasSession, isTrue); + expect(find.byType(InvenTreeMfaWidget), findsNothing); + expect(find.text(homeText), findsOneWidget); + }); + } + }); + + group("handleAuthResult:", () { + testWidgets("Successful login connects and returns home", (tester) async { + final profile = (await tester.runAsync(fakeProfile))!; + + await pumpApp(tester, screen: InvenTreeLoginWidget(profile)); + + await tester.enterText(usernameField, "user"); + await tester.enterText(passwordField, "password"); + + await runAndWait( + tester, + () => tester.tap(loginButton), + done: () => api.isConnected(), + ); + + expect(api.isConnected(), isTrue); + expect(profile.hasSession, isTrue); + expect(profile.username, equals("user")); + + expect(find.byType(InvenTreeLoginWidget), findsNothing); + expect(find.text(homeText), findsOneWidget); + }); + + testWidgets("MFA required opens the MFA screen, then returns home", ( + tester, + ) async { + final profile = (await tester.runAsync(fakeProfile))!; + + await pumpApp(tester, screen: InvenTreeLoginWidget(profile)); + + await tester.enterText(usernameField, "mfa"); + await tester.enterText(passwordField, "password"); + + await runAndWait( + tester, + () => tester.tap(loginButton), + done: () => + server.received("POST", "api/auth/v1/auth/login").isNotEmpty, + ); + + expect(find.byType(InvenTreeMfaWidget), findsOneWidget); + expect(api.isConnected(), isFalse); + + await tester.enterText(codeField(L10().mfaCode), server.validCode); + + await runAndWait( + tester, + () => tester.tap(mfaSubmitButton), + done: () => api.isConnected(), + ); + + expect(api.isConnected(), isTrue); + + // Both the MFA and login screens are closed + expect(find.byType(InvenTreeMfaWidget), findsNothing); + expect(find.byType(InvenTreeLoginWidget), findsNothing); + expect(find.text(homeText), findsOneWidget); + }); + + /* + * Call handleAuthResult() directly from the login screen, + * returning the reported errors + */ + Future> handle(WidgetTester tester, AuthResult result) async { + final UserProfile profile = UserProfile( + name: profileName, + server: server.url, + ); + + await pumpApp(tester, screen: InvenTreeLoginWidget(profile)); + + final List errors = []; + + await handleAuthResult( + tester.element(find.byType(InvenTreeLoginWidget)), + profile, + result, + errors.add, + ); + + await tester.pumpAndSettle(); + + // No navigation + expect(find.byType(InvenTreeLoginWidget), findsOneWidget); + expect(find.byType(InvenTreeMfaWidget), findsNothing); + + return errors; + } + + AuthResult pending(String id, {List types = const []}) => + AuthResult( + status: AuthStatus.flowPending, + statusCode: 401, + pendingFlow: AuthFlow(id: id, isPending: true, types: types), + ); + + testWidgets("Unsupported MFA types show an error", (tester) async { + final errors = await handle( + tester, + pending(FLOW_MFA_AUTHENTICATE, types: [MFA_TYPE_WEBAUTHN]), + ); + + expect(errors, equals([L10().mfaUnsupported])); + }); + + testWidgets("Unsupported flows show an error", (tester) async { + final errors = await handle(tester, pending(FLOW_VERIFY_EMAIL)); + + expect( + errors, + equals(["${L10().authFlowUnsupported} (${FLOW_VERIFY_EMAIL})"]), + ); + }); + + testWidgets("Failure shows the server error message", (tester) async { + final errors = await handle(tester, AuthResult.failed("Bad things")); + + expect(errors, equals(["Bad things"])); + }); + + testWidgets("Failure without a message describes the status code", ( + tester, + ) async { + final errors = await handle( + tester, + AuthResult(status: AuthStatus.failed, statusCode: 429), + ); + + expect(errors, equals([statusCodeToString(429)])); + expect(errors.single, isNotEmpty); + }); + }); + + group("Session expiry:", () { + testWidgets("Expiry while connected opens the login screen", ( + tester, + ) async { + api.testNavigatorKey = navigatorKey; + + await pumpApp(tester); + + final profile = (await tester.runAsync(() async { + final profile = await fakeProfile(); + + await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod("user", "password"), + ); + + expect(await api.connectToServer(profile), isTrue); + + return profile; + }))!; + + expect(find.byType(InvenTreeLoginWidget), findsNothing); + + server.endAllSessions(); + + await runAndWait( + tester, + () => api.get("part/", expectedStatusCode: null), + done: () => !api.isConnected(), + ); + + // Login screen for the expired profile, with the username kept + expect(find.byType(InvenTreeLoginWidget), findsOneWidget); + expect(find.text(profile.server), findsOneWidget); + expect(editable(tester, usernameField).controller.text, equals("user")); + + // Further rejected requests do not open a second login screen + await runAndWait( + tester, + () => api.get("stock/", expectedStatusCode: null), + done: () => server.received("GET", "api/stock/").isNotEmpty, + ); + + expect(find.byType(InvenTreeLoginWidget), findsOneWidget); + + // Login again, returning to the home screen + await tester.enterText(passwordField, "password"); + + await runAndWait( + tester, + () => tester.tap(loginButton), + done: () => api.isConnected(), + ); + + expect(api.isConnected(), isTrue); + expect(api.suppressServerErrors, isFalse); + expect(find.byType(InvenTreeLoginWidget), findsNothing); + expect(find.text(homeText), findsOneWidget); + }); + + testWidgets("Dismissed login screen opens again on the next rejection", ( + tester, + ) async { + api.testNavigatorKey = navigatorKey; + + await pumpApp(tester); + + await tester.runAsync(() async { + final profile = await fakeProfile(); + + await InvenTreeAuth().beginLogin( + profile, + PasswordAuthMethod("user", "password"), + ); + + expect(await api.connectToServer(profile), isTrue); + }); + + server.endAllSessions(); + + await runAndWait( + tester, + () => api.get("part/", expectedStatusCode: null), + done: () => !api.isConnected(), + ); + + expect(find.byType(InvenTreeLoginWidget), findsOneWidget); + expect(api.suppressServerErrors, isTrue); + + // User goes back without logging in + await tester.runAsync(() async { + navigatorKey.currentState!.pop(); + await Future.delayed(Duration.zero); + }); + await tester.pumpAndSettle(); + + expect(find.byType(InvenTreeLoginWidget), findsNothing); + expect(api.suppressServerErrors, isFalse); + + await runAndWait( + tester, + () => api.get("part/", expectedStatusCode: null), + done: () => server.received("GET", "api/part/").length >= 2, + ); + + expect(find.byType(InvenTreeLoginWidget), findsOneWidget); + }); + }); +}