From 8d1545db817f48dcd6bfd5db7594fb71a878e0db Mon Sep 17 00:00:00 2001 From: Philipp Bumann Date: Tue, 1 Oct 2024 13:08:01 +0200 Subject: [PATCH] Added error handling if resumption token is not a valid base64 string --- .../services/impl/SimpleResumptionTokenFormat.java | 10 +++++++--- .../impl/SimpleResumptionTokenFormatTest.java | 13 +++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/xoai-common/src/main/java/io/gdcc/xoai/services/impl/SimpleResumptionTokenFormat.java b/xoai-common/src/main/java/io/gdcc/xoai/services/impl/SimpleResumptionTokenFormat.java index a7b3ae23..4129e602 100644 --- a/xoai-common/src/main/java/io/gdcc/xoai/services/impl/SimpleResumptionTokenFormat.java +++ b/xoai-common/src/main/java/io/gdcc/xoai/services/impl/SimpleResumptionTokenFormat.java @@ -124,12 +124,16 @@ public String format(ResumptionToken.Value resumptionToken) { * @param value The Base64 encoded string * @return A decoded String (may be empty) */ - static String base64Decode(String value) { + static String base64Decode(String value) throws BadResumptionTokenException { if (value == null) { return null; } - byte[] decodedValue = Base64.getDecoder().decode(value); - return new String(decodedValue, StandardCharsets.UTF_8); + try { + byte[] decodedValue = Base64.getDecoder().decode(value); + return new String(decodedValue, StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + throw new BadResumptionTokenException("Token has no valid base64 encoding", e); + } } static String base64Encode(String value) { diff --git a/xoai-common/src/test/java/io/gdcc/xoai/services/impl/SimpleResumptionTokenFormatTest.java b/xoai-common/src/test/java/io/gdcc/xoai/services/impl/SimpleResumptionTokenFormatTest.java index a0cb6ab7..e5f9e244 100644 --- a/xoai-common/src/test/java/io/gdcc/xoai/services/impl/SimpleResumptionTokenFormatTest.java +++ b/xoai-common/src/test/java/io/gdcc/xoai/services/impl/SimpleResumptionTokenFormatTest.java @@ -9,6 +9,7 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.stream.Stream; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -73,4 +74,16 @@ void validParse(String token) { String encoded = SimpleResumptionTokenFormat.base64Encode(token); assertDoesNotThrow(() -> format.parse(encoded)); } + + @Test + void validBase64Decoding() { + assertDoesNotThrow(() -> SimpleResumptionTokenFormat.base64Decode("b2Zmc2V0OjoxMDA=")); + } + + @Test + void invalidBase64Decoding() { + assertThrows( + BadResumptionTokenException.class, + () -> SimpleResumptionTokenFormat.base64Decode("b2Zmc2V0OjoMDA=")); + } }