Introduce auth.httpTrustedProxyNetworks for securing HTTP auth

When using auth=HTTP or auth=HTTP_LDAP, Gerrit relies on receiving the
incoming username from an HTTP header. When misusing this configuration
with a remote proxy and having Gerrit listening to an external interface
over plain HTTP without firewalls, the security of the incoming username
is subject to HTTP header spoofing.

Highlight the risk in the documentation and also add a mitigation of the
problem with a new auth.httpTrustedProxyNetworks that would restrict the
fetching of the username from HTTP to a subset of CIDRs.

The solution is similar to the mitigation adopted in other projects with
a similar vulnerability.

The parsing of the auth.httpTrustedProxyNetworks is expensive because it
involves the creation of a SubnetUtils object and the string-based
parsing of CIDRs. As a mitigation of the computational costs, parse and
store the subnets in the RemoteUserUtil during the singleton
instantiation, so that incoming HTTP calls can reuse the SubnetUtils
objects and reduce the runtime memory and CPU footprint.

Also, with regard to the subnet matching, differentiate between
individual IP matching (CIDRs ending with /32) and full networking
address matching with SubnetUtils. The individual IP matching is a
simple O(1) independently of the number of entries; however, the full
CIDRs matching will loop through all the networks and check the netmasks
against the IP, with an O(N) complexity.

The detection of the proxy-IP is quite complex because it also involves
the wrapping of the X-Forwarded* headers management by Jetty, which
overwrites the socket remote IP address with the original client IP
forwarded by the proxy in between. It is necessary to wrap the concept
of the extraction of the address into a generic interface, which can be
overridden by actual implementations, with a default fallback to the
standard servlet mechanism.

The auth path in RemoteUserUtil needs exactly one piece of information
that the servlet API does not give it directly: the pre-X-Forwarded-*
TCP peer address.

- RemoteUserUtil declares a public PROXY_REMOTE_ADDRESS_ATTR
  constant. Its javadoc documents the contract: any HTTP layer that
  wants its requests evaluated against auth.httpTrustedProxyNetworks
  sets this attribute to the pre-rewrite peer address. If unset,
  RemoteUserUtil falls back to HttpServletRequest.getRemoteAddr().

- JettyServer writes the attribute (one line) before delegating to
  the parent ForwardedRequestCustomizer, which is where Jetty rewrites
  getRemoteAddr() with the X-Forwarded-For value.

Beyond the smaller surface, this design generalizes to non-Jetty HTTP
layers without any new class hierarchy. A Tomcat valve, an embedded
Netty pipeline stage, or a plain servlet filter installed before the
auth filter can opt into the trusted-proxy check by setting the same
attribute on the request. No subclass of ProxyAddressProvider, no module
override, no Guice rebinding -- the contract is the constant plus its
javadoc.

In the case of JettyServer, we need to extend the
ForwardedRequestCustomizer to remember what the original IP was before
the wrapping and store into a request attribute. The runtime filter then
accesses the attribute transparently and, if present, uses the proxy IP
instead of the wrapped client IP. This also protects from malicious
attackers trying to fake their client IP by spoofing the X-Forwarded*
header values.

Co-Author: David Ostrovsky <david.ostrovsky@gmail.com>
Bug: Issue 520369774
Release-Notes: Introduce auth.httpTrustedProxyNetworks for mitigating the vulnerability of auth=HTTP or auth=HTTP_LDAP on external IPs
Change-Id: If9809ff092520aa467fa108b4179b7b75afe0a85
diff --git a/Documentation/config-gerrit.txt b/Documentation/config-gerrit.txt
index efd083e..911eb56 100644
--- a/Documentation/config-gerrit.txt
+++ b/Documentation/config-gerrit.txt
@@ -427,6 +427,26 @@
 HTTP header to trust the username from, or unset to select HTTP basic
 authentication.  Only used if `auth.type` is set to `HTTP`.
 
