Ejemplo n.º 1
0
		protected virtual ServletFacesContext GetFacesContext (FacesContextFactory facesContextFactory,
																	ServletContext servletContext,
																	ServletRequest servletRequest,
																	ServletResponse servletResponse,
																	Lifecycle lifecycle,
																	HttpContext httpContext,
																	string executionFilePath) {
			return ServletFacesContext.GetFacesContext (facesContextFactory, servletContext, servletRequest, servletResponse, lifecycle, httpContext, executionFilePath);
		}
Ejemplo n.º 2
0
		public static ServletFacesContext GetFacesContext (FacesContextFactory facesContextFactory,
																	ServletContext servletContext,
																	ServletRequest servletRequest,
																	ServletResponse servletResponse,
																	Lifecycle lifecycle,
																	HttpContext httpContext,
																	string executionFilePath) {
			FacesContext oldFacesContex = FacesContext.getCurrentInstance ();
			FacesContext wrappedFacesContex = facesContextFactory.getFacesContext (servletContext, servletRequest, servletResponse, lifecycle);
			ExternalContext externalContext = new ServletExternalContext (wrappedFacesContex.getExternalContext (), httpContext, executionFilePath);
			ServletFacesContext context = new ServletFacesContext (wrappedFacesContex, externalContext, httpContext, oldFacesContex);
			return context;
		}
Ejemplo n.º 3
0
        public virtual void TestGetUgi()
        {
            conf.Set(DFSConfigKeys.FsDefaultNameKey, "hdfs://localhost:4321/");
            HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>();
            ServletContext     context = Org.Mockito.Mockito.Mock <ServletContext>();
            string             user    = "******";
            Text userText = new Text(user);
            DelegationTokenIdentifier dtId = new DelegationTokenIdentifier(userText, userText
                                                                           , null);

            Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier> token = new Org.Apache.Hadoop.Security.Token.Token
                                                                                       <DelegationTokenIdentifier>(dtId, new TestJspHelper.DummySecretManager(0, 0, 0,
                                                                                                                                                              0));
            string tokenString = token.EncodeToUrlString();

            Org.Mockito.Mockito.When(request.GetParameter(JspHelper.DelegationParameterName))
            .ThenReturn(tokenString);
            Org.Mockito.Mockito.When(request.GetRemoteUser()).ThenReturn(user);
            //Test attribute in the url to be used as service in the token.
            Org.Mockito.Mockito.When(request.GetParameter(JspHelper.NamenodeAddress)).ThenReturn
                ("1.1.1.1:1111");
            conf.Set(DFSConfigKeys.HadoopSecurityAuthentication, "kerberos");
            UserGroupInformation.SetConfiguration(conf);
            VerifyServiceInToken(context, request, "1.1.1.1:1111");
            //Test attribute name.node.address
            //Set the nnaddr url parameter to null.
            Org.Mockito.Mockito.When(request.GetParameter(JspHelper.NamenodeAddress)).ThenReturn
                (null);
            IPEndPoint addr = new IPEndPoint("localhost", 2222);

            Org.Mockito.Mockito.When(context.GetAttribute(NameNodeHttpServer.NamenodeAddressAttributeKey
                                                          )).ThenReturn(addr);
            VerifyServiceInToken(context, request, addr.Address.GetHostAddress() + ":2222");
            //Test service already set in the token
            token.SetService(new Text("3.3.3.3:3333"));
            tokenString = token.EncodeToUrlString();
            //Set the name.node.address attribute in Servlet context to null
            Org.Mockito.Mockito.When(context.GetAttribute(NameNodeHttpServer.NamenodeAddressAttributeKey
                                                          )).ThenReturn(null);
            Org.Mockito.Mockito.When(request.GetParameter(JspHelper.DelegationParameterName))
            .ThenReturn(tokenString);
            VerifyServiceInToken(context, request, "3.3.3.3:3333");
        }
