refactor(core): share the token decode in Pagination (#6431)

tokenStartsWith and decodeCursor each decoded the base64url token and
caught the IllegalArgumentException of an unreadable one. Both now use a
private decodeToken that returns the decoded cursor, or null for an absent
or unreadable token. Behaviour is unchanged; PaginationTest now covers
tokenStartsWith directly.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-10-24 13:36:01 -04:00
1 parent e1796b33b1
commit 8ef9e1ddbf
2 files changed
+36 -15

No files matched your search

@@ -117,14 +117,8 @@ public final class Pagination {
* need to tell a token they issued under another scope from one that is not theirs at all.
*/
public static boolean tokenStartsWith(String token, String prefix) {
if (token == null || token.isEmpty()) {
return false;
}
try {
return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8).startsWith(prefix);
} catch (IllegalArgumentException e) {
return false;
}
String decoded = decodeToken(token);
return decoded != null && decoded.startsWith(prefix);
}
private static String encodeToken(String cursor) {
@@ -136,15 +130,21 @@ public final class Pagination {
if (token == null || token.isEmpty()) {
return null;
}
String decoded;
try {
decoded = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
throw invalidToken.apply(token);
}
if (!decoded.startsWith(prefix)) {
String decoded = decodeToken(token);
if (decoded == null || !decoded.startsWith(prefix)) {
throw invalidToken.apply(token);
}
return decoded.substring(prefix.length());
}
private static String decodeToken(String token) {
if (token == null || token.isEmpty()) {
return null;
}
try {
return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
return null;
}
}
}