Skip to content

Commit

Permalink
✅ Improve cookie format check
Browse files Browse the repository at this point in the history
  • Loading branch information
YvanMazy committed May 14, 2024
1 parent e90a39c commit 30810a6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@

package be.darkkraft.transferproxy.api.util;

import static net.kyori.adventure.key.Key.checkNamespace;
import static net.kyori.adventure.key.Key.checkValue;

public final class CookieUtil {

private static final int MAX_COOKIE_SIZE = 5120; // 5 kiB
Expand All @@ -36,9 +39,16 @@ public static void ensureCookieFormat(final String cookieKey) {
if (cookieKey == null) {
throw new IllegalArgumentException("Cookie key must not be null");
}
if (cookieKey.indexOf(':') < 0) {
final int index = cookieKey.indexOf(':');
if (index < 1) {
throw new IllegalArgumentException("Cookie key format must be: namespace:key");
}
if (checkNamespace(cookieKey.substring(0, index)).isPresent()) {
throw new IllegalArgumentException("Invalid characters in cookie namespace: " + cookieKey);
}
if (checkValue(cookieKey.substring(index + 1)).isPresent()) {
throw new IllegalArgumentException("Invalid characters in cookie value: " + cookieKey);
}
}

public static int getMaxCookieSize() { // Maybe that changes in future versions?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,29 @@
package be.darkkraft.transferproxy.api.util;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;

class CookieUtilTest {

@ParameterizedTest
@ValueSource(strings = {"namespace:key", "minecraft:cookie", "minecraft:cookie_part"})
void testValidCookieFormat(final String key) {
assertDoesNotThrow(() -> CookieUtil.ensureCookieFormat(key));
}

@Test
void testCookieFormat() {
void testCookieFormatWithNullValue() {
assertThrows(IllegalArgumentException.class, () -> CookieUtil.ensureCookieFormat(null));
assertThrows(IllegalArgumentException.class, () -> CookieUtil.ensureCookieFormat("key"));
assertDoesNotThrow(() -> CookieUtil.ensureCookieFormat("namespace:key"));
assertDoesNotThrow(() -> CookieUtil.ensureCookieFormat("minecraft:cookie"));
}

@ParameterizedTest
@ValueSource(strings = {"", "key", ":key", "namespace:ke@y", "n@mespace:key"})
void testInvalidCookieFormat(final String key) {
assertThrows(IllegalArgumentException.class, () -> CookieUtil.ensureCookieFormat(key));
}

}

0 comments on commit 30810a6

Please sign in to comment.