/// <summary> /// Enforces the content-type to be application/octet-stream for /// POST and PUT requests. /// </summary> /// <param name="request">servlet request.</param> /// <param name="response">servlet response.</param> /// <param name="chain">filter chain.</param> /// <exception cref="System.IO.IOException">thrown if an IO error occurrs.</exception> /// <exception cref="Javax.Servlet.ServletException">thrown if a servet error occurrs. /// </exception> public virtual void DoFilter(ServletRequest request, ServletResponse response, FilterChain chain) { bool contentTypeOK = true; HttpServletRequest httpReq = (HttpServletRequest)request; HttpServletResponse httpRes = (HttpServletResponse)response; string method = httpReq.GetMethod(); if (method.Equals("PUT") || method.Equals("POST")) { string op = httpReq.GetParameter(HttpFSFileSystem.OpParam); if (op != null && UploadOperations.Contains(StringUtils.ToUpperCase(op))) { if (Sharpen.Runtime.EqualsIgnoreCase("true", httpReq.GetParameter(HttpFSParametersProvider.DataParam .Name))) { string contentType = httpReq.GetContentType(); contentTypeOK = Sharpen.Runtime.EqualsIgnoreCase(HttpFSFileSystem.UploadContentType , contentType); } } } if (contentTypeOK) { chain.DoFilter(httpReq, httpRes); } else { httpRes.SendError(HttpServletResponse.ScBadRequest, "Data upload requests must have content-type set to '" + HttpFSFileSystem.UploadContentType + "'"); } }
public virtual void Mdc() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); Org.Mockito.Mockito.When(request.GetUserPrincipal()).ThenReturn(null); Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn("METHOD"); Org.Mockito.Mockito.When(request.GetPathInfo()).ThenReturn("/pathinfo"); ServletResponse response = Org.Mockito.Mockito.Mock <ServletResponse>(); AtomicBoolean invoked = new AtomicBoolean(); FilterChain chain = new _FilterChain_55(invoked); MDC.Clear(); Filter filter = new MDCFilter(); filter.Init(null); filter.DoFilter(request, response, chain); NUnit.Framework.Assert.IsTrue(invoked.Get()); NUnit.Framework.Assert.IsNull(MDC.Get("hostname")); NUnit.Framework.Assert.IsNull(MDC.Get("user")); NUnit.Framework.Assert.IsNull(MDC.Get("method")); NUnit.Framework.Assert.IsNull(MDC.Get("path")); Org.Mockito.Mockito.When(request.GetUserPrincipal()).ThenReturn(new _Principal_78 ()); invoked.Set(false); chain = new _FilterChain_86(invoked); filter.DoFilter(request, response, chain); NUnit.Framework.Assert.IsTrue(invoked.Get()); HostnameFilter.HostnameTl.Set("HOST"); invoked.Set(false); chain = new _FilterChain_103(invoked); filter.DoFilter(request, response, chain); NUnit.Framework.Assert.IsTrue(invoked.Get()); HostnameFilter.HostnameTl.Remove(); filter.Destroy(); }
/// <exception cref="System.Exception"/> private void TestGetToken(string renewer, Text expectedTokenKind) { DelegationTokenAuthenticator.DelegationTokenOperation op = DelegationTokenAuthenticator.DelegationTokenOperation .Getdelegationtoken; HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetQueryString()).ThenReturn(DelegationTokenAuthenticator .OpParam + "=" + op.ToString()); Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn(op.GetHttpMethod()); AuthenticationToken token = Org.Mockito.Mockito.Mock <AuthenticationToken>(); Org.Mockito.Mockito.When(token.GetUserName()).ThenReturn("user"); Org.Mockito.Mockito.When(response.GetWriter()).ThenReturn(new PrintWriter(new StringWriter ())); NUnit.Framework.Assert.IsFalse(handler.ManagementOperation(token, request, response )); Org.Mockito.Mockito.When(request.GetQueryString()).ThenReturn(DelegationTokenAuthenticator .OpParam + "=" + op.ToString() + "&" + DelegationTokenAuthenticator.RenewerParam + "=" + renewer); Org.Mockito.Mockito.Reset(response); Org.Mockito.Mockito.Reset(token); Org.Mockito.Mockito.When(token.GetUserName()).ThenReturn("user"); StringWriter writer = new StringWriter(); PrintWriter pwriter = new PrintWriter(writer); Org.Mockito.Mockito.When(response.GetWriter()).ThenReturn(pwriter); NUnit.Framework.Assert.IsFalse(handler.ManagementOperation(token, request, response )); if (renewer == null) { Org.Mockito.Mockito.Verify(token).GetUserName(); } else { Org.Mockito.Mockito.Verify(token).GetUserName(); } Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScOk); Org.Mockito.Mockito.Verify(response).SetContentType(MediaType.ApplicationJson); pwriter.Close(); string responseOutput = writer.ToString(); string tokenLabel = DelegationTokenAuthenticator.DelegationTokenJson; Assert.True(responseOutput.Contains(tokenLabel)); Assert.True(responseOutput.Contains(DelegationTokenAuthenticator .DelegationTokenUrlStringJson)); ObjectMapper jsonMapper = new ObjectMapper(); IDictionary json = jsonMapper.ReadValue <IDictionary>(responseOutput); json = (IDictionary)json[tokenLabel]; string tokenStr; tokenStr = (string)json[DelegationTokenAuthenticator.DelegationTokenUrlStringJson ]; Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier> dt = new Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier>(); dt.DecodeFromUrlString(tokenStr); handler.GetTokenManager().VerifyToken(dt); Assert.Equal(expectedTokenKind, dt.GetKind()); }
/// <exception cref="System.Exception"/> private void TestManagementOperationErrors() { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetQueryString()).ThenReturn(DelegationTokenAuthenticator .OpParam + "=" + DelegationTokenAuthenticator.DelegationTokenOperation.Getdelegationtoken .ToString()); Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn("FOO"); NUnit.Framework.Assert.IsFalse(handler.ManagementOperation(null, request, response )); Org.Mockito.Mockito.Verify(response).SendError(Org.Mockito.Mockito.Eq(HttpServletResponse .ScBadRequest), Org.Mockito.Mockito.StartsWith("Wrong HTTP method")); Org.Mockito.Mockito.Reset(response); Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn(DelegationTokenAuthenticator.DelegationTokenOperation .Getdelegationtoken.GetHttpMethod()); NUnit.Framework.Assert.IsFalse(handler.ManagementOperation(null, request, response )); Org.Mockito.Mockito.Verify(response).SetStatus(Org.Mockito.Mockito.Eq(HttpServletResponse .ScUnauthorized)); Org.Mockito.Mockito.Verify(response).SetHeader(Org.Mockito.Mockito.Eq(KerberosAuthenticator .WwwAuthenticate), Org.Mockito.Mockito.Eq("mock")); }
/// <exception cref="System.Exception"/> private void TestRenewToken() { DelegationTokenAuthenticator.DelegationTokenOperation op = DelegationTokenAuthenticator.DelegationTokenOperation .Renewdelegationtoken; HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetQueryString()).ThenReturn(DelegationTokenAuthenticator .OpParam + "=" + op.ToString()); Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn(op.GetHttpMethod()); NUnit.Framework.Assert.IsFalse(handler.ManagementOperation(null, request, response )); Org.Mockito.Mockito.Verify(response).SetStatus(Org.Mockito.Mockito.Eq(HttpServletResponse .ScUnauthorized)); Org.Mockito.Mockito.Verify(response).SetHeader(Org.Mockito.Mockito.Eq(KerberosAuthenticator .WwwAuthenticate), Org.Mockito.Mockito.Eq("mock")); Org.Mockito.Mockito.Reset(response); AuthenticationToken token = Org.Mockito.Mockito.Mock <AuthenticationToken>(); Org.Mockito.Mockito.When(token.GetUserName()).ThenReturn("user"); NUnit.Framework.Assert.IsFalse(handler.ManagementOperation(token, request, response )); Org.Mockito.Mockito.Verify(response).SendError(Org.Mockito.Mockito.Eq(HttpServletResponse .ScBadRequest), Org.Mockito.Mockito.Contains("requires the parameter [token]")); Org.Mockito.Mockito.Reset(response); StringWriter writer = new StringWriter(); PrintWriter pwriter = new PrintWriter(writer); Org.Mockito.Mockito.When(response.GetWriter()).ThenReturn(pwriter); 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.GetQueryString()).ThenReturn(DelegationTokenAuthenticator .OpParam + "=" + op.ToString() + "&" + DelegationTokenAuthenticator.TokenParam + "=" + dToken.EncodeToUrlString()); NUnit.Framework.Assert.IsFalse(handler.ManagementOperation(token, request, response )); Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScOk); pwriter.Close(); Assert.True(writer.ToString().Contains("long")); handler.GetTokenManager().VerifyToken(dToken); }
/// <summary> /// Handle redirects with a status code that can in future support verbs other /// than GET, thus supporting full REST functionality. /// </summary> /// <remarks> /// Handle redirects with a status code that can in future support verbs other /// than GET, thus supporting full REST functionality. /// <p> /// The target URL is included in the redirect text returned /// <p> /// At the end of this method, the output stream is closed. /// </remarks> /// <param name="request"> /// request (hence: the verb and any other information /// relevant to a redirect) /// </param> /// <param name="response">the response</param> /// <param name="target">the target URL -unencoded</param> /// <exception cref="System.IO.IOException"/> public static void SendRedirect(HttpServletRequest request, HttpServletResponse response , string target) { if (Log.IsDebugEnabled()) { Log.Debug("Redirecting {} {} to {}", request.GetMethod(), request.GetRequestURI() , target); } string location = response.EncodeRedirectURL(target); response.SetStatus(HttpServletResponse.ScFound); response.SetHeader(Location, location); response.SetContentType(MimeType.Html); PrintWriter writer = response.GetWriter(); ProxyUtils.Page p = new ProxyUtils.Page(writer); p.Html().Head().Title("Moved").().Body().H1("Moved").Div().("Content has moved ") .A(location, "here").().().(); writer.Close(); }
/// <exception cref="System.Exception"/> private void TestCancelToken() { DelegationTokenAuthenticator.DelegationTokenOperation op = DelegationTokenAuthenticator.DelegationTokenOperation .Canceldelegationtoken; HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.When(request.GetQueryString()).ThenReturn(DelegationTokenAuthenticator .OpParam + "=" + op.ToString()); Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn(op.GetHttpMethod()); NUnit.Framework.Assert.IsFalse(handler.ManagementOperation(null, request, response )); Org.Mockito.Mockito.Verify(response).SendError(Org.Mockito.Mockito.Eq(HttpServletResponse .ScBadRequest), Org.Mockito.Mockito.Contains("requires the parameter [token]")); Org.Mockito.Mockito.Reset(response); Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier> token = (Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier>)handler.GetTokenManager().CreateToken(UserGroupInformation .GetCurrentUser(), "foo"); Org.Mockito.Mockito.When(request.GetQueryString()).ThenReturn(DelegationTokenAuthenticator .OpParam + "=" + op.ToString() + "&" + DelegationTokenAuthenticator.TokenParam + "=" + token.EncodeToUrlString()); NUnit.Framework.Assert.IsFalse(handler.ManagementOperation(null, request, response )); Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScOk); try { handler.GetTokenManager().VerifyToken(token); NUnit.Framework.Assert.Fail(); } catch (SecretManager.InvalidToken) { } catch { //NOP NUnit.Framework.Assert.Fail(); } }
/// <exception cref="System.IO.IOException"/> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// "/> public override bool ManagementOperation(AuthenticationToken token, HttpServletRequest request, HttpServletResponse response) { bool requestContinues = true; string op = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator .OpParam); op = (op != null) ? StringUtils.ToUpperCase(op) : null; if (DelegationTokenOps.Contains(op) && !request.GetMethod().Equals("OPTIONS")) { DelegationTokenAuthenticator.DelegationTokenOperation dtOp = DelegationTokenAuthenticator.DelegationTokenOperation .ValueOf(op); if (dtOp.GetHttpMethod().Equals(request.GetMethod())) { bool doManagement; if (dtOp.RequiresKerberosCredentials() && token == null) { token = Authenticate(request, response); if (token == null) { requestContinues = false; doManagement = false; } else { doManagement = true; } } else { doManagement = true; } if (doManagement) { UserGroupInformation requestUgi = (token != null) ? UserGroupInformation.CreateRemoteUser (token.GetUserName()) : null; // Create the proxy user if doAsUser exists string doAsUser = DelegationTokenAuthenticationFilter.GetDoAs(request); if (requestUgi != null && doAsUser != null) { requestUgi = UserGroupInformation.CreateProxyUser(doAsUser, requestUgi); try { ProxyUsers.Authorize(requestUgi, request.GetRemoteHost()); } catch (AuthorizationException ex) { HttpExceptionUtils.CreateServletExceptionResponse(response, HttpServletResponse.ScForbidden , ex); return(false); } } IDictionary map = null; switch (dtOp) { case DelegationTokenAuthenticator.DelegationTokenOperation.Getdelegationtoken: { if (requestUgi == null) { throw new InvalidOperationException("request UGI cannot be NULL"); } string renewer = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator .RenewerParam); try { Org.Apache.Hadoop.Security.Token.Token <object> dToken = tokenManager.CreateToken( requestUgi, renewer); map = DelegationTokenToJSON(dToken); } catch (IOException ex) { throw new AuthenticationException(ex.ToString(), ex); } break; } case DelegationTokenAuthenticator.DelegationTokenOperation.Renewdelegationtoken: { if (requestUgi == null) { throw new InvalidOperationException("request UGI cannot be NULL"); } string tokenToRenew = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator .TokenParam); if (tokenToRenew == null) { response.SendError(HttpServletResponse.ScBadRequest, MessageFormat.Format("Operation [{0}] requires the parameter [{1}]" , dtOp, KerberosDelegationTokenAuthenticator.TokenParam)); requestContinues = false; } else { Org.Apache.Hadoop.Security.Token.Token <AbstractDelegationTokenIdentifier> dt = new Org.Apache.Hadoop.Security.Token.Token(); try { dt.DecodeFromUrlString(tokenToRenew); long expirationTime = tokenManager.RenewToken(dt, requestUgi.GetShortUserName()); map = new Hashtable(); map["long"] = expirationTime; } catch (IOException ex) { throw new AuthenticationException(ex.ToString(), ex); } } break; } case DelegationTokenAuthenticator.DelegationTokenOperation.Canceldelegationtoken: { string tokenToCancel = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator .TokenParam); if (tokenToCancel == null) { response.SendError(HttpServletResponse.ScBadRequest, MessageFormat.Format("Operation [{0}] requires the parameter [{1}]" , dtOp, KerberosDelegationTokenAuthenticator.TokenParam)); requestContinues = false; } else { Org.Apache.Hadoop.Security.Token.Token <AbstractDelegationTokenIdentifier> dt = new Org.Apache.Hadoop.Security.Token.Token(); try { dt.DecodeFromUrlString(tokenToCancel); tokenManager.CancelToken(dt, (requestUgi != null) ? requestUgi.GetShortUserName() : null); } catch (IOException) { response.SendError(HttpServletResponse.ScNotFound, "Invalid delegation token, cannot cancel" ); requestContinues = false; } } break; } } if (requestContinues) { response.SetStatus(HttpServletResponse.ScOk); if (map != null) { response.SetContentType(MediaType.ApplicationJson); TextWriter writer = response.GetWriter(); ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.WriteValue(writer, map); writer.Write(Enter); writer.Flush(); } requestContinues = false; } } } else { response.SendError(HttpServletResponse.ScBadRequest, MessageFormat.Format("Wrong HTTP method [{0}] for operation [{1}], it should be " + "[{2}]", request.GetMethod(), dtOp, dtOp.GetHttpMethod())); requestContinues = false; } } return(requestContinues); }
/// <exception cref="Javax.Servlet.ServletException"/> /// <exception cref="System.IO.IOException"/> protected override void Service(HttpServletRequest req, HttpServletResponse res) { res.SetCharacterEncoding("UTF-8"); string uri = HtmlQuoting.QuoteHtmlChars(req.GetRequestURI()); if (uri == null) { uri = "/"; } if (devMode && uri.Equals("/__stop")) { // quick hack to restart servers in dev mode without OS commands res.SetStatus(res.ScNoContent); Log.Info("dev mode restart requested"); PrepareToExit(); return; } // if they provide a redirectPath go there instead of going to // "/" so that filters can differentiate the webapps. if (uri.Equals("/")) { string redirectPath = webApp.GetRedirectPath(); if (redirectPath != null && !redirectPath.IsEmpty()) { res.SendRedirect(redirectPath); return; } } string method = req.GetMethod(); if (method.Equals("OPTIONS")) { DoOptions(req, res); return; } if (method.Equals("TRACE")) { DoTrace(req, res); return; } if (method.Equals("HEAD")) { DoGet(req, res); // default to bad request return; } string pathInfo = req.GetPathInfo(); if (pathInfo == null) { pathInfo = "/"; } Controller.RequestContext rc = injector.GetInstance <Controller.RequestContext>(); if (SetCookieParams(rc, req) > 0) { Cookie ec = rc.Cookies()[ErrorCookie]; if (ec != null) { rc.SetStatus(System.Convert.ToInt32(rc.Cookies()[StatusCookie].GetValue())); RemoveErrorCookies(res, uri); rc.Set(Params.ErrorDetails, ec.GetValue()); Render(typeof(ErrorPage)); return; } } rc.prefix = webApp.Name(); Router.Dest dest = null; try { dest = router.Resolve(method, pathInfo); } catch (WebAppException e) { rc.error = e; if (!e.Message.Contains("not found")) { rc.SetStatus(res.ScInternalServerError); Render(typeof(ErrorPage)); return; } } if (dest == null) { rc.SetStatus(res.ScNotFound); Render(typeof(ErrorPage)); return; } rc.devMode = devMode; SetMoreParams(rc, pathInfo, dest); Controller controller = injector.GetInstance(dest.controllerClass); try { // TODO: support args converted from /path/:arg1/... dest.action.Invoke(controller, (object[])null); if (!rc.rendered) { if (dest.defaultViewClass != null) { Render(dest.defaultViewClass); } else { if (rc.status == 200) { throw new InvalidOperationException("No view rendered for 200"); } } } } catch (Exception e) { Log.Error("error handling URI: " + uri, e); // Page could be half rendered (but still not flushed). So redirect. RedirectToErrorPage(res, e, uri, devMode); } }
/// <exception cref="System.Exception"/> private void Test(string method, string operation, string contentType, bool upload , bool error) { HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>(); HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>(); Org.Mockito.Mockito.Reset(request); Org.Mockito.Mockito.When(request.GetMethod()).ThenReturn(method); Org.Mockito.Mockito.When(request.GetParameter(HttpFSFileSystem.OpParam)).ThenReturn (operation); Org.Mockito.Mockito.When(request.GetParameter(HttpFSParametersProvider.DataParam. Name)).ThenReturn(bool.ToString(upload)); Org.Mockito.Mockito.When(request.GetContentType()).ThenReturn(contentType); FilterChain chain = Org.Mockito.Mockito.Mock <FilterChain>(); Filter filter = new CheckUploadContentTypeFilter(); filter.DoFilter(request, response, chain); if (error) { Org.Mockito.Mockito.Verify(response).SendError(Org.Mockito.Mockito.Eq(HttpServletResponse .ScBadRequest), Org.Mockito.Mockito.Contains("Data upload")); } else { Org.Mockito.Mockito.Verify(chain).DoFilter(request, response); } }