Exemple #1
0
        /// <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());
        }
        /// <summary>Returns the full URL of the request including the query string.</summary>
        /// <remarks>
        /// Returns the full URL of the request including the query string.
        /// <p>
        /// Used as a convenience method for logging purposes.
        /// </remarks>
        /// <param name="request">the request object.</param>
        /// <returns>the full URL of the request including the query string.</returns>
        protected internal virtual string GetRequestURL(HttpServletRequest request)
        {
            StringBuilder sb = request.GetRequestURL();

            if (request.GetQueryString() != null)
            {
                sb.Append("?").Append(request.GetQueryString());
            }
            return(sb.ToString());
        }
Exemple #3
0
 /// <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");
     }
 }
Exemple #4
0
        /// <exception cref="System.Exception"/>
        private void _testUserName(bool anonymous)
        {
            PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler();

            try
            {
                Properties props = new Properties();
                props.SetProperty(PseudoAuthenticationHandler.AnonymousAllowed, bool.ToString(anonymous
                                                                                              ));
                handler.Init(props);
                HttpServletRequest  request  = Org.Mockito.Mockito.Mock <HttpServletRequest>();
                HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>();
                Org.Mockito.Mockito.When(request.GetQueryString()).ThenReturn(PseudoAuthenticator
                                                                              .UserName + "=" + "user");
                AuthenticationToken token = handler.Authenticate(request, response);
                NUnit.Framework.Assert.IsNotNull(token);
                Assert.Equal("user", token.GetUserName());
                Assert.Equal("user", token.GetName());
                Assert.Equal(PseudoAuthenticationHandler.Type, token.GetType()
                             );
            }
            finally
            {
                handler.Destroy();
            }
        }
Exemple #5
0
            /// <exception cref="Javax.Servlet.ServletException"/>
            /// <exception cref="System.IO.IOException"/>
            protected override void DoGet(HttpServletRequest req, HttpServletResponse res)
            {
                string queryString = req.GetQueryString();

                switch (counter)
                {
                case 0:
                {
                    VerifyQuery(queryString, "SUCCEEDED");
                    break;
                }

                case 2:
                {
                    VerifyQuery(queryString, "KILLED");
                    break;
                }

                case 4:
                {
                    VerifyQuery(queryString, "FAILED");
                    break;
                }
                }
                if (counter % 2 == 0)
                {
                    res.SendError(HttpServletResponse.ScBadRequest, "forcing error");
                }
                else
                {
                    res.SetStatus(HttpServletResponse.ScOk);
                }
                counter++;
            }
Exemple #6
0
        /// <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);
        }
Exemple #7
0
        /// <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();
            }
        }
Exemple #8
0
        /// <exception cref="System.Exception"/>
        private void TestInvalidDelegationTokenQueryString()
        {
            HttpServletRequest  request  = Org.Mockito.Mockito.Mock <HttpServletRequest>();
            HttpServletResponse response = Org.Mockito.Mockito.Mock <HttpServletResponse>();

            Org.Mockito.Mockito.When(request.GetQueryString()).ThenReturn(DelegationTokenAuthenticator
                                                                          .DelegationParam + "=invalid");
            StringWriter writer = new StringWriter();

            Org.Mockito.Mockito.When(response.GetWriter()).ThenReturn(new PrintWriter(writer)
                                                                      );
            NUnit.Framework.Assert.IsNull(handler.Authenticate(request, response));
            Org.Mockito.Mockito.Verify(response).SetStatus(HttpServletResponse.ScForbidden);
            Assert.True(writer.ToString().Contains("AuthenticationException"
                                                   ));
        }
Exemple #9
0
        /// <summary>
        /// Extract a query string parameter without triggering http parameters
        /// processing by the servlet container.
        /// </summary>
        /// <param name="request">the request</param>
        /// <param name="name">the parameter to get the value.</param>
        /// <returns>
        /// the parameter value, or <code>NULL</code> if the parameter is not
        /// defined.
        /// </returns>
        /// <exception cref="System.IO.IOException">thrown if there was an error parsing the query string.
        ///     </exception>
        public static string GetParameter(HttpServletRequest request, string name)
        {
            IList <NameValuePair> list = URLEncodedUtils.Parse(request.GetQueryString(), Utf8Charset
                                                               );

            if (list != null)
            {
                foreach (NameValuePair nv in list)
                {
                    if (name.Equals(nv.GetName()))
                    {
                        return(nv.GetValue());
                    }
                }
            }
            return(null);
        }