+[[auth.httpTrustedProxyNetworks]]auth.httpTrustedProxyNetworks::
++
+List of IPv4 networks CIDRs (e.g., `192.168.0.0/16`) that are trusted proxies for receiving
+HTTP header authentication.  Specify multiple networks by adding multiple entries.
+It applies only when `auth.type` is set to `HTTP` or `HTTP_LDAP`. The trusted-proxy
+remote address must be IPv4; if Gerrit is reached over IPv6, header-based
+authentication is rejected.
++
+[NOTE]
+====
+Accepting a trusted authentication HTTP header involves a leap of faith in the security
+of the incoming HTTP traffic. By default, the only secure way to ensure that all the
+traffic is coming from a trusted authentication proxy is via firewall rules or using
+a local proxy on the loopback interface. When using a remote proxy, the security of
+the connection between the proxy and Gerrit is in doubt, and this can be mitigated by
+the use of `auth.httpTrustedProxyNetworks`.
+====
++
+Default: accept any incoming IPs.
+
 [[auth.httpDisplaynameHeader]]auth.httpDisplaynameHeader::
 +
 HTTP header to retrieve the user's display name from.  Only used if `auth.type`
diff --git a/java/com/google/gerrit/httpd/BUILD b/java/com/google/gerrit/httpd/BUILD
index 0142031..18334aa 100644
--- a/java/com/google/gerrit/httpd/BUILD
+++ b/java/com/google/gerrit/httpd/BUILD
@@ -38,6 +38,7 @@
         "//lib/auto:auto-value",
         "//lib/auto:auto-value-annotations",
         "//lib/commons:lang3",
+        "//lib/commons:net",
         "//lib/errorprone:annotations",
         "//lib/flogger:api",
         "//lib/guice",
diff --git a/java/com/google/gerrit/httpd/RemoteUserUtil.java b/java/com/google/gerrit/httpd/RemoteUserUtil.java
index 7294736..8856f91 100644
--- a/java/com/google/gerrit/httpd/RemoteUserUtil.java
+++ b/java/com/google/gerrit/httpd/RemoteUserUtil.java
@@ -18,13 +18,71 @@
 import static com.google.common.net.HttpHeaders.AUTHORIZATION;
 import static java.nio.charset.StandardCharsets.UTF_8;
 
+import com.google.common.base.MoreObjects;
+import com.google.common.flogger.FluentLogger;
 import com.google.common.io.BaseEncoding;
 import com.google.gerrit.common.Nullable;
+import com.google.gerrit.server.config.AuthConfig;
+import com.google.inject.ProvisionException;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
 import javax.inject.Singleton;
 import javax.servlet.http.HttpServletRequest;
