Skip to content

Commit

Permalink
fix: issue#62 strip auth key
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
timazhum committed Feb 19, 2025
1 parent 87e78b1 commit 15b74df
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
13 changes: 9 additions & 4 deletions deepl-java/src/main/java/com/deepl/api/Translator.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,24 @@ public class Translator {
*/
@Deprecated
public Translator(String authKey, TranslatorOptions options) throws IllegalArgumentException {
if (authKey == null || authKey.length() == 0) {
throw new IllegalArgumentException("authKey must be a non-empty string");
if (authKey == null || authKey.isEmpty()) {
throw new IllegalArgumentException("authKey cannot be null or empty");
}

String sanitizedAuthKey = authKey.trim();

String serverUrl =
(options.getServerUrl() != null)
? options.getServerUrl()
: (isFreeAccountAuthKey(authKey) ? DEEPL_SERVER_URL_FREE : DEEPL_SERVER_URL_PRO);
: (isFreeAccountAuthKey(sanitizedAuthKey)
? DEEPL_SERVER_URL_FREE
: DEEPL_SERVER_URL_PRO);

Map<String, String> headers = new HashMap<>();
if (options.getHeaders() != null) {
headers.putAll(options.getHeaders());
}
headers.putIfAbsent("Authorization", "DeepL-Auth-Key " + authKey);
headers.putIfAbsent("Authorization", "DeepL-Auth-Key " + sanitizedAuthKey);
headers.putIfAbsent(
"User-Agent",
constructUserAgentString(options.getSendPlatformInfo(), options.getAppInfo()));
Expand Down
10 changes: 10 additions & 0 deletions deepl-java/src/test/java/com/deepl/api/GeneralTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ void testEmptyAuthKey() {
});
}

@Test
void testNullAuthKey() {
IllegalArgumentException thrown =
Assertions.assertThrows(
IllegalArgumentException.class,
() -> {
Translator translator = new Translator(null);
});
}

@Test
void testInvalidAuthKey() {
String authKey = "invalid";
Expand Down

0 comments on commit 15b74df

Please sign in to comment.