Exemple #10
0
        private string GetUserName(HttpServletRequest request)
        {
            IList <NameValuePair> list = URLEncodedUtils.Parse(request.GetQueryString(), Utf8Charset
                                                               );

            if (list != null)
            {
                foreach (NameValuePair nv in list)
                {
                    if (PseudoAuthenticator.UserName.Equals(nv.GetName()))
                    {
                        return(nv.GetValue());
                    }
                }
            }
            return(null);
        }
            /// <exception cref="Javax.Servlet.ServletException"/>
            /// <exception cref="System.IO.IOException"/>
            protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                          )
            {
                InputStreamReader @in  = new InputStreamReader(request.GetInputStream());
                TextWriter        @out = new TextWriter(response.GetOutputStream());

                calledTimes++;
                try
                {
                    requestUri = new URI(null, null, request.GetRequestURI(), request.GetQueryString(
                                             ), null);
                }
                catch (URISyntaxException)
                {
                }
                @in.Close();
                @out.Close();
            }
Exemple #12
0
        internal static string GetDoAs(HttpServletRequest request)
        {
            IList <NameValuePair> list = URLEncodedUtils.Parse(request.GetQueryString(), Utf8Charset
                                                               );

            if (list != null)
            {
                foreach (NameValuePair nv in list)
                {
                    if (Runtime.EqualsIgnoreCase(DelegationTokenAuthenticatedURL.DoAs, nv.GetName
                                                     ()))
                    {
                        return(nv.GetValue());
                    }
                }
            }
            return(null);
        }
Exemple #13
0
        /// <exception cref="System.Exception"/>
        private void TestValidDelegationTokenQueryString()
        {
            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.GetQueryString()).ThenReturn(DelegationTokenAuthenticator
                                                                          .DelegationParam + "=" + 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());
        }
