Skip to content

Commit

Permalink
fix: 829 - no more crash if the user name is not ASCII/ISO-8859-1 (#830)
Browse files Browse the repository at this point in the history
Impacted files:
* `http_helper.dart`: safer `From` http header.
* `user_management_test_test_env.dart`: new test if the login crashes with a non-ASCII/ISO-8859-1 username
  • Loading branch information
monsieurtanuki authored Nov 22, 2023
1 parent a98cfcb commit 8a23aee
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
30 changes: 27 additions & 3 deletions lib/src/utils/http_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class HttpHelper {
}
}

http.Response response = await http.post(
return http.post(
uri,
headers: _buildHeaders(
user: user,
Expand All @@ -105,7 +105,6 @@ class HttpHelper {
),
body: addUserAgentParameters(body),
);
return response;
}

static const String userInfoForTest = 'off:off';
Expand Down Expand Up @@ -214,7 +213,9 @@ class HttpHelper {
headers.addAll({
'Accept': 'application/json',
'User-Agent': OpenFoodAPIConfiguration.userAgent!.toValueString(),
'From': OpenFoodAPIConfiguration.getUser(user)?.userId ?? FROM,
'From': _getSafeString(
OpenFoodAPIConfiguration.getUser(user)?.userId ?? FROM,
),
});

final bool isTestModeActive = uriHelper.isTestMode;
Expand Down Expand Up @@ -254,4 +255,27 @@ class HttpHelper {
rethrow;
}
}

/// Returns true if the [input] string is ISO-8859-1 encoded.
static bool _isIso88591(final String input) {
try {
latin1.encode(input);
return true;
} catch (e) {
return false;
}
}

/// Returns the [input] string if ISO-8859-1 encoded, or a safer version of it
///
/// Used for HTTP headers, that do not accept any other charset.
/// Here instead of encoding systematically, we keep ISO-8859-1 inputs and
/// only encode the other "problematic" inputs.
/// cf. https://github.com/openfoodfacts/openfoodfacts-dart/issues/829
static String _getSafeString(final String input) {
if (_isIso88591(input)) {
return input;
}
return base64Encode(utf8.encode(input));
}
}
9 changes: 9 additions & 0 deletions test/user_management_test_test_env.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,15 @@ void main() {
expect(status?.successful, false);
expect(status?.statusVerbose, 'user not signed-in');
});

test('Login with problematic charset', () async {
final LoginStatus? status = await OpenFoodAPIClient.login2(
User(userId: 'លីវយី', password: ''),
uriHelper: uriHelper,
);
expect(status?.successful, false);
expect(status?.statusVerbose, 'user not signed-in');
});
});
}

Expand Down

0 comments on commit 8a23aee

Please sign in to comment.