private String getRemoteAddr(String clientAddr, String proxyAddr, boolean trusted) { HttpServletRequest req = mock(HttpServletRequest.class); when(req.getRemoteAddr()).thenReturn("1.2.3.4"); Configuration conf = new Configuration(); if (proxyAddr == null) { when(req.getRemoteAddr()).thenReturn(clientAddr); } else { when(req.getRemoteAddr()).thenReturn(proxyAddr); when(req.getHeader("X-Forwarded-For")).thenReturn(clientAddr); if (trusted) { conf.set(ProxyServers.CONF_HADOOP_PROXYSERVERS, proxyAddr); } } ProxyUsers.refreshSuperUserGroupsConfiguration(conf); return JspHelper.getRemoteAddr(req); }
public static String getRemoteAddr(HttpServletRequest request) { String remoteAddr = request.getRemoteAddr(); String proxyHeader = request.getHeader("X-Forwarded-For"); if (proxyHeader != null && ProxyServers.isProxyServer(remoteAddr)) { final String clientAddr = proxyHeader.split(",")[0].trim(); if (!clientAddr.isEmpty()) { remoteAddr = clientAddr; } } return remoteAddr; }
@Test public void testWebHdfsAuditLogger() throws IOException, URISyntaxException { Configuration conf = new HdfsConfiguration(); conf.set(DFS_NAMENODE_AUDIT_LOGGERS_KEY, DummyAuditLogger.class.getName()); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); GetOpParam.Op op = GetOpParam.Op.GETFILESTATUS; try { cluster.waitClusterUp(); assertTrue(DummyAuditLogger.initialized); URI uri = new URI( "http", NetUtils.getHostPortString(cluster.getNameNode().getHttpAddress()), "/webhdfs/v1/", op.toQueryString(), null); // non-proxy request HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection(); conn.setRequestMethod(op.getType().toString()); conn.connect(); assertEquals(200, conn.getResponseCode()); conn.disconnect(); assertEquals(1, DummyAuditLogger.logCount); assertEquals("127.0.0.1", DummyAuditLogger.remoteAddr); // non-trusted proxied request conn = (HttpURLConnection) uri.toURL().openConnection(); conn.setRequestMethod(op.getType().toString()); conn.setRequestProperty("X-Forwarded-For", "1.1.1.1"); conn.connect(); assertEquals(200, conn.getResponseCode()); conn.disconnect(); assertEquals(2, DummyAuditLogger.logCount); assertEquals("127.0.0.1", DummyAuditLogger.remoteAddr); // trusted proxied request conf.set(ProxyServers.CONF_HADOOP_PROXYSERVERS, "127.0.0.1"); ProxyUsers.refreshSuperUserGroupsConfiguration(conf); conn = (HttpURLConnection) uri.toURL().openConnection(); conn.setRequestMethod(op.getType().toString()); conn.setRequestProperty("X-Forwarded-For", "1.1.1.1"); conn.connect(); assertEquals(200, conn.getResponseCode()); conn.disconnect(); assertEquals(3, DummyAuditLogger.logCount); assertEquals("1.1.1.1", DummyAuditLogger.remoteAddr); } finally { cluster.shutdown(); } }