Ejemplo n.º 4
0
		public static string GetApplicationPhysicalPath (ServletContext context) {
			string path = String.Empty;

			string appDir = context.getInitParameter(IAppDomainConfig.APP_DIR_NAME);
			if (appDir != null) {
				try {
					if (Directory.Exists(appDir))
						path = appDir;
				}
				catch (Exception e) {
					Trace.WriteLine (e.Message + appDir + "is invalid or unaccessible." +
						" If " + appDir + " really exists, check your security permissions");
				}
			}
			if (path.Length == 0)
				path = GetApplicationRealPath (context);

			return path;
		}
Ejemplo n.º 5
0
        public void ProcessRequest(HttpContext context)
        {
            ServletWorkerRequest wr             = (ServletWorkerRequest)((IServiceProvider)context).GetService(typeof(HttpWorkerRequest));
            ServletContext       servletContext = wr.GetContext();
            HttpServletRequest   request        = wr.ServletRequest;
            HttpServletResponse  response       = wr.ServletResponse;

            ServletFacesContext facesContext = GetFacesContext(_facesContextFactory, servletContext, request, response, _lifecycle, context, _executionFilePath);

            try {
                try {
                    try {
                        Trace.WriteLine("FacesPageHandler: before execute");
                        _lifecycle.execute(facesContext);
                        Trace.WriteLine("FacesPageHandler: after execute");
                    }
                    finally {
                        UIViewRoot viewRoot = facesContext.getViewRoot();
                        if (viewRoot != null && viewRoot.getChildCount() > 0)
                        {
                            _page = (Page)viewRoot.getChildren().get(0);
                        }
                    }
                    Trace.WriteLine("FacesPageHandler: before render");
                    SetupResponseWriter(facesContext, response.getContentType(), response.getCharacterEncoding());
                    _lifecycle.render(facesContext);
                    Trace.WriteLine("FacesPageHandler: after render");
                }
                catch (FacesException fex) {
                    Exception inner = fex.InnerException;
                    if (inner != null)
                    {
                        TypeUtils.Throw(inner);
                    }
                    throw;
                }
            }
            finally {
                facesContext.release();
            }
        }
Ejemplo n.º 6
0
        /// <summary>Handle fsck request</summary>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                      )
        {
            IDictionary <string, string[]> pmap = request.GetParameterMap();
            PrintWriter @out          = response.GetWriter();
            IPAddress   remoteAddress = Sharpen.Extensions.GetAddressByName(request.GetRemoteAddr
                                                                                ());
            ServletContext       context = GetServletContext();
            Configuration        conf    = NameNodeHttpServer.GetConfFromContext(context);
            UserGroupInformation ugi     = GetUGI(request, conf);

            try
            {
                ugi.DoAs(new _PrivilegedExceptionAction_58(context, conf, pmap, @out, remoteAddress
                                                           ));
            }
            catch (Exception e)
            {
                response.SendError(400, e.Message);
            }
        }
Ejemplo n.º 7
0
		public static string GetApplicationRealPath (ServletContext context, string appVirtualPath)
		{
			string realFs = context.getInitParameter (J2EEConsts.FILESYSTEM_ACCESS);
			if (realFs == null || realFs == J2EEConsts.ACCESS_FULL) {
				try {
					string realPath = context.getRealPath (appVirtualPath);
					if (!String.IsNullOrEmpty (realPath)) {
						if (!String.IsNullOrEmpty (appVirtualPath) &&
							appVirtualPath [appVirtualPath.Length - 1] == '/')
							if (realPath [realPath.Length - 1] != Path.DirectorySeparatorChar)
								realPath += Path.DirectorySeparatorChar;

						return realPath;
					}
				}
				catch (Exception e) {
					Trace.WriteLine (e.ToString());
				}
			}
			return IAppDomainConfig.WAR_ROOT_SYMBOL + appVirtualPath;
		}
