Beispiel #1
0
        /// <exception cref="System.Exception"/>
        public virtual void TestUGIAuthMethodInRealUser()
        {
            UserGroupInformation ugi      = UserGroupInformation.GetCurrentUser();
            UserGroupInformation proxyUgi = UserGroupInformation.CreateProxyUser("proxy", ugi
                                                                                 );

            UserGroupInformation.AuthenticationMethod am = UserGroupInformation.AuthenticationMethod
                                                           .Kerberos;
            ugi.SetAuthenticationMethod(am);
            Assert.Equal(am, ugi.GetAuthenticationMethod());
            Assert.Equal(UserGroupInformation.AuthenticationMethod.Proxy,
                         proxyUgi.GetAuthenticationMethod());
            Assert.Equal(am, UserGroupInformation.GetRealAuthenticationMethod
                             (proxyUgi));
            proxyUgi.DoAs(new _PrivilegedExceptionAction_690(am));
            UserGroupInformation proxyUgi2 = new UserGroupInformation(proxyUgi.GetSubject());

            proxyUgi2.SetAuthenticationMethod(UserGroupInformation.AuthenticationMethod.Proxy
                                              );
            Assert.Equal(proxyUgi, proxyUgi2);
            // Equality should work if authMethod is null
            UserGroupInformation realugi   = UserGroupInformation.GetCurrentUser();
            UserGroupInformation proxyUgi3 = UserGroupInformation.CreateProxyUser("proxyAnother"
                                                                                  , realugi);
            UserGroupInformation proxyUgi4 = new UserGroupInformation(proxyUgi3.GetSubject());

            Assert.Equal(proxyUgi3, proxyUgi4);
        }
        /// <exception cref="System.Exception"/>
        public virtual void TestValidProxyUser()
        {
            UserGroupInformation ugi = UserGroupInformation.CreateProxyUser("u1", UserGroupInformation
                                                                            .GetLoginUser());

            ugi.DoAs(new _PrivilegedExceptionAction_135(this));
        }
        /// <exception cref="System.Exception"/>
        public virtual void ___testInvalidProxyUser()
        {
            UserGroupInformation ugi = UserGroupInformation.CreateProxyUser("u2", UserGroupInformation
                                                                            .GetLoginUser());

            ugi.DoAs(new _PrivilegedExceptionAction_147(this));
        }
