Skip to content

Commit

Permalink
refactor cleanSignedUrl
Browse files Browse the repository at this point in the history
  • Loading branch information
mmorgantaylor committed Sep 9, 2024
1 parent 08611f8 commit ef779fd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
Expand Down Expand Up @@ -122,23 +122,24 @@ public URL generateGetObjectSignedUrl(String projectId, String bucketName, Strin
*/
public static String cleanSignedUrl(URL signedUrl) {
String signedUrlString = signedUrl.toString();
String cleanUrl = signedUrlString;
List<String> signedUrlElements = List.of(signedUrlString.split("\\?")[1].split("&"));

String signatureDelimiter = "X-Goog-Signature=";

String cleanUrl = signedUrlString;
if (signedUrlString.contains(signatureDelimiter)) {
String cleanUrlUpToSignature =
signedUrlString.split(signatureDelimiter)[0] + signatureDelimiter + "REDACTED";
String[] cleanUrlElementsAfterSignature =
signedUrlString.split(signatureDelimiter)[1].split("&");
if (cleanUrlElementsAfterSignature.length == 1) {
cleanUrl = cleanUrlUpToSignature;
} else {
String cleanUrlAfterSignature =
String.join(
"&",
Arrays.copyOfRange(
cleanUrlElementsAfterSignature, 1, cleanUrlElementsAfterSignature.length));
cleanUrl = "%s&%s".formatted(cleanUrlUpToSignature, cleanUrlAfterSignature);
}
// if element contains signatureDelimiter, redact the value, otherwise keep the full element
List<String> cleanUrlElements =
signedUrlElements.stream()
.map(
signedUrlElement -> {
if (signedUrlElement.contains(signatureDelimiter)) {
return signatureDelimiter + "REDACTED";
}
return signedUrlElement;
})
.toList();
cleanUrl = signedUrlString.split("\\?")[0] + "?" + String.join("&", cleanUrlElements);
}
return cleanUrl;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ void cleanSignedUrl() throws MalformedURLException {
// signed URL with no X-Goog-Signature should not throw an exception
URL fakeURLNoSignature =
new URL(
"https://storage.googleapis.com/fc-secure-6970c3a9-dc92-436d-af3d-917bcb4cf05a/user-input-files/ffaffa12-5717-4562-b3fc-2c963f66afa6/TEST.vcf.gz");
"https://storage.googleapis.com/fc-secure-6970c3a9-dc92-436d-af3d-917bcb4cf05a/user-input-files/ffaffa12-5717-4562-b3fc-2c963f66afa6/TEST.vcf.gz?X-Goog-Date=20240823T170006Z&X-Goog-Expires=900");
assertEquals(fakeURLNoSignature.toString(), GcsService.cleanSignedUrl(fakeURLNoSignature));

// signed URL with X-Goog-Signature in the middle
Expand Down

0 comments on commit ef779fd

Please sign in to comment.