Ejemplo n.º 8
0
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
        {
            UserGroupInformation ugi;
            ServletContext       context = GetServletContext();
            Configuration        conf    = NameNodeHttpServer.GetConfFromContext(context);

            try
            {
                ugi = GetUGI(req, conf);
            }
            catch (IOException ioe)
            {
                Log.Info("Request for token received with no authentication from " + req.GetRemoteAddr
                             (), ioe);
                resp.SendError(HttpServletResponse.ScForbidden, "Unable to identify or authenticate user"
                               );
                return;
            }
            NameNode nn          = NameNodeHttpServer.GetNameNodeFromContext(context);
            string   tokenString = req.GetParameter(Token);

            if (tokenString == null)
            {
                resp.SendError(HttpServletResponse.ScMultipleChoices, "Token to renew not specified"
                               );
            }
            Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier> token = new Org.Apache.Hadoop.Security.Token.Token
                                                                                       <DelegationTokenIdentifier>();
            token.DecodeFromUrlString(tokenString);
            try
            {
                ugi.DoAs(new _PrivilegedExceptionAction_70(nn, token));
            }
            catch (Exception e)
            {
                Log.Info("Exception while cancelling token. Re-throwing. ", e);
                resp.SendError(HttpServletResponse.ScInternalServerError, e.Message);
            }
        }
Ejemplo n.º 9
0
            }                                                          // For Java deserialization

            public ServletSessionStateItemCollection(HttpContext context)
                : this()
            {
                _items         = new SessionStateItemCollection();
                _staticObjects = new HttpStaticObjectsCollection();

                if (context != null)
                {
                    ServletContext servletContext     = J2EEUtils.GetWorkerRequest(context).GetContext();
                    string         sessionPersistance = servletContext.getInitParameter(J2EEConsts.Enable_Session_Persistency);
                    if (sessionPersistance != null)
                    {
                        try {
                            _needSessionPersistence = Boolean.Parse(sessionPersistance);
                        }
                        catch (Exception) {
                            _needSessionPersistence = false;
                            Debug.WriteLine("EnableSessionPersistency init param's value is invalid. the value is " + sessionPersistance);
                        }
                    }
                }
            }
        public override void init(ServletConfig config)
        {
            super.init(config);

            _context = config.getServletContext();
            _cache   = new LruCache <String, CacheEntry>(1024);

            _pwd = new FilePath(_context.getRealPath("/"));

            string mode
                = System.getProperty("com.google.appengine.tools.development.ApplicationPreparationMode");

            bool isGsDisabled = "true".equals(mode);

            if (!isGsDisabled)
            {
                string iniPath = getInitParameter("ini-file");

                if (iniPath != null)
                {
                    string realPath = _context.getRealPath(iniPath);

                    // don't call Quercus.init() as that will load all the modules for calling
                    // from PHP code, which we don't use nor want
                    GoogleQuercus quercus = new GoogleQuercus();
                    quercus.setIniFile(_pwd.lookup(realPath));

                    _gsBucket = quercus.getIniString("google.cloud_storage_bucket");

                    if (_gsBucket != null)
                    {
                        _pwd = new GoogleMergePath(_pwd, _gsBucket, true);
                    }
                }
            }

            log.log(Level.INFO, L.l("{0} initialized with bucket={1},pwd={2}",
                                    getClass().getSimpleName(), _gsBucket, _pwd.getUserPath()));
        }
Ejemplo n.º 11
0
        private static IPEndPoint GetNNServiceAddress(ServletContext context, HttpServletRequest
                                                      request)
        {
            string     namenodeAddressInUrl = request.GetParameter(NamenodeAddress);
            IPEndPoint namenodeAddress      = null;

            if (namenodeAddressInUrl != null)
            {
                namenodeAddress = NetUtils.CreateSocketAddr(namenodeAddressInUrl);
            }
            else
            {
                if (context != null)
                {
                    namenodeAddress = NameNodeHttpServer.GetNameNodeAddressFromContext(context);
                }
            }
            if (namenodeAddress != null)
            {
                return(namenodeAddress);
            }
            return(null);
        }
