Skip to content

Commit 15b74df

Browse files
committed
fix: issue#62 strip auth key
Fixing the issue raised in #62 Problem: auth key with leading / trailing whitespaces is throwing exceptions. For example, assigning the secret via `echo` leaves a trailing `\n`. Solution: strip input auth key as an input sanitization procedure Notice: Java 8 does not support `String.strip()`, while `String.trim()` does not support Unicode whitespaces. We anticipate ASCII only input and utilizing `trim()` for simplicity.
1 parent 87e78b1 commit 15b74df

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

deepl-java/src/main/java/com/deepl/api/Translator.java

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,19 +41,24 @@ public class Translator {
4141
*/
4242
@Deprecated
4343
public Translator(String authKey, TranslatorOptions options) throws IllegalArgumentException {
44-
if (authKey == null || authKey.length() == 0) {
45-
throw new IllegalArgumentException("authKey must be a non-empty string");
44+
if (authKey == null || authKey.isEmpty()) {
45+
throw new IllegalArgumentException("authKey cannot be null or empty");
4646
}
47+
48+
String sanitizedAuthKey = authKey.trim();
49+
4750
String serverUrl =
4851
(options.getServerUrl() != null)
4952
? options.getServerUrl()
50-
: (isFreeAccountAuthKey(authKey) ? DEEPL_SERVER_URL_FREE : DEEPL_SERVER_URL_PRO);
53+
: (isFreeAccountAuthKey(sanitizedAuthKey)
54+
? DEEPL_SERVER_URL_FREE
55+
: DEEPL_SERVER_URL_PRO);
5156

5257
Map<String, String> headers = new HashMap<>();
5358
if (options.getHeaders() != null) {
5459
headers.putAll(options.getHeaders());
5560
}
56-
headers.putIfAbsent("Authorization", "DeepL-Auth-Key " + authKey);
61+
headers.putIfAbsent("Authorization", "DeepL-Auth-Key " + sanitizedAuthKey);
5762
headers.putIfAbsent(
5863
"User-Agent",
5964
constructUserAgentString(options.getSendPlatformInfo(), options.getAppInfo()));

deepl-java/src/test/java/com/deepl/api/GeneralTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,16 @@ void testEmptyAuthKey() {
2828
});
2929
}
3030

31+
@Test
32+
void testNullAuthKey() {
33+
IllegalArgumentException thrown =
34+
Assertions.assertThrows(
35+
IllegalArgumentException.class,
36+
() -> {
37+
Translator translator = new Translator(null);
38+
});
39+
}
40+
3141
@Test
3242
void testInvalidAuthKey() {
3343
String authKey = "invalid";

0 commit comments

Comments
 (0)