mirror of
https://github.com/inventree/inventree-app.git
synced 2026-11-28 16:25:05 +00:00
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
This commit is contained in:
1 parent
3d639882d3
commit
c75403b3ed
33 files changed
+6948
-417
No files matched your search
+31
-15
@@ -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'");
|
||||
});
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<int> 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<int> 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<String> 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<void>.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<AuthResult> 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<UserProfile> 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<int> 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<void>();
|
||||
|
||||
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<void> 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<void>();
|
||||
|
||||
// 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)));
|
||||
});
|
||||
}
|
||||
@@ -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<String, dynamic> 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<int> 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);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -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<String, String> query;
|
||||
final String rawQuery;
|
||||
|
||||
// Header names are lower case
|
||||
final Map<String, String> headers;
|
||||
final Map<String, String> cookies;
|
||||
final String body;
|
||||
|
||||
Map<String, dynamic> get json {
|
||||
try {
|
||||
return jsonDecode(body) as Map<String, dynamic>;
|
||||
} 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<String> setCookies;
|
||||
final bool dropConnection;
|
||||
}
|
||||
|
||||
typedef FakeHandler = FutureOr<FakeResponse> Function(FakeRequest request);
|
||||
|
||||
class FakeInvenTreeServer {
|
||||
FakeInvenTreeServer._(this._server, this.apiVersion);
|
||||
|
||||
static Future<FakeInvenTreeServer> 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<String, String> users = {"user": "password", "mfa": "password"};
|
||||
|
||||
// Users which require a TOTP code after their password
|
||||
final Set<String> mfaUsers = {"mfa"};
|
||||
|
||||
// TOTP code accepted for MFA users
|
||||
String validCode = "123456";
|
||||
|
||||
// Authenticator types offered in the pending MFA flow
|
||||
List<String> 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<String> loginMethods = ["username"];
|
||||
|
||||
// Requests received, in order
|
||||
final List<FakeRequest> requests = [];
|
||||
|
||||
// Active sessions (session ID -> username)
|
||||
final Map<String, String> sessions = {};
|
||||
|
||||
// Partially authenticated sessions, waiting for an MFA code
|
||||
final Map<String, String> _pending = {};
|
||||
|
||||
// Pending sessions which have entered a valid code, waiting for mfa_trust
|
||||
final Set<String> _trustPending = {};
|
||||
|
||||
int _counter = 0;
|
||||
|
||||
final Map<String, List<FakeHandler>> _once = {};
|
||||
final Map<String, FakeHandler> _always = {};
|
||||
|
||||
Future<void> 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<FakeRequest> 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<void> _handle(HttpRequest request) async {
|
||||
final Map<String, String> headers = {};
|
||||
|
||||
request.headers.forEach((name, values) {
|
||||
headers[name.toLowerCase()] = values.join(", ");
|
||||
});
|
||||
|
||||
final Map<String, String> 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<String, dynamic> _authenticated(String username) => {
|
||||
"status": 200,
|
||||
"data": {
|
||||
"user": {"username": username},
|
||||
"methods": [],
|
||||
},
|
||||
"meta": {"is_authenticated": true},
|
||||
};
|
||||
|
||||
Map<String, dynamic> _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<String, dynamic> 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."},
|
||||
);
|
||||
}
|
||||
@@ -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<String> 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<String> sent = [];
|
||||
|
||||
@override
|
||||
Future<SentryId?> send(SentryEnvelope envelope) async {
|
||||
final bytes = <int>[];
|
||||
|
||||
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<String, String> cases = {
|
||||
"Cookie: sessionid=SESSION-SECRET-1; csrftoken=CSRF-SECRET-2":
|
||||
"Cookie: <redacted>",
|
||||
"set-cookie: sessionid=SESSION-SECRET-1; Path=/":
|
||||
"set-cookie: <redacted>",
|
||||
"Authorization: Token inv-0123456789abcdef0123456789abcdef01234567-20261101":
|
||||
"Authorization: <redacted>",
|
||||
"X-CSRFToken: CSRF-SECRET-2": "X-CSRFToken: <redacted>",
|
||||
"sent sessionid=SESSION-SECRET-1 to server":
|
||||
"sent sessionid=<redacted> to server",
|
||||
"mfa_trusted=TRUST-SECRET-3": "mfa_trusted=<redacted>",
|
||||
'{"username": "user", "password": "hunter2-password"}':
|
||||
'{"username": "user", "password": "<redacted>"}',
|
||||
"{username: user, password: hunter2-password}":
|
||||
"{username: user, password: <redacted>}",
|
||||
"header Bearer abc123def456ghi": "header Bearer <redacted>",
|
||||
"token inv-0123456789abcdef0123456789abcdef01234567-20261101 used":
|
||||
"token <redacted> used",
|
||||
"https://admin:url-pass-4@example.com/api/":
|
||||
"https://<redacted>@example.com/api/",
|
||||
"https://example.com/api/?limit=10&token=query-token-5&offset=0":
|
||||
"https://example.com/api/?limit=10&token=<redacted>&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<String, String> quoted = {
|
||||
// Whitespace
|
||||
'{"password": "first second"}': '{"password": "<redacted>"}',
|
||||
'{"password": " leading-space"}': '{"password": "<redacted>"}',
|
||||
'{"password": "trailing-space "}': '{"password": "<redacted>"}',
|
||||
'{"password": " "}': '{"password": "<redacted>"}',
|
||||
'{"password": "tab\tand\nnewline"}': '{"password": "<redacted>"}',
|
||||
// Delimiters
|
||||
'{"password": "a,b;c&d}e]f", "username": "user"}':
|
||||
'{"password": "<redacted>", "username": "user"}',
|
||||
'{"password": "key: value, other: 1"}': '{"password": "<redacted>"}',
|
||||
// Escaped quotes and backslashes
|
||||
r'{"password": "a\"b c\"d", "username": "user"}':
|
||||
'{"password": "<redacted>", "username": "user"}',
|
||||
r'{"password": "ends with backslash\\", "username": "user"}':
|
||||
'{"password": "<redacted>", "username": "user"}',
|
||||
// Single quotes (e.g. Python repr)
|
||||
"{'password': 'first second', 'username': 'user'}":
|
||||
"{'password': '<redacted>', 'username': 'user'}",
|
||||
r"{'password': 'it\'s a secret'}": "{'password': '<redacted>'}",
|
||||
// Unquoted (e.g. Dart Map.toString())
|
||||
"{password: first second, username: user}":
|
||||
"{password: <redacted>, username: user}",
|
||||
"{username: user, password: first second}":
|
||||
"{username: user, password: <redacted>}",
|
||||
// Pretty-printed JSON
|
||||
'{\n "password": "first second",\n "username": "user"\n}':
|
||||
'{\n "password": "<redacted>",\n "username": "user"\n}',
|
||||
// Truncated data - unterminated value is redacted to the end
|
||||
'{"username": "user", "password": "first second third':
|
||||
'{"username": "user", "password": "<redacted>',
|
||||
// key=value forms
|
||||
'password="first second" next=1': 'password="<redacted>" next=1',
|
||||
"token='a b' next=1": "token='<redacted>' next=1",
|
||||
"password=first+second&next=1": "password=<redacted>&next=1",
|
||||
// Headers with quoted values
|
||||
r'"Cookie": "a=\"b c\"; sessionid=SESSION-SECRET-1", "Accept": "json"':
|
||||
'"Cookie": "<redacted>", "Accept": "json"',
|
||||
'"Authorization": "Token abc def", "Accept": "json"':
|
||||
'"Authorization": "<redacted>", "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();
|
||||
}
|
||||
});
|
||||
}
|
||||
+36
-13
@@ -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<String> 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<String, String> 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<dynamic, dynamic> args =
|
||||
(methodCall.arguments as Map<dynamic, dynamic>?) ?? {};
|
||||
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<bool> fetchProfileToken({
|
||||
Future<bool> loginProfile({
|
||||
UserProfile? profile,
|
||||
String username = testUsername,
|
||||
String password = testPassword,
|
||||
@@ -78,12 +101,12 @@ Future<bool> 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<bool> fetchProfileToken({
|
||||
*/
|
||||
Future<UserProfile> setupServerProfile({
|
||||
bool select = true,
|
||||
bool fetchToken = false,
|
||||
bool login = false,
|
||||
}) async {
|
||||
// Setup a valid server profile
|
||||
|
||||
@@ -115,10 +138,10 @@ Future<UserProfile> 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<UserProfile> setupServerProfile({
|
||||
* Complete all steps necessary to login to the server
|
||||
*/
|
||||
Future<void> 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));
|
||||
|
||||
@@ -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<NavigatorState> navigatorKey;
|
||||
|
||||
InvenTreeAPI get api => InvenTreeAPI();
|
||||
|
||||
UserProfileDBManager get manager => UserProfileDBManager();
|
||||
|
||||
/*
|
||||
* Create a profile pointing at the fake server
|
||||
*/
|
||||
Future<UserProfile> 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<void> 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<void>(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<void> runAndWait(
|
||||
WidgetTester tester,
|
||||
Future<void> Function() action, {
|
||||
required bool Function() done,
|
||||
}) async {
|
||||
await tester.runAsync(() async {
|
||||
await action();
|
||||
|
||||
for (int i = 0; i < 100 && !done(); i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
}
|
||||
|
||||
// Allow any work following the condition to complete (e.g. navigation)
|
||||
await Future<void>.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<EditableText>(
|
||||
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<NavigatorState>();
|
||||
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<String> types) =>
|
||||
AuthFlow(id: FLOW_MFA_AUTHENTICATE, isPending: true, types: types);
|
||||
|
||||
Future<void> pumpMfa(WidgetTester tester, List<String> 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<UserProfile> 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<CheckboxListTile>(find.byType(CheckboxListTile)).value,
|
||||
isFalse,
|
||||
);
|
||||
|
||||
if (trust) {
|
||||
await tester.tap(find.text(L10().mfaTrustDevice));
|
||||
await tester.pump();
|
||||
|
||||
expect(
|
||||
tester
|
||||
.widget<CheckboxListTile>(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<List<String>> handle(WidgetTester tester, AuthResult result) async {
|
||||
final UserProfile profile = UserProfile(
|
||||
name: profileName,
|
||||
server: server.url,
|
||||
);
|
||||
|
||||
await pumpApp(tester, screen: InvenTreeLoginWidget(profile));
|
||||
|
||||
final List<String> 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<String> 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<void>.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);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user