Ejemplo n.º 12
0
        public override string MapPath(string virtualPath)
        {
            if (virtualPath == null)
            {
                throw new ArgumentNullException("virtualPath");
            }

            ServletContext context = GetContext();

            string contextPath = GetAppPath();

            if ((virtualPath.Length > contextPath.Length && virtualPath [contextPath.Length] != '/') ||
                string.Compare(contextPath, 0, virtualPath, 0, contextPath.Length, StringComparison.OrdinalIgnoreCase) != 0)
            {
                for (int appVirtualPathIndex = 0; appVirtualPathIndex > 0 && virtualPath.Length > appVirtualPathIndex;)
                {
                    appVirtualPathIndex = virtualPath.IndexOf('/', appVirtualPathIndex + 1);
                    string crossContextPath = appVirtualPathIndex > 0 ?
                                              virtualPath.Remove(appVirtualPathIndex) : virtualPath;
                    ServletContext other = context.getContext(crossContextPath);
                    if (other != null)
                    {
                        string appVirtualPath = appVirtualPathIndex > 0 ?
                                                virtualPath.Substring(appVirtualPathIndex) : String.Empty;
                        return(other.getRealPath(appVirtualPath));
                    }
                }

                throw new HttpException(
                          String.Format("MapPath: Mapping across applications is not allowed. ApplicationPath is '{0}', VirtualPath is '{1}'.",
                                        contextPath, virtualPath));
            }

            string thisAppVirtualPath = virtualPath.Length > contextPath.Length ? virtualPath.Substring(contextPath.Length) : String.Empty;

            return(J2EEUtils.GetApplicationRealPath(context, thisAppVirtualPath));
        }
Ejemplo n.º 13
0
        public KeyValueMergedCollection(HttpContext hc, NameValueCollection wrapped)
            : base(wrapped)
        {
            _wrapped = wrapped;

            ServletConfig config = (ServletConfig)AppDomain.CurrentDomain.GetData(vmw.common.IAppDomainConfig.SERVLET_CONFIG);

            if (config != null)
            {
                ServletContext context = config.getServletContext();

                for (java.util.Enumeration e = context.getInitParameterNames(); e.hasMoreElements();)
                {
                    string key = (string)e.nextElement();
                    Set(key, context.getInitParameter(key));
                }

                for (java.util.Enumeration e = config.getInitParameterNames(); e.hasMoreElements();)
                {
                    string key = (string)e.nextElement();
                    Set(key, config.getInitParameter(key));
                }
            }
        }
Ejemplo n.º 14
0
 /// <exception cref="Javax.Servlet.ServletException"/>
 /// <exception cref="System.IO.IOException"/>
 protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                               )
 {
     try
     {
         ServletContext context = GetServletContext();
         FSImage        nnImage = NameNodeHttpServer.GetFsImageFromContext(context);
         ImageServlet.GetImageParams parsedParams = new ImageServlet.GetImageParams(request
                                                                                    , response);
         Configuration   conf    = (Configuration)context.GetAttribute(JspHelper.CurrentConf);
         NameNodeMetrics metrics = NameNode.GetNameNodeMetrics();
         ValidateRequest(context, conf, request, response, nnImage, parsedParams.GetStorageInfoString
                             ());
         UserGroupInformation.GetCurrentUser().DoAs(new _PrivilegedExceptionAction_98(parsedParams
                                                                                      , nnImage, metrics, response, conf));
     }
     catch (Exception t)
     {
         // Metrics non-null only when used inside name node
         // Metrics non-null only when used inside name node
         // Potential race where the file was deleted while we were in the
         // process of setting headers!
         // It's possible the file could be deleted after this point, but
         // we've already opened the 'fis' stream.
         // It's also possible length could change, but this would be
         // detected by the client side as an inaccurate length header.
         // send file
         string errMsg = "GetImage failed. " + StringUtils.StringifyException(t);
         response.SendError(HttpServletResponse.ScGone, errMsg);
         throw new IOException(errMsg);
     }
     finally
     {
         response.GetOutputStream().Close();
     }
 }