Exemple #14
0
        /// <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.IO.IOException"/>
        protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                string   userApprovedParamS = req.GetParameter(ProxyUriUtils.ProxyApprovalParam);
                bool     userWasWarned      = false;
                bool     userApproved       = Sharpen.Extensions.ValueOf(userApprovedParamS);
                bool     securityEnabled    = IsSecurityEnabled();
                string   remoteUser         = req.GetRemoteUser();
                string   pathInfo           = req.GetPathInfo();
                string[] parts = pathInfo.Split("/", 3);
                if (parts.Length < 2)
                {
                    Log.Warn("{} gave an invalid proxy path {}", remoteUser, pathInfo);
                    NotFound(resp, "Your path appears to be formatted incorrectly.");
                    return;
                }
                //parts[0] is empty because path info always starts with a /
                string        appId = parts[1];
                string        rest  = parts.Length > 2 ? parts[2] : string.Empty;
                ApplicationId id    = Apps.ToAppID(appId);
                if (id == null)
                {
                    Log.Warn("{} attempting to access {} that is invalid", remoteUser, appId);
                    NotFound(resp, appId + " appears to be formatted incorrectly.");
                    return;
                }
                if (securityEnabled)
                {
                    string   cookieName = GetCheckCookieName(id);
                    Cookie[] cookies    = req.GetCookies();
                    if (cookies != null)
                    {
                        foreach (Cookie c in cookies)
                        {
                            if (cookieName.Equals(c.GetName()))
                            {
                                userWasWarned = true;
                                userApproved  = userApproved || Sharpen.Extensions.ValueOf(c.GetValue());
                                break;
                            }
                        }
                    }
                }
                bool checkUser = securityEnabled && (!userWasWarned || !userApproved);
                AppReportFetcher.FetchedAppReport fetchedAppReport = null;
                ApplicationReport applicationReport = null;
                try
                {
                    fetchedAppReport = GetApplicationReport(id);
                    if (fetchedAppReport != null)
                    {
                        if (fetchedAppReport.GetAppReportSource() != AppReportFetcher.AppReportSource.Rm &&
                            fetchedAppReport.GetAppReportSource() != AppReportFetcher.AppReportSource.Ahs)
                        {
                            throw new NotSupportedException("Application report not " + "fetched from RM or history server."
                                                            );
                        }
                        applicationReport = fetchedAppReport.GetApplicationReport();
                    }
                }
                catch (ApplicationNotFoundException)
                {
                    applicationReport = null;
                }
                if (applicationReport == null)
                {
                    Log.Warn("{} attempting to access {} that was not found", remoteUser, id);
                    URI toFetch = ProxyUriUtils.GetUriFromTrackingPlugins(id, this.trackingUriPlugins
                                                                          );
                    if (toFetch != null)
                    {
                        ProxyUtils.SendRedirect(req, resp, toFetch.ToString());
                        return;
                    }
                    NotFound(resp, "Application " + appId + " could not be found " + "in RM or history server"
                             );
                    return;
                }
                string original = applicationReport.GetOriginalTrackingUrl();
                URI    trackingUri;
                if (original == null || original.Equals("N/A") || original.Equals(string.Empty))
                {
                    if (fetchedAppReport.GetAppReportSource() == AppReportFetcher.AppReportSource.Rm)
                    {
                        // fallback to ResourceManager's app page if no tracking URI provided
                        // and Application Report was fetched from RM
                        Log.Debug("Original tracking url is '{}'. Redirecting to RM app page", original ==
                                  null ? "NULL" : original);
                        ProxyUtils.SendRedirect(req, resp, StringHelper.Pjoin(rmAppPageUrlBase, id.ToString
                                                                                  ()));
                    }
                    else
                    {
                        if (fetchedAppReport.GetAppReportSource() == AppReportFetcher.AppReportSource.Ahs)
                        {
                            // fallback to Application History Server app page if the application
                            // report was fetched from AHS
                            Log.Debug("Original tracking url is '{}'. Redirecting to AHS app page", original
                                      == null ? "NULL" : original);
                            ProxyUtils.SendRedirect(req, resp, StringHelper.Pjoin(ahsAppPageUrlBase, id.ToString
                                                                                      ()));
                        }
                    }
                    return;
                }
                else
                {
                    if (ProxyUriUtils.GetSchemeFromUrl(original).IsEmpty())
                    {
                        trackingUri = ProxyUriUtils.GetUriFromAMUrl(WebAppUtils.GetHttpSchemePrefix(conf)
                                                                    , original);
                    }
                    else
                    {
                        trackingUri = new URI(original);
                    }
                }
                string runningUser = applicationReport.GetUser();
                if (checkUser && !runningUser.Equals(remoteUser))
                {
                    Log.Info("Asking {} if they want to connect to the " + "app master GUI of {} owned by {}"
                             , remoteUser, appId, runningUser);
                    WarnUserPage(resp, ProxyUriUtils.GetPathAndQuery(id, rest, req.GetQueryString(),
                                                                     true), runningUser, id);
                    return;
                }
                // Append the user-provided path and query parameter to the original
                // tracking url.
                IList <NameValuePair> queryPairs = URLEncodedUtils.Parse(req.GetQueryString(), null
                                                                         );
                UriBuilder builder = UriBuilder.FromUri(trackingUri);
                foreach (NameValuePair pair in queryPairs)
                {
                    builder.QueryParam(pair.GetName(), pair.GetValue());
                }
                URI toFetch_1 = builder.Path(rest).Build();
                Log.Info("{} is accessing unchecked {}" + " which is the app master GUI of {} owned by {}"
                         , remoteUser, toFetch_1, appId, runningUser);
                switch (applicationReport.GetYarnApplicationState())
                {
                case YarnApplicationState.Killed:
                case YarnApplicationState.Finished:
                case YarnApplicationState.Failed:
                {
                    ProxyUtils.SendRedirect(req, resp, toFetch_1.ToString());
                    return;
                }

                default:
                {
                    break;
                }
                }
                // fall out of the switch
                Cookie c_1 = null;
                if (userWasWarned && userApproved)
                {
                    c_1 = MakeCheckCookie(id, true);
                }
                ProxyLink(req, resp, toFetch_1, c_1, GetProxyHost());
            }
            catch (Exception e)
            {
                throw new IOException(e);
            }
        }
Exemple #16
0
 /// <summary>Shuffle specific utils - build string for encoding from URL</summary>
 /// <param name="request"/>
 /// <returns>string for encoding</returns>
 public static string BuildMsgFrom(HttpServletRequest request)
 {
     return(BuildMsgFrom(request.GetRequestURI(), request.GetQueryString(), request.GetLocalPort
                             ()));
 }