+import org.apache.commons.net.util.SubnetUtils;
 
 @Singleton
 public class RemoteUserUtil {
+  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+
+  /**
+   * Request attribute carrying the TCP-peer address before any X-Forwarded-For rewrite.
+   *
+   * <p>HTTP layers that want their requests evaluated against {@code auth.httpTrustedProxyNetworks}
+   * must set this attribute on each request. If the attribute is unset, {@link
+   * HttpServletRequest#getRemoteAddr()} is used as the peer address.
+   *
+   * <p>Gerrit's default Jetty container wires this automatically (see {@code
+   * JettyServer.ForwardedRequestCustomizer}). Other servlet containers (Tomcat, embedded netty,
+   * etc.) can opt in by installing a {@code Filter} or equivalent that runs <em>before</em> any
+   * X-Forwarded-For rewrite (e.g., Tomcat's {@code RemoteIpValve}) and sets this attribute to
+   * {@code request.getRemoteAddr()}.
+   */
+  public static final String PROXY_REMOTE_ADDRESS_ATTR =
+      "com.google.gerrit.httpd.proxyRemoteAddress";
+
+  private final Set<SubnetUtils.SubnetInfo> trustedProxySubnets;
+  private final Set<String> trustedProxyNetworks;
+
+  @Inject
+  RemoteUserUtil(AuthConfig authConfig) {
+    // The full list of `trustedProxyNetworks` is also kept as Set<String>
+    // for allowing the single-IP matching (networks ending with '/32') fast
+    // lookup whilst the full network matching evaluation is performed
+    // through the trustedProxySubnets loop.
+    trustedProxyNetworks = authConfig.getTrustedProxyNetworks();
+
+    try {
+      trustedProxySubnets =
+          trustedProxyNetworks.stream()
+              // Filter out single IPs because they are not matched by
+              // subnetwork matching but rather direct containment in
+              // trustedProxyNetworks
+              .filter(Predicate.not(RemoteUserUtil::isSingleIp))
+              .map(SubnetUtils::new)
+              .map(SubnetUtils::getInfo)
+              .collect(Collectors.toSet());
+    } catch (IllegalArgumentException e) {
+      throw new ProvisionException("Invalid auth trusted proxy definition: " + e.getMessage(), e);
+    }
+  }
+
+  private static boolean isSingleIp(String network) {
+    return network.endsWith("/32");
+  }
+
   /**
    * Tries to get username from a request with following strategies:
    *
@@ -40,7 +98,9 @@
    */
   @Nullable
   public String getRemoteUser(HttpServletRequest req, String loginHeader) {
-    if (AUTHORIZATION.equals(loginHeader)) {
+    boolean isAuthorizationHeader = AUTHORIZATION.equals(loginHeader);
+
+    if (isAuthorizationHeader) {
       String user = emptyToNull(req.getRemoteUser());
       if (user != null) {
         // The container performed the authentication, and has the user
@@ -48,16 +108,55 @@
         // configured to honor HTTP authentication.
         return user;
       }
-
-      // If the container didn't do the authentication we might
-      // have done it in the front-end web server. Try to split
-      // the identity out of the Authorization header and honor it.
-      String auth = req.getHeader(AUTHORIZATION);
-      return extractUsername(auth);
     }
-    // Nonstandard HTTP header. We have been told to trust this
-    // header blindly as-is.
-    return emptyToNull(req.getHeader(loginHeader));
+
+    if (!isRequestFromTrustedProxyNetworks(req)) {
+      return null;
+    }
+
+    String auth = req.getHeader(loginHeader);
+    return isAuthorizationHeader
+        ?
+        // If the container didn't do the authentication we might
+        // have done it in the front-end web server. Try to split
+        // the identity out of the Authorization header and honor it.
+        extractUsername(auth)
+        :
+        // Nonstandard HTTP header. We have been told to trust this
+        // header blindly as-is.
+        emptyToNull(auth);
+  }
+
+  private boolean isRequestFromTrustedProxyNetworks(HttpServletRequest req) {
+    if (trustedProxyNetworks.isEmpty()) {
+      return true;
+    }
+
+    String remoteAddress = getRemoteAddress(req);
+    if (isIpv6Address(remoteAddress)) {
+      logger.atWarning().atMostEvery(1, TimeUnit.MINUTES).log(
+          "IPv6 remote address: %s - trusted proxy enforcement supports only IPv4, HTTP header"
+              + " rejected",
+          remoteAddress);
+      return false;
+    }
+
+    if (trustedProxyNetworks.contains(remoteAddress + "/32")) {
+      return true;
+    }
+
+    if (trustedProxySubnets.stream().anyMatch(subnet -> subnet.isInRange(remoteAddress))) {
+      return true;
+    }
+
+    logger.atWarning().atMostEvery(1, TimeUnit.MINUTES).log(
+        "Untrusted remote address: %s - authentication via HTTP header rejected", remoteAddress);
+    return false;
+  }
+
+  private static String getRemoteAddress(HttpServletRequest req) {
+    return MoreObjects.firstNonNull(
+        (String) req.getAttribute(PROXY_REMOTE_ADDRESS_ATTR), req.getRemoteAddr());
   }
 
   /**
@@ -92,4 +191,8 @@
       return null;
     }
   }
+
+  private static boolean isIpv6Address(String ipAddress) {
+    return ipAddress.contains(":");
+  }
 }
diff --git a/java/com/google/gerrit/pgm/http/jetty/JettyServer.java b/java/com/google/gerrit/pgm/http/jetty/JettyServer.java
index 5a00e99..bea4fb4 100644
--- a/java/com/google/gerrit/pgm/http/jetty/JettyServer.java
+++ b/java/com/google/gerrit/pgm/http/jetty/JettyServer.java
@@ -23,6 +23,7 @@
 import com.google.common.base.Strings;
 import com.google.gerrit.extensions.client.AuthType;
 import com.google.gerrit.extensions.events.LifecycleListener;
+import com.google.gerrit.httpd.RemoteUserUtil;
 import com.google.gerrit.pgm.http.jetty.HttpLog.HttpLogFactory;
 import com.google.gerrit.server.config.GerritServerConfig;
 import com.google.gerrit.server.config.SitePaths;
@@ -58,6 +59,7 @@
 import org.eclipse.jetty.server.Handler;
 import org.eclipse.jetty.server.HttpConfiguration;
 import org.eclipse.jetty.server.HttpConnectionFactory;
+import org.eclipse.jetty.server.Request;
 import org.eclipse.jetty.server.SecureRequestCustomizer;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.ServerConnector;
@@ -79,6 +81,34 @@
 
 @Singleton
 public class JettyServer {
+
+  private static final ForwardedRequestCustomizer FORWARDED_REQUEST_CUSTOMIZER =
+      new ForwardedRequestCustomizer() {
+        @Override
+        public void customize(Connector connector, HttpConfiguration config, Request request) {
+          /*
+           * The default behavior of ForwardedRequestCustomizer is to overwrite the remote address
+           * with the value of the X-Forwarded-For header, if present.
+           * However, it does not "remember" the original remote address and therefore would
+           * prevent any validation against it.
+           *
+           * ForwardedRequestCustomizer's original code fragment:
+           * <code>
+           * if (forwarded.hasFor())
+           * {
+           *     int forPort = forwarded._for._port > 0 ? forwarded._for._port : request.getRemotePort();
+           *     request.setRemoteAddr(InetSocketAddress.createUnresolved(forwarded._for._host, forPort));
+           * }
+           * </code>
+           *
+           * What we want to achieve here is to remember what it was the original proxy address before
+           * calling super.customize() and give the possibility to fetch it later down the chain.
+           */
+          request.setAttribute(RemoteUserUtil.PROXY_REMOTE_ADDRESS_ATTR, request.getRemoteAddr());
+          super.customize(connector, config, request);
+        }
+      };
+
   static class Lifecycle implements LifecycleListener {
     private final JettyServer server;
     private final Config cfg;
@@ -365,12 +395,12 @@
 
       } else if ("proxy-http".equals(u.getScheme())) {
         defaultPort = 8080;
-        config.addCustomizer(new ForwardedRequestCustomizer());
+        config.addCustomizer(FORWARDED_REQUEST_CUSTOMIZER);
         c = newServerConnector(server, acceptors, config);
 
       } else if ("proxy-https".equals(u.getScheme())) {
         defaultPort = 8080;
-        config.addCustomizer(new ForwardedRequestCustomizer());
+        config.addCustomizer(FORWARDED_REQUEST_CUSTOMIZER);
         config.addCustomizer(
             (connector, channelConfig, request) -> {
               request.setScheme(HttpScheme.HTTPS.asString());
diff --git a/java/com/google/gerrit/server/config/AuthConfig.java b/java/com/google/gerrit/server/config/AuthConfig.java
index 1e7fa6a..996ec71 100644
--- a/java/com/google/gerrit/server/config/AuthConfig.java
+++ b/java/com/google/gerrit/server/config/AuthConfig.java
@@ -18,6 +18,7 @@
 import static com.google.gerrit.server.account.externalids.ExternalId.SCHEME_USERNAME;
 import static com.google.gerrit.server.account.externalids.ExternalId.SCHEME_UUID;
 
+import com.google.common.collect.ImmutableSet;
 import com.google.gerrit.extensions.client.AuthType;
 import com.google.gerrit.extensions.client.GitBasicAuthPolicy;
 import com.google.gerrit.server.account.externalids.ExternalId;
@@ -31,6 +32,7 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
+import java.util.Set;
 import java.util.concurrent.TimeUnit;
 import org.eclipse.jgit.lib.Config;
 
@@ -39,6 +41,7 @@
 public class AuthConfig {
   private final AuthType authType;
   private final String httpHeader;
+  private final ImmutableSet<String> trustedProxyNetworks;
   private final String httpDisplaynameHeader;
   private final String httpEmailHeader;
   private final String httpExternalIdHeader;
@@ -74,6 +77,8 @@
   AuthConfig(@GerritServerConfig Config cfg) throws XsrfException {
     authType = toType(cfg);
     httpHeader = cfg.getString("auth", null, "httpheader");
+    trustedProxyNetworks =
+        ImmutableSet.copyOf(cfg.getStringList("auth", null, "httpTrustedProxyNetworks"));
     httpDisplaynameHeader = cfg.getString("auth", null, "httpdisplaynameheader");
     httpEmailHeader = cfg.getString("auth", null, "httpemailheader");
     httpExternalIdHeader = cfg.getString("auth", null, "httpexternalidheader");
@@ -364,4 +369,8 @@
   public boolean isAllowRegisterNewEmail() {
     return allowRegisterNewEmail;
   }
+
+  public Set<String> getTrustedProxyNetworks() {
+    return trustedProxyNetworks;
+  }
 }
diff --git a/javatests/com/google/gerrit/httpd/RemoteUserUtilTest.java b/javatests/com/google/gerrit/httpd/RemoteUserUtilTest.java
index f012ee3..ab464e8 100644
--- a/javatests/com/google/gerrit/httpd/RemoteUserUtilTest.java
+++ b/javatests/com/google/gerrit/httpd/RemoteUserUtilTest.java
@@ -15,11 +15,45 @@
 package com.google.gerrit.httpd;
 
 import static com.google.common.truth.Truth.assertThat;
+import static com.google.gerrit.httpd.RemoteUserUtil.PROXY_REMOTE_ADDRESS_ATTR;
 import static com.google.gerrit.httpd.RemoteUserUtil.extractUsername;
+import static com.google.gerrit.testing.GerritJUnit.assertThrows;
+import static org.mockito.Mockito.when;
 
+import com.google.common.base.Suppliers;
+import com.google.common.net.HttpHeaders;
+import com.google.gerrit.server.config.AuthConfig;
+import com.google.gerrit.util.http.testutil.FakeHttpServletRequest;
+import com.google.inject.ProvisionException;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
 
+@RunWith(MockitoJUnitRunner.class)
 public class RemoteUserUtilTest {
+  private static final String CUSTOM_LOGIN_HEADER = "MY_HEADER";
+  private static final String EXPECTED_USER = "user";
+  private static final String BASIC_AUTHENTICATION_USER_HEADER =
+      "Basic "
+          + Base64.getEncoder()
+              .encodeToString((EXPECTED_USER + ":pass").getBytes(StandardCharsets.UTF_8));
+
+  private Supplier<RemoteUserUtil> remoteUserUtil;
+
+  @Mock AuthConfig authConfigMock;
+
+  @Before
+  public void setup() {
+    when(authConfigMock.getTrustedProxyNetworks()).thenReturn(Set.of());
+    remoteUserUtil = Suppliers.memoize(() -> new RemoteUserUtil(authConfigMock));
+  }
+
   @Test
   public void testExtractUsername() {
     assertThat(extractUsername(null)).isNull();
@@ -27,4 +61,165 @@
     assertThat(extractUsername("Basic dXNlcjpwYXNzd29yZA==")).isEqualTo("user");
     assertThat(extractUsername("Digest username=\"user\", realm=\"test\"")).isEqualTo("user");
   }
+
+  @Test
+  public void testExtractUserFromRequestWithCustomHeaderAllowedByDefault() throws Exception {
+    FakeHttpServletRequest fakeRequest = new FakeHttpServletRequest();
+    fakeRequest.addHeader(CUSTOM_LOGIN_HEADER, EXPECTED_USER);
+    assertThat(remoteUserUtil.get().getRemoteUser(fakeRequest, CUSTOM_LOGIN_HEADER))
+        .isEqualTo(EXPECTED_USER);
+  }
+
+  @Test
+  public void testExtractUserFromRequestWithAuthenticationHeaderAllowedByDefault()
+      throws Exception {
+    FakeHttpServletRequest fakeRequest = new FakeHttpServletRequest();
+    fakeRequest.addHeader(HttpHeaders.AUTHORIZATION, BASIC_AUTHENTICATION_USER_HEADER);
+    assertThat(remoteUserUtil.get().getRemoteUser(fakeRequest, HttpHeaders.AUTHORIZATION))
+        .isEqualTo(EXPECTED_USER);
+  }
+
+  @Test
+  public void testExtractUserFromRequestWithCustomHeaderAllowedUsingProxyExactIPv4Matching()
+      throws Exception {
+    String clientIP = "192.168.1.2";
+    String proxyId = "80.78.1.3";
+    when(authConfigMock.getTrustedProxyNetworks()).thenReturn(Set.of(proxyId + "/32"));
+    FakeHttpServletRequest fakeRequest = newFakeHttpRequest(clientIP, EXPECTED_USER);
+    fakeRequest.setAttribute(PROXY_REMOTE_ADDRESS_ATTR, proxyId);
+    assertThat(remoteUserUtil.get().getRemoteUser(fakeRequest, CUSTOM_LOGIN_HEADER))
+        .isEqualTo(EXPECTED_USER);
+  }
+
+  @Test
+  public void testExtractUserFromRequestWithCustomHeaderAllowedWithExactIPv4Matching()
+      throws Exception {
+    String remoteIp = "192.168.1.2";
+    when(authConfigMock.getTrustedProxyNetworks()).thenReturn(Set.of(remoteIp + "/32"));
+    assertThat(
+            remoteUserUtil
+                .get()
+                .getRemoteUser(newFakeHttpRequest(remoteIp, EXPECTED_USER), CUSTOM_LOGIN_HEADER))
+        .isEqualTo(EXPECTED_USER);
+  }
+
+  @Test
+  public void testExtractUserFromRequestWithAuthenticationHeaderAllowedWithExactIPv4Matching()
+      throws Exception {
+    String remoteIp = "192.168.1.2";
+    when(authConfigMock.getTrustedProxyNetworks()).thenReturn(Set.of(remoteIp + "/32"));
+    assertThat(
+            remoteUserUtil
+                .get()
+                .getRemoteUser(
+                    newFakeAuthHttpRequest(remoteIp, BASIC_AUTHENTICATION_USER_HEADER),
+                    HttpHeaders.AUTHORIZATION))
+        .isEqualTo(EXPECTED_USER);
+  }
+
+  @Test
+  public void testExtractUserFromRequestWithCustomHeaderAllowedWithExactIPv4InAcceptedRange()
+      throws Exception {
+    when(authConfigMock.getTrustedProxyNetworks())
+        .thenReturn(Set.of("10.16.0.0/16", "192.168.1.0/24", "8.8.8.8/32"));
+    assertThat(
+            remoteUserUtil
+                .get()
+                .getRemoteUser(newFakeHttpRequest("10.16.5.1", EXPECTED_USER), CUSTOM_LOGIN_HEADER))
+        .isEqualTo(EXPECTED_USER);
+  }
+
+  @Test
+  public void
+      testExtractUserFromRequestWithAuthenticationHeaderAllowedWithExactIPv4InAcceptedRange()
+          throws Exception {
+    when(authConfigMock.getTrustedProxyNetworks())
+        .thenReturn(Set.of("10.16.0.0/16", "192.168.1.0/24", "8.8.8.8/32"));
+    assertThat(
+            remoteUserUtil
+                .get()
+                .getRemoteUser(
+                    newFakeAuthHttpRequest("10.16.5.1", BASIC_AUTHENTICATION_USER_HEADER),
+                    HttpHeaders.AUTHORIZATION))
+        .isEqualTo(EXPECTED_USER);
+  }
+
+  @Test
+  public void testExtractUserFromRequestWithCustomHeaderRejectedWithNonMatchingExactIPv4()
+      throws Exception {
+    when(authConfigMock.getTrustedProxyNetworks()).thenReturn(Set.of("2.2.2.2/32"));
+    assertThat(
+            remoteUserUtil
+                .get()
+                .getRemoteUser(newFakeHttpRequest("1.1.1.1", EXPECTED_USER), CUSTOM_LOGIN_HEADER))
+        .isNull();
+  }
+
+  @Test
+  public void testExtractUserFromRequestWithAuthenticationHeaderRejectedWithNonMatchingExactIPv4()
+      throws Exception {
+    when(authConfigMock.getTrustedProxyNetworks()).thenReturn(Set.of("2.2.2.2/32"));
+    assertThat(
+            remoteUserUtil
+                .get()
+                .getRemoteUser(
+                    newFakeAuthHttpRequest("1.1.1.1", BASIC_AUTHENTICATION_USER_HEADER),
+                    HttpHeaders.AUTHORIZATION))
+        .isNull();
+  }
+
+  @Test
+  public void testExtractUserFromRequestRejectedWithIPv6() throws Exception {
+    when(authConfigMock.getTrustedProxyNetworks()).thenReturn(Set.of("255.255.255.255/32"));
+    assertThat(
+            remoteUserUtil
+                .get()
+                .getRemoteUser(
+                    newFakeHttpRequest("2001:0db8:85a3:0000:0000:8a2e:0370:7334", "user"),
+                    CUSTOM_LOGIN_HEADER))
+        .isNull();
+  }
+
+  @Test
+  public void testFailWhenUsingAnInvalidProxyNetworkCIDR() throws Exception {
+    when(authConfigMock.getTrustedProxyNetworks()).thenReturn(Set.of("invalid-network"));
+    assertThrows(ProvisionException.class, () -> remoteUserUtil.get());
+  }
+
+  @Test
+  public void testFailWhenUsingSingleIPAsProxyNetworkCIDR() throws Exception {
+    when(authConfigMock.getTrustedProxyNetworks()).thenReturn(Set.of("192.168.0.1"));
+    assertThrows(ProvisionException.class, () -> remoteUserUtil.get());
+  }
+
+  @Test
+  public void testFailWhenUsingIPv6AsProxyNetworkCIDR() throws Exception {
+    when(authConfigMock.getTrustedProxyNetworks()).thenReturn(Set.of("2000::/3"));
+    assertThrows(ProvisionException.class, () -> remoteUserUtil.get());
+  }
+
+  private static FakeHttpServletRequest newFakeHttpRequest(String remoteIp, String expectedUser) {
+    FakeHttpServletRequest fakeRequest =
+        new FakeHttpServletRequest() {
+          @Override
+          public String getRemoteAddr() {
+            return remoteIp;
+          }
+        };
+    fakeRequest.addHeader(CUSTOM_LOGIN_HEADER, expectedUser);
+    return fakeRequest;
+  }
+
+  private static FakeHttpServletRequest newFakeAuthHttpRequest(
+      String remoteIp, String basicAuthHeader) {
+    FakeHttpServletRequest fakeRequest =
+        new FakeHttpServletRequest() {
+          @Override
+          public String getRemoteAddr() {
+            return remoteIp;
+          }
+        };
+    fakeRequest.addHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader);
+    return fakeRequest;
+  }
 }