public virtual void TestDisallowedMethod() { // Setup the configuration settings of the server IDictionary <string, string> conf = new Dictionary <string, string>(); conf[CrossOriginFilter.AllowedOrigins] = "example.com"; FilterConfig filterConfig = new TestCrossOriginFilter.FilterConfigTest(conf); // Origin is not specified for same origin requests HttpServletRequest mockReq = Org.Mockito.Mockito.Mock <HttpServletRequest>(); Org.Mockito.Mockito.When(mockReq.GetHeader(CrossOriginFilter.Origin)).ThenReturn( "example.com"); Org.Mockito.Mockito.When(mockReq.GetHeader(CrossOriginFilter.AccessControlRequestMethod )).ThenReturn("DISALLOWED_METHOD"); // Objects to verify interactions based on request HttpServletResponse mockRes = Org.Mockito.Mockito.Mock <HttpServletResponse>(); FilterChain mockChain = Org.Mockito.Mockito.Mock <FilterChain>(); // Object under test CrossOriginFilter filter = new CrossOriginFilter(); filter.Init(filterConfig); filter.DoFilter(mockReq, mockRes, mockChain); Org.Mockito.Mockito.VerifyZeroInteractions(mockRes); Org.Mockito.Mockito.Verify(mockChain).DoFilter(mockReq, mockRes); }
public virtual void TestCrossOriginFilter() { // Setup the configuration settings of the server IDictionary <string, string> conf = new Dictionary <string, string>(); conf[CrossOriginFilter.AllowedOrigins] = "example.com"; FilterConfig filterConfig = new TestCrossOriginFilter.FilterConfigTest(conf); // Origin is not specified for same origin requests HttpServletRequest mockReq = Org.Mockito.Mockito.Mock <HttpServletRequest>(); Org.Mockito.Mockito.When(mockReq.GetHeader(CrossOriginFilter.Origin)).ThenReturn( "example.com"); Org.Mockito.Mockito.When(mockReq.GetHeader(CrossOriginFilter.AccessControlRequestMethod )).ThenReturn("GET"); Org.Mockito.Mockito.When(mockReq.GetHeader(CrossOriginFilter.AccessControlRequestHeaders )).ThenReturn("X-Requested-With"); // Objects to verify interactions based on request HttpServletResponse mockRes = Org.Mockito.Mockito.Mock <HttpServletResponse>(); FilterChain mockChain = Org.Mockito.Mockito.Mock <FilterChain>(); // Object under test CrossOriginFilter filter = new CrossOriginFilter(); filter.Init(filterConfig); filter.DoFilter(mockReq, mockRes, mockChain); Org.Mockito.Mockito.Verify(mockRes).SetHeader(CrossOriginFilter.AccessControlAllowOrigin , "example.com"); Org.Mockito.Mockito.Verify(mockRes).SetHeader(CrossOriginFilter.AccessControlAllowCredentials , true.ToString()); Org.Mockito.Mockito.Verify(mockRes).SetHeader(CrossOriginFilter.AccessControlAllowMethods , filter.GetAllowedMethodsHeader()); Org.Mockito.Mockito.Verify(mockRes).SetHeader(CrossOriginFilter.AccessControlAllowHeaders , filter.GetAllowedHeadersHeader()); Org.Mockito.Mockito.Verify(mockChain).DoFilter(mockReq, mockRes); }
private void DoCrossFilter(HttpServletRequest req, HttpServletResponse res) { string originsList = EncodeHeader(req.GetHeader(Origin)); if (!IsCrossOrigin(originsList)) { if (Log.IsDebugEnabled()) { Log.Debug("Header origin is null. Returning"); } return; } if (!AreOriginsAllowed(originsList)) { if (Log.IsDebugEnabled()) { Log.Debug("Header origins '" + originsList + "' not allowed. Returning"); } return; } string accessControlRequestMethod = req.GetHeader(AccessControlRequestMethod); if (!IsMethodAllowed(accessControlRequestMethod)) { if (Log.IsDebugEnabled()) { Log.Debug("Access control method '" + accessControlRequestMethod + "' not allowed. Returning" ); } return; } string accessControlRequestHeaders = req.GetHeader(AccessControlRequestHeaders); if (!AreHeadersAllowed(accessControlRequestHeaders)) { if (Log.IsDebugEnabled()) { Log.Debug("Access control headers '" + accessControlRequestHeaders + "' not allowed. Returning" ); } return; } if (Log.IsDebugEnabled()) { Log.Debug("Completed cross origin filter checks. Populating " + "HttpServletResponse" ); } res.SetHeader(AccessControlAllowOrigin, originsList); res.SetHeader(AccessControlAllowCredentials, true.ToString()); res.SetHeader(AccessControlAllowMethods, GetAllowedMethodsHeader()); res.SetHeader(AccessControlAllowHeaders, GetAllowedHeadersHeader()); res.SetHeader(AccessControlMaxAge, maxAge); }
/// <exception cref="System.Exception"/> public virtual void TestNonDefaultNonBrowserUserAgentAsBrowser() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); if (handler != null) { handler.Destroy(); handler = null; } handler = GetNewAuthenticationHandler(); Properties props = GetDefaultProperties(); props.SetProperty("alt-kerberos.non-browser.user-agents", "foo, bar"); try { handler.Init(props); } catch (Exception ex) { handler = null; throw; } // Pretend we're something that will not match with "foo" (or "bar") Org.Mockito.Mockito.When(request.GetHeader("User-Agent")).ThenReturn("blah"); // Should use alt authentication AuthenticationToken token = handler.Authenticate(request, response); Assert.Equal("A", token.GetUserName()); Assert.Equal("B", token.GetName()); Assert.Equal(GetExpectedType(), token.GetType()); }
/// <exception cref="System.Exception"/> public virtual void TestRequestWithAuthorization() { string token = KerberosTestUtils.DoAsClient(new _Callable_225()); HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetHeader(KerberosAuthenticator.Authorization)). ThenReturn(KerberosAuthenticator.Negotiate + " " + token); Org.Mockito.Mockito.When(request.GetServerName()).ThenReturn("localhost"); AuthenticationToken authToken = handler.Authenticate(request, response); if (authToken != null) { Org.Mockito.Mockito.Verify(response).SetHeader(Org.Mockito.Mockito.Eq(KerberosAuthenticator .WwwAuthenticate), Org.Mockito.Mockito.Matches(KerberosAuthenticator.Negotiate + " .*")); Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScOk); Assert.Equal(KerberosTestUtils.GetClientPrincipal(), authToken .GetName()); Assert.True(KerberosTestUtils.GetClientPrincipal().StartsWith(authToken .GetUserName())); Assert.Equal(GetExpectedType(), authToken.GetType()); } else { Org.Mockito.Mockito.Verify(response).SetHeader(Org.Mockito.Mockito.Eq(KerberosAuthenticator .WwwAuthenticate), Org.Mockito.Mockito.Matches(KerberosAuthenticator.Negotiate + " .*")); Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScUnauthorized ); } }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest request, HttpServletResponse response ) { Assert.Equal(63 * 1024, request.GetHeader("longheader").Length ); response.SetStatus(HttpServletResponse.ScOk); }
/// <summary><inheritDoc/></summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="Javax.Servlet.ServletException"/> public override void DoFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) { HttpServletRequest req = (HttpServletRequest)request; string newHeader = req.GetHeader(DelegationTokenAuthenticator.DelegationTokenHeader ); if (newHeader == null || newHeader.IsEmpty()) { // For backward compatibility, allow use of the old header field // only when the new header doesn't exist string oldHeader = req.GetHeader(OldHeader); if (oldHeader != null && !oldHeader.IsEmpty()) { request = new _HttpServletRequestWrapper_70(oldHeader, req); } } base.DoFilter(request, response, filterChain); }
/// <exception cref="System.IO.IOException"/> private string GetDelegationToken(HttpServletRequest request) { string dToken = request.GetHeader(DelegationTokenAuthenticator.DelegationTokenHeader ); if (dToken == null) { dToken = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator. DelegationParam); } return(dToken); }
/// <exception cref="System.Exception"/> public virtual void TestRequestWithInvalidAuthorization() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetHeader(KerberosAuthenticator.Authorization)). ThenReturn("invalid"); NUnit.Framework.Assert.IsNull(handler.Authenticate(request, response)); Org.Mockito.Mockito.Verify(response).SetHeader(KerberosAuthenticator.WwwAuthenticate , KerberosAuthenticator.Negotiate); Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScUnauthorized ); }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest req, HttpServletResponse resp) { resp.SetStatus(HttpServletResponse.ScOk); resp.GetWriter().Write("ping"); if (req.GetHeader(DelegationTokenAuthenticator.DelegationTokenHeader) != null) { resp.SetHeader("UsingHeader", "true"); } if (req.GetQueryString() != null && req.GetQueryString().Contains(DelegationTokenAuthenticator .DelegationParam + "=")) { resp.SetHeader("UsingQueryString", "true"); } }
// honor the X-Forwarded-For header set by a configured set of trusted // proxy servers. allows audit logging and proxy user checks to work // via an http proxy public static string GetRemoteAddr(HttpServletRequest request) { string remoteAddr = request.GetRemoteAddr(); string proxyHeader = request.GetHeader("X-Forwarded-For"); if (proxyHeader != null && ProxyServers.IsProxyServer(remoteAddr)) { string clientAddr = proxyHeader.Split(",")[0].Trim(); if (!clientAddr.IsEmpty()) { remoteAddr = clientAddr; } } return(remoteAddr); }
/// <exception cref="System.Exception"/> public virtual void TestAlternateAuthenticationAsBrowser() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); // By default, a User-Agent without "java", "curl", "wget", or "perl" in it // is considered a browser Org.Mockito.Mockito.When(request.GetHeader("User-Agent")).ThenReturn("Some Browser" ); AuthenticationToken token = handler.Authenticate(request, response); Assert.Equal("A", token.GetUserName()); Assert.Equal("B", token.GetName()); Assert.Equal(GetExpectedType(), token.GetType()); }
/// <exception cref="System.Exception"/> private void TestInvalidDelegationTokenHeader() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetHeader(Org.Mockito.Mockito.Eq(DelegationTokenAuthenticator .DelegationTokenHeader))).ThenReturn("invalid"); StringWriter writer = new StringWriter(); Org.Mockito.Mockito.When(response.GetWriter()).ThenReturn(new PrintWriter(writer) ); NUnit.Framework.Assert.IsNull(handler.Authenticate(request, response)); Assert.True(writer.ToString().Contains("AuthenticationException" )); }
/// <summary> /// It enforces the the Kerberos SPNEGO authentication sequence returning an /// <see cref="AuthenticationToken"/> /// only after the Kerberos SPNEGO sequence has /// completed successfully (in the case of Java access) and only after the /// custom authentication implemented by the subclass in alternateAuthenticate /// has completed successfully (in the case of browser access). /// </summary> /// <param name="request">the HTTP client request.</param> /// <param name="response">the HTTP client response.</param> /// <returns>an authentication token if the request is authorized or null</returns> /// <exception cref="System.IO.IOException">thrown if an IO error occurred</exception> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// ">thrown if an authentication error occurred</exception> public override AuthenticationToken Authenticate(HttpServletRequest request, HttpServletResponse response) { AuthenticationToken token; if (IsBrowser(request.GetHeader("User-Agent"))) { token = AlternateAuthenticate(request, response); } else { token = base.Authenticate(request, response); } return(token); }
/// <summary> /// It enforces the the Kerberos SPNEGO authentication sequence returning an /// <see cref="AuthenticationToken"/> /// only /// after the Kerberos SPNEGO sequence has completed successfully. /// </summary> /// <param name="request">the HTTP client request.</param> /// <param name="response">the HTTP client response.</param> /// <returns> /// an authentication token if the Kerberos SPNEGO sequence is complete and valid, /// <code>null</code> if it is in progress (in this case the handler handles the response to the client). /// </returns> /// <exception cref="System.IO.IOException">thrown if an IO error occurred.</exception> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// ">thrown if Kerberos SPNEGO sequence failed.</exception> public override AuthenticationToken Authenticate(HttpServletRequest request, HttpServletResponse response) { AuthenticationToken token = null; string authorization = request.GetHeader(KerberosAuthenticator.Authorization); if (authorization == null || !authorization.StartsWith(KerberosAuthenticator.Negotiate )) { response.SetHeader(WwwAuthenticate, KerberosAuthenticator.Negotiate); response.SetStatus(HttpServletResponse.ScUnauthorized); if (authorization == null) { Log.Trace("SPNEGO starting"); } else { Log.Warn("'" + KerberosAuthenticator.Authorization + "' does not start with '" + KerberosAuthenticator.Negotiate + "' : {}", authorization); } } else { authorization = Runtime.Substring(authorization, KerberosAuthenticator.Negotiate .Length).Trim(); Base64 base64 = new Base64(0); byte[] clientToken = base64.Decode(authorization); string serverName = request.GetServerName(); try { token = Subject.DoAs(serverSubject, new _PrivilegedExceptionAction_347(this, serverName , clientToken, base64, response)); } catch (PrivilegedActionException ex) { if (ex.GetException() is IOException) { throw (IOException)ex.GetException(); } else { throw new AuthenticationException(ex.GetException()); } } } return(token); }
/// <exception cref="System.Exception"/> private void TestValidDelegationTokenHeader() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier> dToken = (Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier>)handler.GetTokenManager().CreateToken(UserGroupInformation .GetCurrentUser(), "user"); Org.Mockito.Mockito.When(request.GetHeader(Org.Mockito.Mockito.Eq(DelegationTokenAuthenticator .DelegationTokenHeader))).ThenReturn(dToken.EncodeToUrlString()); AuthenticationToken token = handler.Authenticate(request, response); Assert.Equal(UserGroupInformation.GetCurrentUser().GetShortUserName (), token.GetUserName()); Assert.Equal(0, token.GetExpires()); Assert.Equal(handler.GetType(), token.GetType()); Assert.True(token.IsExpired()); }
/// <exception cref="System.Exception"/> public virtual void TestRequestWithIncompleteAuthorization() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetHeader(KerberosAuthenticator.Authorization)). ThenReturn(KerberosAuthenticator.Negotiate); try { handler.Authenticate(request, response); NUnit.Framework.Assert.Fail(); } catch (AuthenticationException) { } catch (Exception) { // Expected NUnit.Framework.Assert.Fail(); } }
/// <exception cref="System.Exception"/> public virtual void TestRequestWithInvalidKerberosAuthorization() { string token = new Base64(0).EncodeToString(new byte[] { 0, 1, 2 }); HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetHeader(KerberosAuthenticator.Authorization)). ThenReturn(KerberosAuthenticator.Negotiate + token); try { handler.Authenticate(request, response); NUnit.Framework.Assert.Fail(); } catch (AuthenticationException) { } catch (Exception) { // Expected NUnit.Framework.Assert.Fail(); } }
private string GetRemoteAddr(string clientAddr, string proxyAddr, bool trusted) { HttpServletRequest req = Org.Mockito.Mockito.Mock <HttpServletRequest>(); Org.Mockito.Mockito.When(req.GetRemoteAddr()).ThenReturn("1.2.3.4"); Configuration conf = new Configuration(); if (proxyAddr == null) { Org.Mockito.Mockito.When(req.GetRemoteAddr()).ThenReturn(clientAddr); } else { Org.Mockito.Mockito.When(req.GetRemoteAddr()).ThenReturn(proxyAddr); Org.Mockito.Mockito.When(req.GetHeader("X-Forwarded-For")).ThenReturn(clientAddr); if (trusted) { conf.Set(ProxyServers.ConfHadoopProxyservers, proxyAddr); } } ProxyUsers.RefreshSuperUserGroupsConfiguration(conf); return(JspHelper.GetRemoteAddr(req)); }
public virtual void TestSameOrigin() { // Setup the configuration settings of the server IDictionary <string, string> conf = new Dictionary <string, string>(); conf[CrossOriginFilter.AllowedOrigins] = string.Empty; FilterConfig filterConfig = new TestCrossOriginFilter.FilterConfigTest(conf); // Origin is not specified for same origin requests HttpServletRequest mockReq = Org.Mockito.Mockito.Mock <HttpServletRequest>(); Org.Mockito.Mockito.When(mockReq.GetHeader(CrossOriginFilter.Origin)).ThenReturn( null); // Objects to verify interactions based on request HttpServletResponse mockRes = Org.Mockito.Mockito.Mock <HttpServletResponse>(); FilterChain mockChain = Org.Mockito.Mockito.Mock <FilterChain>(); // Object under test CrossOriginFilter filter = new CrossOriginFilter(); filter.Init(filterConfig); filter.DoFilter(mockReq, mockRes, mockChain); Org.Mockito.Mockito.VerifyZeroInteractions(mockRes); Org.Mockito.Mockito.Verify(mockChain).DoFilter(mockReq, mockRes); }
/// <summary>Download link and have it be the response.</summary> /// <param name="req">the http request</param> /// <param name="resp">the http response</param> /// <param name="link">the link to download</param> /// <param name="c">the cookie to set if any</param> /// <exception cref="System.IO.IOException">on any error.</exception> private static void ProxyLink(HttpServletRequest req, HttpServletResponse resp, URI link, Cookie c, string proxyHost) { DefaultHttpClient client = new DefaultHttpClient(); client.GetParams().SetParameter(ClientPNames.CookiePolicy, CookiePolicy.BrowserCompatibility ).SetBooleanParameter(ClientPNames.AllowCircularRedirects, true); // Make sure we send the request from the proxy address in the config // since that is what the AM filter checks against. IP aliasing or // similar could cause issues otherwise. IPAddress localAddress = Sharpen.Extensions.GetAddressByName(proxyHost); if (Log.IsDebugEnabled()) { Log.Debug("local InetAddress for proxy host: {}", localAddress); } client.GetParams().SetParameter(ConnRoutePNames.LocalAddress, localAddress); HttpGet httpGet = new HttpGet(link); Enumeration <string> names = req.GetHeaderNames(); while (names.MoveNext()) { string name = names.Current; if (passThroughHeaders.Contains(name)) { string value = req.GetHeader(name); if (Log.IsDebugEnabled()) { Log.Debug("REQ HEADER: {} : {}", name, value); } httpGet.SetHeader(name, value); } } string user = req.GetRemoteUser(); if (user != null && !user.IsEmpty()) { httpGet.SetHeader("Cookie", ProxyUserCookieName + "=" + URLEncoder.Encode(user, "ASCII" )); } OutputStream @out = resp.GetOutputStream(); try { HttpResponse httpResp = client.Execute(httpGet); resp.SetStatus(httpResp.GetStatusLine().GetStatusCode()); foreach (Header header in httpResp.GetAllHeaders()) { resp.SetHeader(header.GetName(), header.GetValue()); } if (c != null) { resp.AddCookie(c); } InputStream @in = httpResp.GetEntity().GetContent(); if (@in != null) { IOUtils.CopyBytes(@in, @out, 4096, true); } } finally { httpGet.ReleaseConnection(); } }
/// <summary> /// The default behavior of this method is to return GetHeader(string name) /// on the wrapped request object. /// </summary> /// <param name="name"></param> /// <returns></returns> public string GetHeader(string name) { return(HttpServletRequest.GetHeader(name)); }
private static MD5Hash ParseMD5Header(HttpServletRequest request) { string header = request.GetHeader(Md5Header); return((header != null) ? new MD5Hash(header) : null); }