From 15b74df979436a27631581571fa7fc7b5360bb39 Mon Sep 17 00:00:00 2001 From: Tima Zhum Date: Thu, 13 Feb 2025 22:15:12 +0000 Subject: [PATCH] fix: issue#62 strip auth key Fixing the issue raised in https://github.com/DeepLcom/deepl-java/issues/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. --- .../src/main/java/com/deepl/api/Translator.java | 13 +++++++++---- .../src/test/java/com/deepl/api/GeneralTest.java | 10 ++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/deepl-java/src/main/java/com/deepl/api/Translator.java b/deepl-java/src/main/java/com/deepl/api/Translator.java index bb80a24..b556d65 100644 --- a/deepl-java/src/main/java/com/deepl/api/Translator.java +++ b/deepl-java/src/main/java/com/deepl/api/Translator.java @@ -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 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())); diff --git a/deepl-java/src/test/java/com/deepl/api/GeneralTest.java b/deepl-java/src/test/java/com/deepl/api/GeneralTest.java index 904c8b0..5c897be 100644 --- a/deepl-java/src/test/java/com/deepl/api/GeneralTest.java +++ b/deepl-java/src/test/java/com/deepl/api/GeneralTest.java @@ -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";