Beispiel #4
0
        public virtual void TestProxyUserConfiguration()
        {
            MockRM rm = null;

            try
            {
                rm = new MockRM(conf);
                rm.Start();
                // wait for web server starting
                Sharpen.Thread.Sleep(10000);
                UserGroupInformation proxyUser = UserGroupInformation.CreateProxyUser(BarUser.GetShortUserName
                                                                                          (), FooUser);
                try
                {
                    ProxyUsers.GetDefaultImpersonationProvider().Authorize(proxyUser, ipAddress);
                }
                catch (AuthorizationException)
                {
                    // Exception is not expected
                    NUnit.Framework.Assert.Fail();
                }
            }
            finally
            {
                if (rm != null)
                {
                    rm.Stop();
                    rm.Close();
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Get
        /// <see cref="Org.Apache.Hadoop.Security.UserGroupInformation"/>
        /// and possibly the delegation token out of
        /// the request.
        /// </summary>
        /// <param name="context">the ServletContext that is serving this request.</param>
        /// <param name="request">the http request</param>
        /// <param name="conf">configuration</param>
        /// <param name="secureAuthMethod">the AuthenticationMethod used in secure mode.</param>
        /// <param name="tryUgiParameter">Should it try the ugi parameter?</param>
        /// <returns>a new user from the request</returns>
        /// <exception cref="Org.Apache.Hadoop.Security.AccessControlException">if the request has no token
        ///     </exception>
        /// <exception cref="System.IO.IOException"/>
        public static UserGroupInformation GetUGI(ServletContext context, HttpServletRequest
                                                  request, Configuration conf, UserGroupInformation.AuthenticationMethod secureAuthMethod
                                                  , bool tryUgiParameter)
        {
            UserGroupInformation ugi = null;
            string usernameFromQuery = GetUsernameFromQuery(request, tryUgiParameter);
            string doAsUserFromQuery = request.GetParameter(DoAsParam.Name);
            string remoteUser;

            if (UserGroupInformation.IsSecurityEnabled())
            {
                remoteUser = request.GetRemoteUser();
                string tokenString = request.GetParameter(DelegationParameterName);
                if (tokenString != null)
                {
                    // Token-based connections need only verify the effective user, and
                    // disallow proxying to different user.  Proxy authorization checks
                    // are not required since the checks apply to issuing a token.
                    ugi = GetTokenUGI(context, request, tokenString, conf);
                    CheckUsername(ugi.GetShortUserName(), usernameFromQuery);
                    CheckUsername(ugi.GetShortUserName(), doAsUserFromQuery);
                }
                else
                {
                    if (remoteUser == null)
                    {
                        throw new IOException("Security enabled but user not authenticated by filter");
                    }
                }
            }
            else
            {
                // Security's not on, pull from url or use default web user
                remoteUser = (usernameFromQuery == null) ? GetDefaultWebUserName(conf) : usernameFromQuery;
            }
            // not specified in request
            if (ugi == null)
            {
                // security is off, or there's no token
                ugi = UserGroupInformation.CreateRemoteUser(remoteUser);
                CheckUsername(ugi.GetShortUserName(), usernameFromQuery);
                if (UserGroupInformation.IsSecurityEnabled())
                {
                    // This is not necessarily true, could have been auth'ed by user-facing
                    // filter
                    ugi.SetAuthenticationMethod(secureAuthMethod);
                }
                if (doAsUserFromQuery != null)
                {
                    // create and attempt to authorize a proxy user
                    ugi = UserGroupInformation.CreateProxyUser(doAsUserFromQuery, ugi);
                    ProxyUsers.Authorize(ugi, GetRemoteAddr(request));
                }
            }
            if (Log.IsDebugEnabled())
            {
                Log.Debug("getUGI is returning: " + ugi.GetShortUserName());
            }
            return(ugi);
        }
Beispiel #6
0
        public virtual void TestOperationDoAs()
        {
            CreateHttpFSServer();
            UserGroupInformation ugi = UserGroupInformation.CreateProxyUser(HadoopUsersConfTestHelper
                                                                            .GetHadoopUsers()[0], UserGroupInformation.GetCurrentUser());

            ugi.DoAs(new _PrivilegedExceptionAction_928(this));
        }
Beispiel #7
0
        /// <exception cref="System.IO.IOException"/>
        public virtual void TestSecureProxyAuthParamsInUrl()
        {
            Configuration conf = new Configuration();

            // fake turning on security so api thinks it should use tokens
            SecurityUtil.SetAuthenticationMethod(UserGroupInformation.AuthenticationMethod.Kerberos
                                                 , conf);
            UserGroupInformation.SetConfiguration(conf);
            UserGroupInformation ugi = UserGroupInformation.CreateRemoteUser("test-user");

            ugi.SetAuthenticationMethod(UserGroupInformation.AuthenticationMethod.Kerberos);
            ugi = UserGroupInformation.CreateProxyUser("test-proxy-user", ugi);
            UserGroupInformation.SetLoginUser(ugi);
            WebHdfsFileSystem webhdfs = GetWebHdfsFileSystem(ugi, conf);
            Path   fsPath             = new Path("/");
            string tokenString        = webhdfs.GetDelegationToken().EncodeToUrlString();
            // send real+effective
            Uri getTokenUrl = webhdfs.ToUrl(GetOpParam.OP.Getdelegationtoken, fsPath);

            CheckQueryParams(new string[] { GetOpParam.OP.Getdelegationtoken.ToQueryString(),
                                            new UserParam(ugi.GetRealUser().GetShortUserName()).ToString(), new DoAsParam(ugi
                                                                                                                          .GetShortUserName()).ToString() }, getTokenUrl);
            // send real+effective
            Uri renewTokenUrl = webhdfs.ToUrl(PutOpParam.OP.Renewdelegationtoken, fsPath, new
                                              TokenArgumentParam(tokenString));

            CheckQueryParams(new string[] { PutOpParam.OP.Renewdelegationtoken.ToQueryString(
                                                ), new UserParam(ugi.GetRealUser().GetShortUserName()).ToString(), new DoAsParam
                                                (ugi.GetShortUserName()).ToString(), new TokenArgumentParam(tokenString).ToString
                                                () }, renewTokenUrl);
            // send token
            Uri cancelTokenUrl = webhdfs.ToUrl(PutOpParam.OP.Canceldelegationtoken, fsPath, new
                                               TokenArgumentParam(tokenString));

            CheckQueryParams(new string[] { PutOpParam.OP.Canceldelegationtoken.ToQueryString
                                                (), new UserParam(ugi.GetRealUser().GetShortUserName()).ToString(), new DoAsParam
                                                (ugi.GetShortUserName()).ToString(), new TokenArgumentParam(tokenString).ToString
                                                () }, cancelTokenUrl);
            // send token
            Uri fileStatusUrl = webhdfs.ToUrl(GetOpParam.OP.Getfilestatus, fsPath);

            CheckQueryParams(new string[] { GetOpParam.OP.Getfilestatus.ToQueryString(), new
                                            DelegationParam(tokenString).ToString() }, fileStatusUrl);
            // wipe out internal token to simulate auth always required
            webhdfs.SetDelegationToken(null);
            // send real+effective
            cancelTokenUrl = webhdfs.ToUrl(PutOpParam.OP.Canceldelegationtoken, fsPath, new TokenArgumentParam
                                               (tokenString));
            CheckQueryParams(new string[] { PutOpParam.OP.Canceldelegationtoken.ToQueryString
                                                (), new UserParam(ugi.GetRealUser().GetShortUserName()).ToString(), new DoAsParam
                                                (ugi.GetShortUserName()).ToString(), new TokenArgumentParam(tokenString).ToString
                                                () }, cancelTokenUrl);
            // send real+effective
            fileStatusUrl = webhdfs.ToUrl(GetOpParam.OP.Getfilestatus, fsPath);
            CheckQueryParams(new string[] { GetOpParam.OP.Getfilestatus.ToQueryString(), new
                                            UserParam(ugi.GetRealUser().GetShortUserName()).ToString(), new DoAsParam(ugi.GetShortUserName
                                                                                                                          ()).ToString() }, fileStatusUrl);
        }
Beispiel #8
0
        /// <exception cref="System.Exception"/>
        public virtual void TestEqualsWithRealUser()
        {
            UserGroupInformation realUgi1 = UserGroupInformation.CreateUserForTesting("RealUser"
                                                                                      , GroupNames);
            UserGroupInformation proxyUgi1 = UserGroupInformation.CreateProxyUser(UserName, realUgi1
                                                                                  );
            UserGroupInformation proxyUgi2 = new UserGroupInformation(proxyUgi1.GetSubject());
            UserGroupInformation remoteUgi = UserGroupInformation.CreateRemoteUser(UserName);

            Assert.Equal(proxyUgi1, proxyUgi2);
            NUnit.Framework.Assert.IsFalse(remoteUgi.Equals(proxyUgi1));
        }
Beispiel #9
0
        public virtual void TestCreateProxyUser()
        {
            // ensure that doAs works correctly
            UserGroupInformation realUserUgi = UserGroupInformation.CreateRemoteUser(RealUserName
                                                                                     );
            UserGroupInformation proxyUserUgi = UserGroupInformation.CreateProxyUser(ProxyUserName
                                                                                     , realUserUgi);
            UserGroupInformation curUGI = proxyUserUgi.DoAs(new _PrivilegedExceptionAction_122
                                                                ());

            Assert.Equal(ProxyUserName + " (auth:PROXY) via " + RealUserName
                         + " (auth:SIMPLE)", curUGI.ToString());
        }
Beispiel #10
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Javax.Servlet.ServletException"/>
        protected override void DoFilter(FilterChain filterChain, HttpServletRequest request
                                         , HttpServletResponse response)
        {
            bool requestCompleted          = false;
            UserGroupInformation ugi       = null;
            AuthenticationToken  authToken = (AuthenticationToken)request.GetUserPrincipal();

            if (authToken != null && authToken != AuthenticationToken.Anonymous)
            {
                // if the request was authenticated because of a delegation token,
                // then we ignore proxyuser (this is the same as the RPC behavior).
                ugi = (UserGroupInformation)request.GetAttribute(DelegationTokenAuthenticationHandler
                                                                 .DelegationTokenUgiAttribute);
                if (ugi == null)
                {
                    string realUser = request.GetUserPrincipal().GetName();
                    ugi = UserGroupInformation.CreateRemoteUser(realUser, handlerAuthMethod);
                    string doAsUser = GetDoAs(request);
                    if (doAsUser != null)
                    {
                        ugi = UserGroupInformation.CreateProxyUser(doAsUser, ugi);
                        try
                        {
                            ProxyUsers.Authorize(ugi, request.GetRemoteHost());
                        }
                        catch (AuthorizationException ex)
                        {
                            HttpExceptionUtils.CreateServletExceptionResponse(response, HttpServletResponse.ScForbidden
                                                                              , ex);
                            requestCompleted = true;
                        }
                    }
                }
                UgiTl.Set(ugi);
            }
            if (!requestCompleted)
            {
                UserGroupInformation ugiF = ugi;
                try
                {
                    request = new _HttpServletRequestWrapper_269(this, ugiF, request);
                    base.DoFilter(filterChain, request, response);
                }
                finally
                {
                    UgiTl.Remove();
                }
            }
        }
Beispiel #11
0
        public virtual void TestGetRealAuthenticationMethod()
        {
            UserGroupInformation ugi = UserGroupInformation.CreateRemoteUser("user1");

            ugi.SetAuthenticationMethod(UserGroupInformation.AuthenticationMethod.Simple);
            Assert.Equal(UserGroupInformation.AuthenticationMethod.Simple,
                         ugi.GetAuthenticationMethod());
            Assert.Equal(UserGroupInformation.AuthenticationMethod.Simple,
                         ugi.GetRealAuthenticationMethod());
            ugi = UserGroupInformation.CreateProxyUser("user2", ugi);
            Assert.Equal(UserGroupInformation.AuthenticationMethod.Proxy,
                         ugi.GetAuthenticationMethod());
            Assert.Equal(UserGroupInformation.AuthenticationMethod.Simple,
                         ugi.GetRealAuthenticationMethod());
        }
Beispiel #12
0
        /// <exception cref="System.IO.IOException"/>
        public virtual void TestSimpleProxyAuthParamsInUrl()
        {
            Configuration        conf = new Configuration();
            UserGroupInformation ugi  = UserGroupInformation.CreateRemoteUser("test-user");

            ugi = UserGroupInformation.CreateProxyUser("test-proxy-user", ugi);
            UserGroupInformation.SetLoginUser(ugi);
            WebHdfsFileSystem webhdfs = GetWebHdfsFileSystem(ugi, conf);
            Path fsPath = new Path("/");
            // send real+effective
            Uri fileStatusUrl = webhdfs.ToUrl(GetOpParam.OP.Getfilestatus, fsPath);

            CheckQueryParams(new string[] { GetOpParam.OP.Getfilestatus.ToQueryString(), new
                                            UserParam(ugi.GetRealUser().GetShortUserName()).ToString(), new DoAsParam(ugi.GetShortUserName
                                                                                                                          ()).ToString() }, fileStatusUrl);
        }
Beispiel #13
0
        /// <summary>This method uses the currentUser, and real user to create a proxy</summary>
        /// <param name="effectiveUser">The user who is being proxied by the real user</param>
        /// <param name="realUser">The actual user who does the command</param>
        /// <returns>Proxy UserGroupInformation</returns>
        /// <exception cref="System.IO.IOException">If proxying fails</exception>
        internal virtual UserGroupInformation GetUserGroupInformation(string effectiveUser
                                                                      , UserGroupInformation realUser)
        {
            Preconditions.CheckNotNull(effectiveUser);
            Preconditions.CheckNotNull(realUser);
            realUser.CheckTGTAndReloginFromKeytab();
            UserGroupInformation ugi = UserGroupInformation.CreateProxyUser(effectiveUser, realUser
                                                                            );

            if (Log.IsDebugEnabled())
            {
                Log.Debug(string.Format("Created ugi:" + " %s for username: %s", ugi, effectiveUser
                                        ));
            }
            return(ugi);
        }
Beispiel #14
0
        /// <exception cref="System.Exception"/>
        private void TestDelegationTokenWithinDoAs(Type fileSystemClass, bool proxyUser)
        {
            Configuration conf = new Configuration();

            conf.Set("hadoop.security.authentication", "kerberos");
            UserGroupInformation.SetConfiguration(conf);
            UserGroupInformation.LoginUserFromKeytab("client", "/Users/tucu/tucu.keytab");
            UserGroupInformation ugi = UserGroupInformation.GetLoginUser();

            if (proxyUser)
            {
                ugi = UserGroupInformation.CreateProxyUser("foo", ugi);
            }
            conf = new Configuration();
            UserGroupInformation.SetConfiguration(conf);
            ugi.DoAs(new _PrivilegedExceptionAction_248(this, fileSystemClass));
        }
        /// <summary>Get the username encoded in the token identifier</summary>
        /// <returns>the username or owner</returns>
        public override UserGroupInformation GetUser()
        {
            if ((owner == null) || (owner.ToString().IsEmpty()))
            {
                return(null);
            }
            UserGroupInformation realUgi;
            UserGroupInformation ugi;

            if ((realUser == null) || (realUser.ToString().IsEmpty()) || realUser.Equals(owner
                                                                                         ))
            {
                ugi = realUgi = UserGroupInformation.CreateRemoteUser(owner.ToString());
            }
            else
            {
                realUgi = UserGroupInformation.CreateRemoteUser(realUser.ToString());
                ugi     = UserGroupInformation.CreateProxyUser(owner.ToString(), realUgi);
            }
            realUgi.SetAuthenticationMethod(UserGroupInformation.AuthenticationMethod.Token);
            return(ugi);
        }
        /// <exception cref="System.IO.IOException"/>
        internal virtual UserGroupInformation Ugi()
        {
            if (UserGroupInformation.IsSecurityEnabled())
            {
                return(TokenUGI());
            }
            string usernameFromQuery = @params.UserName();
            string doAsUserFromQuery = @params.DoAsUser();
            string remoteUser        = usernameFromQuery == null?JspHelper.GetDefaultWebUserName(@params
                                                                                                 .Conf()) : usernameFromQuery;

            // not specified in
            // request
            UserGroupInformation ugi = UserGroupInformation.CreateRemoteUser(remoteUser);

            JspHelper.CheckUsername(ugi.GetShortUserName(), usernameFromQuery);
            if (doAsUserFromQuery != null)
            {
                // create and attempt to authorize a proxy user
                ugi = UserGroupInformation.CreateProxyUser(doAsUserFromQuery, ugi);
            }
            return(ugi);
        }
Beispiel #17
0
        public static UserGroupInformation GetUgi(IpcConnectionContextProtos.UserInformationProto
                                                  userInfo)
        {
            UserGroupInformation ugi = null;
            string effectiveUser     = userInfo.HasEffectiveUser() ? userInfo.GetEffectiveUser() :
                                       null;
            string realUser = userInfo.HasRealUser() ? userInfo.GetRealUser() : null;

            if (effectiveUser != null)
            {
                if (realUser != null)
                {
                    UserGroupInformation realUserUgi = UserGroupInformation.CreateRemoteUser(realUser
                                                                                             );
                    ugi = UserGroupInformation.CreateProxyUser(effectiveUser, realUserUgi);
                }
                else
                {
                    ugi = UserGroupInformation.CreateRemoteUser(effectiveUser);
                }
            }
            return(ugi);
        }
Beispiel #18
0
 /// <exception cref="System.IO.IOException"/>
 protected internal virtual UserGroupInformation GetUGI(string user)
 {
     return(UserGroupInformation.CreateProxyUser(user, UserGroupInformation.GetLoginUser
                                                     ()));
 }
Beispiel #19
0
        /// <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);
        }
        public virtual void TestDelegationTokenOperations()
        {
            TimelineClient httpUserClient = KerberosTestUtils.DoAs(HttpUser + "/localhost", new
                                                                   _Callable_221(this));
            UserGroupInformation httpUser = KerberosTestUtils.DoAs(HttpUser + "/localhost", new
                                                                   _Callable_228());

            // Let HTTP user to get the delegation for itself
            Org.Apache.Hadoop.Security.Token.Token <TimelineDelegationTokenIdentifier> token =
                httpUserClient.GetDelegationToken(httpUser.GetShortUserName());
            NUnit.Framework.Assert.IsNotNull(token);
            TimelineDelegationTokenIdentifier tDT = token.DecodeIdentifier();

            NUnit.Framework.Assert.IsNotNull(tDT);
            NUnit.Framework.Assert.AreEqual(new Text(HttpUser), tDT.GetOwner());
            // Renew token
            NUnit.Framework.Assert.IsFalse(token.GetService().ToString().IsEmpty());
            // Renew the token from the token service address
            long renewTime1 = httpUserClient.RenewDelegationToken(token);

            Sharpen.Thread.Sleep(100);
            token.SetService(new Text());
            NUnit.Framework.Assert.IsTrue(token.GetService().ToString().IsEmpty());
            // If the token service address is not avaiable, it still can be renewed
            // from the configured address
            long renewTime2 = httpUserClient.RenewDelegationToken(token);

            NUnit.Framework.Assert.IsTrue(renewTime1 < renewTime2);
            // Cancel token
            NUnit.Framework.Assert.IsTrue(token.GetService().ToString().IsEmpty());
            // If the token service address is not avaiable, it still can be canceled
            // from the configured address
            httpUserClient.CancelDelegationToken(token);
            // Renew should not be successful because the token is canceled
            try
            {
                httpUserClient.RenewDelegationToken(token);
                NUnit.Framework.Assert.Fail();
            }
            catch (Exception e)
            {
                NUnit.Framework.Assert.IsTrue(e.Message.Contains("Renewal request for unknown token"
                                                                 ));
            }
            // Let HTTP user to get the delegation token for FOO user
            UserGroupInformation fooUgi = UserGroupInformation.CreateProxyUser(FooUser, httpUser
                                                                               );
            TimelineClient fooUserClient = fooUgi.DoAs(new _PrivilegedExceptionAction_272(this
                                                                                          ));

            token = fooUserClient.GetDelegationToken(httpUser.GetShortUserName());
            NUnit.Framework.Assert.IsNotNull(token);
            tDT = token.DecodeIdentifier();
            NUnit.Framework.Assert.IsNotNull(tDT);
            NUnit.Framework.Assert.AreEqual(new Text(FooUser), tDT.GetOwner());
            NUnit.Framework.Assert.AreEqual(new Text(HttpUser), tDT.GetRealUser());
            // Renew token as the renewer
            Org.Apache.Hadoop.Security.Token.Token <TimelineDelegationTokenIdentifier> tokenToRenew
                       = token;
            renewTime1 = httpUserClient.RenewDelegationToken(tokenToRenew);
            renewTime2 = httpUserClient.RenewDelegationToken(tokenToRenew);
            NUnit.Framework.Assert.IsTrue(renewTime1 < renewTime2);
            // Cancel token
            NUnit.Framework.Assert.IsFalse(tokenToRenew.GetService().ToString().IsEmpty());
            // Cancel the token from the token service address
            fooUserClient.CancelDelegationToken(tokenToRenew);
            // Renew should not be successful because the token is canceled
            try
            {
                httpUserClient.RenewDelegationToken(tokenToRenew);
                NUnit.Framework.Assert.Fail();
            }
            catch (Exception e)
            {
                NUnit.Framework.Assert.IsTrue(e.Message.Contains("Renewal request for unknown token"
                                                                 ));
            }
            // Let HTTP user to get the delegation token for BAR user
            UserGroupInformation barUgi = UserGroupInformation.CreateProxyUser(BarUser, httpUser
                                                                               );
            TimelineClient barUserClient = barUgi.DoAs(new _PrivilegedExceptionAction_309(this
                                                                                          ));

            try
            {
                barUserClient.GetDelegationToken(httpUser.GetShortUserName());
                NUnit.Framework.Assert.Fail();
            }
            catch (Exception e)
            {
                NUnit.Framework.Assert.IsTrue(e.InnerException is AuthorizationException || e.InnerException
                                              is AuthenticationException);
            }
        }