minor changes to utility classes (#1127)

This commit is contained in:
sergey-signal 2022-10-25 08:48:56 -07:00 committed by GitHub
parent 90490c9c84
commit 5868d9969a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 33 deletions

View File

@ -1,26 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteUtil {
public static byte[] combine(byte[]... elements) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (byte[] element : elements) {
baos.write(element);
}
return baos.toByteArray();
} catch (IOException e) {
throw new AssertionError(e);
}
}
}

View File

@ -5,15 +5,21 @@
package org.whispersystems.textsecuregcm.util;
import org.apache.commons.lang3.StringUtils;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
/**
* Tools for working with chains of IP addresses in forwarding lists in HTTP headers.
*
* @see <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For">X-Forwarded-For - HTTP | MDN</a>
*/
public class ForwardedIpUtil {
public final class ForwardedIpUtil {
private ForwardedIpUtil() {
// utility class
}
/**
* Returns the most recent proxy in a chain described by an {@code X-Forwarded-For} header.
@ -23,11 +29,15 @@ public class ForwardedIpUtil {
* @return the IP address of the most recent proxy in the forwarding chain, or empty if none was found or
* {@code forwardedFor} was null
*/
public static Optional<String> getMostRecentProxy(final String forwardedFor) {
@Nonnull
public static Optional<String> getMostRecentProxy(@Nullable final String forwardedFor) {
return Optional.ofNullable(forwardedFor)
.filter(StringUtils::isNotBlank)
.map(proxies -> proxies.split(","))
.map(proxyArray -> proxyArray[proxyArray.length - 1])
.map(String::trim);
.map(ff -> {
final int idx = forwardedFor.lastIndexOf(',') + 1;
return idx < forwardedFor.length()
? forwardedFor.substring(idx).trim()
: null;
})
.filter(StringUtils::isNotBlank);
}
}

View File

@ -28,6 +28,8 @@ class ForwardedIpUtilTest {
arguments(null, Optional.empty()),
arguments("", Optional.empty()),
arguments(" ", Optional.empty()),
arguments("203.0.113.195,", Optional.empty()),
arguments("203.0.113.195, ", Optional.empty()),
arguments("203.0.113.195", Optional.of("203.0.113.195")),
arguments("203.0.113.195, 70.41.3.18, 150.172.238.178", Optional.of("150.172.238.178"))
);