Skip to content

Commit 931c717

Browse files
fix(bigquerystorage): pick the base64 alphabet up front instead of by fallback
Falling back through a caught IllegalArgumentException put an exception on the happy path for every record when a producer uses the URL-safe alphabet. A value containing - or _ is never valid standard base64, so the alphabet can be chosen before decoding. The original exception is now kept as the cause.
1 parent c4c78b9 commit 931c717

1 file changed

Lines changed: 12 additions & 11 deletions

File tree

  • java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1

java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/JsonToProtoMessage.java

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,23 +1122,24 @@ private static void throwWrongFieldType(
11221122
/**
11231123
* Decodes a base64 string into bytes, the encoding protobuf's canonical JSON mapping defines for
11241124
* the {@code bytes} type. Standard and URL-safe alphabets are both accepted, with or without
1125-
* padding, as that mapping requires; the two alphabets are mutually exclusive on {@code +/}
1126-
* versus {@code -_}, so the fallback is what makes both work.
1125+
* padding, as that mapping requires. The two differ only in {@code +/} versus {@code -_}, so the
1126+
* alphabet is picked by looking for the URL-safe characters rather than by decoding twice, which
1127+
* would make an exception part of the happy path for every URL-safe record.
11271128
*
1128-
* @throws IllegalArgumentException if the value decodes under neither alphabet
1129+
* @throws IllegalArgumentException if the value is not valid base64
11291130
*/
11301131
private static byte[] parseBase64(String currentScope, String value) {
11311132
try {
1132-
return Base64.getDecoder().decode(value);
1133-
} catch (IllegalArgumentException standardAlphabetFailed) {
1134-
try {
1133+
if (value.indexOf('-') >= 0 || value.indexOf('_') >= 0) {
11351134
return Base64.getUrlDecoder().decode(value);
1136-
} catch (IllegalArgumentException urlSafeAlphabetFailed) {
1137-
throw new IllegalArgumentException(
1138-
"Error: "
1139-
+ currentScope
1140-
+ " could not be converted to byte[]: not a valid base64 string.");
11411135
}
1136+
return Base64.getDecoder().decode(value);
1137+
} catch (IllegalArgumentException e) {
1138+
throw new IllegalArgumentException(
1139+
"Error: "
1140+
+ currentScope
1141+
+ " could not be converted to byte[]: not a valid base64 string.",
1142+
e);
11421143
}
11431144
}
11441145

0 commit comments

Comments
 (0)