Ejemplo n.º 15
0
		public static void DestroyRuntime (ServletContext context, IJDBCDriverDeregisterer evidence) {
			AppDomain servletDomain = (AppDomain) context.getAttribute (J2EEConsts.APP_DOMAIN);
			if (servletDomain == null)
				return;

			try {
				[email protected] (servletDomain);
				Debug.WriteLine ("Destroy of GhHttpServlet");
				HttpRuntime.Close ();
				[email protected] (evidence);
				context.removeAttribute (J2EEConsts.APP_DOMAIN);
				try {
					FactoryFinder.releaseFactories ();
				}
				catch (FacesException) { }

				java.lang.ClassLoader appClassLoader = vmw.common.TypeUtils.ToClass (evidence).getClassLoader ();

				IJDBCDriverDeregisterer dereg = evidence;

				java.util.Enumeration en = java.sql.DriverManager.getDrivers ();
				while (en.hasMoreElements ()) {
					Object o = en.nextElement ();
					if (vmw.common.TypeUtils.ToClass (o).getClassLoader () == appClassLoader)
						dereg.DeregisterDriver ((java.sql.Driver) o);
				}

				java.lang.Thread.currentThread ().setContextClassLoader (null);
			}
			catch (Exception e) {
				Debug.WriteLine (String.Format ("ERROR in Servlet Destroy {0},{1}", e.GetType (), e.Message));
				Debug.WriteLine (e.StackTrace);
			}
			finally {
				[email protected] ();
			}
		}
Ejemplo n.º 16
0
 // Expected
 public override void Init(Properties config, ServletContext servletContext, long
                           tokenValidity)
 {
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Writes an explanatory message and a stack trace
 /// for a given <code>Throwable</code> exception
 /// to the servlet log file, prepended by the servlet's name.
 /// See {@link ServletContext#Log(String, Throwable)}.
 /// </summary>
 /// <param name="message">a string that describes the error or exception</param>
 /// <param name="t">the error or exception</param>
 public void Log(string message, Exception t)
 {
     ServletContext.Log(ServletName + ": " + message, t);
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Writes the specified message to a servlet log file, prepended by the
 /// servlet's name.  See {@link ServletContext#Log(string)}.
 /// </summary>
 /// <param name="msg">a string specifying the message to be written to the log file</param>
 public void Log(string msg)
 {
     ServletContext.Log(ServletName + ": " + msg);
 }
Ejemplo n.º 19
0
 /// <summary>Initialize the SignerSecretProvider</summary>
 /// <param name="config">configuration properties</param>
 /// <param name="servletContext">servlet context</param>
 /// <param name="tokenValidity">The amount of time a token is valid for</param>
 /// <exception cref="System.Exception"/>
 public abstract void Init(Properties config, ServletContext servletContext, long
                           tokenValidity);
Ejemplo n.º 20
0
 public static IPEndPoint GetNameNodeAddressFromContext(ServletContext context)
 {
     return((IPEndPoint)context.GetAttribute(NamenodeAddressAttributeKey));
 }
Ejemplo n.º 21
0
        /// <exception cref="System.IO.IOException"/>
        public static Journal GetJournalFromContext(ServletContext context, string jid)
        {
            JournalNode jn = (JournalNode)context.GetAttribute(JnAttributeKey);

            return(jn.GetOrCreateJournal(jid));
        }
Ejemplo n.º 22
0
 public static NameNode GetNameNodeFromContext(ServletContext context)
 {
     return((NameNode)context.GetAttribute(NamenodeAttributeKey));
 }
Ejemplo n.º 23
0
 internal static Configuration GetConfFromContext(ServletContext context)
 {
     return((Configuration)context.GetAttribute(JspHelper.CurrentConf));
 }
Ejemplo n.º 24
0
        public virtual void TestGetProxyUgi()
        {
            conf.Set(DFSConfigKeys.FsDefaultNameKey, "hdfs://localhost:4321/");
            ServletContext context  = Org.Mockito.Mockito.Mock <ServletContext>();
            string         realUser = "******";
            string         user     = "******";

            conf.Set(DFSConfigKeys.HadoopSecurityAuthentication, "kerberos");
            conf.Set(DefaultImpersonationProvider.GetTestProvider().GetProxySuperuserGroupConfKey
                         (realUser), "*");
            conf.Set(DefaultImpersonationProvider.GetTestProvider().GetProxySuperuserIpConfKey
                         (realUser), "*");
            ProxyUsers.RefreshSuperUserGroupsConfiguration(conf);
            UserGroupInformation.SetConfiguration(conf);
            UserGroupInformation ugi;
            HttpServletRequest   request;

            // have to be auth-ed with remote user
            request = GetMockRequest(null, null, user);
            try
            {
                JspHelper.GetUGI(context, request, conf);
                NUnit.Framework.Assert.Fail("bad request allowed");
            }
            catch (IOException ioe)
            {
                NUnit.Framework.Assert.AreEqual("Security enabled but user not authenticated by filter"
                                                , ioe.Message);
            }
            request = GetMockRequest(null, realUser, user);
            try
            {
                JspHelper.GetUGI(context, request, conf);
                NUnit.Framework.Assert.Fail("bad request allowed");
            }
            catch (IOException ioe)
            {
                NUnit.Framework.Assert.AreEqual("Security enabled but user not authenticated by filter"
                                                , ioe.Message);
            }
            // proxy ugi for user via remote user
            request = GetMockRequest(realUser, null, user);
            ugi     = JspHelper.GetUGI(context, request, conf);
            NUnit.Framework.Assert.IsNotNull(ugi.GetRealUser());
            NUnit.Framework.Assert.AreEqual(ugi.GetRealUser().GetShortUserName(), realUser);
            NUnit.Framework.Assert.AreEqual(ugi.GetShortUserName(), user);
            CheckUgiFromAuth(ugi);
            // proxy ugi for user vi a remote user = real user
            request = GetMockRequest(realUser, realUser, user);
            ugi     = JspHelper.GetUGI(context, request, conf);
            NUnit.Framework.Assert.IsNotNull(ugi.GetRealUser());
            NUnit.Framework.Assert.AreEqual(ugi.GetRealUser().GetShortUserName(), realUser);
            NUnit.Framework.Assert.AreEqual(ugi.GetShortUserName(), user);
            CheckUgiFromAuth(ugi);
            // proxy ugi for user via remote user != real user
            request = GetMockRequest(realUser, user, user);
            try
            {
                JspHelper.GetUGI(context, request, conf);
                NUnit.Framework.Assert.Fail("bad request allowed");
            }
            catch (IOException ioe)
            {
                NUnit.Framework.Assert.AreEqual("Usernames not matched: name=" + user + " != expected="
                                                + realUser, ioe.Message);
            }
            // try to get get a proxy user with unauthorized user
            try
            {
                request = GetMockRequest(user, null, realUser);
                JspHelper.GetUGI(context, request, conf);
                NUnit.Framework.Assert.Fail("bad proxy request allowed");
            }
            catch (AuthorizationException ae)
            {
                NUnit.Framework.Assert.AreEqual("User: "******" is not allowed to impersonate "
                                                + realUser, ae.Message);
            }
            try
            {
                request = GetMockRequest(user, user, realUser);
                JspHelper.GetUGI(context, request, conf);
                NUnit.Framework.Assert.Fail("bad proxy request allowed");
            }
            catch (AuthorizationException ae)
            {
                NUnit.Framework.Assert.AreEqual("User: "******" is not allowed to impersonate "
                                                + realUser, ae.Message);
            }
        }
Ejemplo n.º 25
0
 public ServletResourceLoader(ServletContext context)
 {
     _context = context;
 }
Ejemplo n.º 26
0
 public QuercusServletContextImpl(ServletContext ctx)
 {
     _ctx = ctx;
 }
Ejemplo n.º 27
0
        //public static string GetInitParameterByHierarchy(ServletConfig config, string name)
        //{
        //    if (config == null)
        //        throw new ArgumentNullException("config");

        //    string value = config.getInitParameter(name);
        //    if (value != null)
        //        return value;

        //    return config.getServletContext().getInitParameter(name);
        //}

        public static string GetApplicationRealPath(ServletContext context)
        {
            return(GetApplicationRealPath(context, "/"));
        }
Ejemplo n.º 28
0
 /// <summary>Returns StartupProgress associated with ServletContext.</summary>
 /// <param name="context">ServletContext to get</param>
 /// <returns>StartupProgress associated with context</returns>
 internal static StartupProgress GetStartupProgressFromContext(ServletContext context
                                                               )
 {
     return((StartupProgress)context.GetAttribute(StartupProgressAttributeKey));
 }
Ejemplo n.º 29
0
        public virtual void TestGetUgiFromToken()
        {
            conf.Set(DFSConfigKeys.FsDefaultNameKey, "hdfs://localhost:4321/");
            ServletContext context  = Org.Mockito.Mockito.Mock <ServletContext>();
            string         realUser = "******";
            string         user     = "******";

            conf.Set(DFSConfigKeys.HadoopSecurityAuthentication, "kerberos");
            UserGroupInformation.SetConfiguration(conf);
            UserGroupInformation ugi;
            HttpServletRequest   request;
            Text ownerText = new Text(user);
            DelegationTokenIdentifier dtId = new DelegationTokenIdentifier(ownerText, ownerText
                                                                           , new Text(realUser));

            Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier> token = new Org.Apache.Hadoop.Security.Token.Token
                                                                                       <DelegationTokenIdentifier>(dtId, new TestJspHelper.DummySecretManager(0, 0, 0,
                                                                                                                                                              0));
            string tokenString = token.EncodeToUrlString();

            // token with no auth-ed user
            request = GetMockRequest(null, null, null);
            Org.Mockito.Mockito.When(request.GetParameter(JspHelper.DelegationParameterName))
            .ThenReturn(tokenString);
            ugi = JspHelper.GetUGI(context, request, conf);
            NUnit.Framework.Assert.IsNotNull(ugi.GetRealUser());
            NUnit.Framework.Assert.AreEqual(ugi.GetRealUser().GetShortUserName(), realUser);
            NUnit.Framework.Assert.AreEqual(ugi.GetShortUserName(), user);
            CheckUgiFromToken(ugi);
            // token with auth-ed user
            request = GetMockRequest(realUser, null, null);
            Org.Mockito.Mockito.When(request.GetParameter(JspHelper.DelegationParameterName))
            .ThenReturn(tokenString);
            ugi = JspHelper.GetUGI(context, request, conf);
            NUnit.Framework.Assert.IsNotNull(ugi.GetRealUser());
            NUnit.Framework.Assert.AreEqual(ugi.GetRealUser().GetShortUserName(), realUser);
            NUnit.Framework.Assert.AreEqual(ugi.GetShortUserName(), user);
            CheckUgiFromToken(ugi);
            // completely different user, token trumps auth
            request = GetMockRequest("rogue", null, null);
            Org.Mockito.Mockito.When(request.GetParameter(JspHelper.DelegationParameterName))
            .ThenReturn(tokenString);
            ugi = JspHelper.GetUGI(context, request, conf);
            NUnit.Framework.Assert.IsNotNull(ugi.GetRealUser());
            NUnit.Framework.Assert.AreEqual(ugi.GetRealUser().GetShortUserName(), realUser);
            NUnit.Framework.Assert.AreEqual(ugi.GetShortUserName(), user);
            CheckUgiFromToken(ugi);
            // expected case
            request = GetMockRequest(null, user, null);
            Org.Mockito.Mockito.When(request.GetParameter(JspHelper.DelegationParameterName))
            .ThenReturn(tokenString);
            ugi = JspHelper.GetUGI(context, request, conf);
            NUnit.Framework.Assert.IsNotNull(ugi.GetRealUser());
            NUnit.Framework.Assert.AreEqual(ugi.GetRealUser().GetShortUserName(), realUser);
            NUnit.Framework.Assert.AreEqual(ugi.GetShortUserName(), user);
            CheckUgiFromToken(ugi);
            // can't proxy with a token!
            request = GetMockRequest(null, null, "rogue");
            Org.Mockito.Mockito.When(request.GetParameter(JspHelper.DelegationParameterName))
            .ThenReturn(tokenString);
            try
            {
                JspHelper.GetUGI(context, request, conf);
                NUnit.Framework.Assert.Fail("bad request allowed");
            }
            catch (IOException ioe)
            {
                NUnit.Framework.Assert.AreEqual("Usernames not matched: name=rogue != expected="
                                                + user, ioe.Message);
            }
            // can't proxy with a token!
            request = GetMockRequest(null, user, "rogue");
            Org.Mockito.Mockito.When(request.GetParameter(JspHelper.DelegationParameterName))
            .ThenReturn(tokenString);
            try
            {
                JspHelper.GetUGI(context, request, conf);
                NUnit.Framework.Assert.Fail("bad request allowed");
            }
            catch (IOException ioe)
            {
                NUnit.Framework.Assert.AreEqual("Usernames not matched: name=rogue != expected="
                                                + user, ioe.Message);
            }
        }
Ejemplo n.º 30
0
		//public static string GetInitParameterByHierarchy(ServletConfig config, string name)
		//{
		//    if (config == null)
		//        throw new ArgumentNullException("config");

		//    string value = config.getInitParameter(name);
		//    if (value != null)
		//        return value;

		//    return config.getServletContext().getInitParameter(name);
		//}

		public static string GetApplicationRealPath (ServletContext context) {
			return GetApplicationRealPath (context, "/");
		}
Ejemplo n.º 31
0
 /// <summary>Same as getUGI(context, request, conf, KERBEROS_SSL, true).</summary>
 /// <exception cref="System.IO.IOException"/>
 public static UserGroupInformation GetUGI(ServletContext context, HttpServletRequest
                                           request, Configuration conf)
 {
     return(GetUGI(context, request, conf, UserGroupInformation.AuthenticationMethod.KerberosSsl
                   , true));
 }
Ejemplo n.º 32
0
 internal static FSImage GetFsImageFromContext(ServletContext context)
 {
     return((FSImage)context.GetAttribute(FsimageAttributeKey));
 }
 /// <summary>Initialize the SignerSecretProvider.</summary>
 /// <remarks>
 /// Initialize the SignerSecretProvider.  It initializes the current secret
 /// and starts the scheduler for the rollover to run at an interval of
 /// tokenValidity.
 /// </remarks>
 /// <param name="config">configuration properties</param>
 /// <param name="servletContext">servlet context</param>
 /// <param name="tokenValidity">The amount of time a token is valid for</param>
 /// <exception cref="System.Exception"/>
 public override void Init(Properties config, ServletContext servletContext, long
                           tokenValidity)
 {
     InitSecrets(GenerateNewSecret(), null);
     StartScheduler(tokenValidity, tokenValidity);
 }
Ejemplo n.º 34
0
		public ServletResourceLoader (ServletContext context) {
			_context = context;
		}