Exemplo n.º 1
0
        public void GetFilters_ReturnsFiltersInCorrectOrder(IEnumerable <IFilter> input)
        {
            foreach (IFilter filter in input)
            {
                _configuration.Filters.Add(filter);
            }

            IEnumerable <FilterInfo> filters = _filterProvider.GetFilters(_configuration, _mockActionDescriptor.Object);

            filters.Count().ShouldBe(2);
            filters.ElementAt(0).Instance.ShouldBeOfType <OrderedFilter1>();
            filters.ElementAt(1).Instance.ShouldBeOfType <OrderedFilter2>();
        }
Exemplo n.º 2
0
 public IEnumerable <FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
 {
     foreach (var filterInfo in internalProvider.GetFilters(configuration, actionDescriptor))
     {
         ObjectFactory.Inject(filterInfo.Instance.GetType(), filterInfo.Instance);
         yield return(filterInfo);
     }
 }
    public IEnumerable <AuthorizeAttribute> GetAuthorizeAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        var filters = filterProvider.GetFilters(controllerContext, actionDescriptor);

        return(filters
               .Where(f => typeof(AuthorizeAttribute).IsAssignableFrom(f.Instance.GetType()))
               .Select(f => f.Instance as AuthorizeAttribute));
    }
Exemplo n.º 4
0
        internal static IReadOnlyList <byte> Decode(this StreamToken stream, IFilterProvider filterProvider)
        {
            var filters = filterProvider.GetFilters(stream.StreamDictionary);

            var transform = stream.Data;

            for (var i = 0; i < filters.Count; i++)
            {
                transform = filters[i].Decode(transform, stream.StreamDictionary, i);
            }

            return(transform);
        }
Exemplo n.º 5
0
        public void WithCustomConstructor_OnlyCustomActionDescriptorFilterProvidersAreUsed()
        {
            var mockFilterProvider = new Mock <IFilterProvider>();

            mockFilterProvider.Setup(p => p.GetFilters(It.IsAny <HttpConfiguration>(), It.IsAny <HttpActionDescriptor>())).Returns(() => Enumerable.Empty <FilterInfo>());

            IFilter testGlobalFilter = new UnorderedFilter();

            _configuration.Filters.Add(testGlobalFilter);

            _filterProvider = new OrderedFilterProvider(new[] { mockFilterProvider.Object });
            IEnumerable <FilterInfo> filters = _filterProvider.GetFilters(_configuration, _mockActionDescriptor.Object);

            filters.ShouldNotContain(f => f.Instance == testGlobalFilter);
            _mockControllerDescriptor.Verify(d => d.GetFilters(), Times.Never(), "Controller Filters should not have been requested");
            _mockActionDescriptor.Verify(d => d.GetFilters(), Times.Never(), "Action Filters should not have been requested");
        }
Exemplo n.º 6
0
        public byte[] Decode(IFilterProvider filterProvider)
        {
            lock (Lock)
            {
                if (decodedBytes != null)
                {
                    return(decodedBytes);
                }

                var filters = filterProvider.GetFilters(Dictionary);

                var transform = streamBytes;
                for (var i = 0; i < filters.Count; i++)
                {
                    transform = filters[i].Decode(transform, Dictionary, i);
                }

                decodedBytes = transform;

                return(transform);
            }
        }
Exemplo n.º 7
0
        internal IReadOnlyList <byte> Decode(IFilterProvider filterProvider)
        {
            lock (lockObject)
            {
                if (decodedBytes != null)
                {
                    return(decodedBytes);
                }

                var filters = filterProvider.GetFilters(StreamDictionary);

                var transform = Data;
                for (var i = 0; i < filters.Count; i++)
                {
                    transform = filters[i].Decode(transform, StreamDictionary, i);
                }

                decodedBytes = transform;

                return(transform);
            }
        }
Exemplo n.º 8
0
        private Collection <FilterInfo> InitializeFilterPipeline()
        {
            IFilterProvider[] filterProviders = this.Configuration.Services.GetFilterProviders();

            List <FilterInfo> filters = new List <FilterInfo>();

            for (int i = 0; i < filterProviders.Length; i++)
            {
                IFilterProvider provider = filterProviders[i];
                foreach (FilterInfo filter in provider.GetFilters(this.Configuration, this))
                {
                    filters.Add(filter);
                }
            }

            filters.Sort(FilterInfoComparer.Instance);

            if (filters.Count > 1)
            {
                RemoveDuplicates(filters);
            }

            return(new Collection <FilterInfo>(filters));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Determines whether node is accessible to user.
        /// </summary>
        /// <param name="controllerTypeResolver">The controller type resolver.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="context">The context.</param>
        /// <param name="node">The node.</param>
        /// <returns>
        ///     <c>true</c> if accessible to user; otherwise, <c>false</c>.
        /// </returns>
        public bool IsAccessibleToUser(IControllerTypeResolver controllerTypeResolver, DefaultSiteMapProvider provider, HttpContext context, SiteMapNode node)
        {
            // Is security trimming enabled?
            if (!provider.SecurityTrimmingEnabled)
            {
                return(true);
            }

            // Is it an external node?
            var nodeUrl = node.Url;

            if (nodeUrl.StartsWith("http") || nodeUrl.StartsWith("ftp"))
            {
                return(true);
            }

            // Is it a regular node?
            var mvcNode = node as MvcSiteMapNode;

            if (mvcNode == null)
            {
                throw new AclModuleNotSupportedException(
                          Resources.Messages.AclModuleDoesNotSupportRegularSiteMapNodes);
            }

            // Clickable? Always accessible.
            if (mvcNode.Clickable == false)
            {
                return(true);
            }

            // Time to delve into the AuthorizeAttribute defined on the node.
            // Let's start by getting all metadata for the controller...
            var controllerType = controllerTypeResolver.ResolveControllerType(mvcNode.Area, mvcNode.Controller);

            if (controllerType == null)
            {
                return(false);
            }

            // Find routes for the sitemap node's url
            HttpContextBase httpContext    = new HttpContextWrapper(context);
            string          originalPath   = httpContext.Request.Path;
            var             originalRoutes = RouteTable.Routes.GetRouteData(httpContext);

            httpContext.RewritePath(nodeUrl, true);

            HttpContextBase httpContext2 = new HttpContext2(context);
            RouteData       routes       = mvcNode.GetRouteData(httpContext2);

            if (routes == null)
            {
                return(true); // Static URL's will have no route data, therefore return true.
            }
            foreach (var routeValue in mvcNode.RouteValues)
            {
                routes.Values[routeValue.Key] = routeValue.Value;
            }
            if (!routes.Route.Equals(originalRoutes.Route) || originalPath != nodeUrl || mvcNode.Area == String.Empty)
            {
                routes.DataTokens.Remove("area");
                //routes.DataTokens.Remove("Namespaces");
                //routes.Values.Remove("area");
            }
            var requestContext = new RequestContext(httpContext, routes);

            // Create controller context
            var controllerContext = new ControllerContext();

            controllerContext.RequestContext = requestContext;

            // Whether controller is built by the ControllerFactory (or otherwise by Activator)
            bool factoryBuiltController = false;

            try
            {
                string controllerName = requestContext.RouteData.GetRequiredString("controller");
                controllerContext.Controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, controllerName) as ControllerBase;
                factoryBuiltController       = true;
            }
            catch
            {
                try
                {
                    controllerContext.Controller = Activator.CreateInstance(controllerType) as ControllerBase;
                }
                catch
                {
                }
            }

            ControllerDescriptor controllerDescriptor = null;

            if (typeof(IController).IsAssignableFrom(controllerType))
            {
                controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
            }
            else if (typeof(IAsyncController).IsAssignableFrom(controllerType))
            {
                controllerDescriptor = new ReflectedAsyncControllerDescriptor(controllerType);
            }

            ActionDescriptor actionDescriptor = null;

            try
            {
                actionDescriptor = controllerDescriptor.FindAction(controllerContext, mvcNode.Action);
            }
            catch
            {
            }
            if (actionDescriptor == null)
            {
                actionDescriptor = controllerDescriptor.GetCanonicalActions().Where(a => a.ActionName == mvcNode.Action).FirstOrDefault();
            }

            // Verify security
            try
            {
                if (actionDescriptor != null)
                {
#if NET35
                    IEnumerable <AuthorizeAttribute> authorizeAttributesToCheck =
                        actionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).OfType
                        <AuthorizeAttribute>().ToList()
                        .Union(
                            controllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).OfType
                            <AuthorizeAttribute>().ToList());
#else
                    IFilterProvider      filterProvider = ResolveFilterProvider();
                    IEnumerable <Filter> filters;

                    // If depencency resolver has an IFilterProvider registered, use it
                    if (filterProvider != null)
                    {
                        filters = filterProvider.GetFilters(controllerContext, actionDescriptor);
                    }
                    // Otherwise use FilterProviders.Providers
                    else
                    {
                        filters = FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor);
                    }

                    IEnumerable <AuthorizeAttribute> authorizeAttributesToCheck =
                        filters
                        .Where(f => typeof(AuthorizeAttribute).IsAssignableFrom(f.Instance.GetType()))
                        .Select(f => f.Instance as AuthorizeAttribute);
#endif

                    // Verify all attributes
                    foreach (var authorizeAttribute in authorizeAttributesToCheck)
                    {
                        try
                        {
                            var currentAuthorizationAttributeType = authorizeAttribute.GetType();

                            var builder             = new AuthorizeAttributeBuilder();
                            var subclassedAttribute =
                                currentAuthorizationAttributeType == typeof(AuthorizeAttribute) ?
                                new InternalAuthorize(authorizeAttribute) :    // No need to use Reflection.Emit when ASP.NET MVC built-in attribute is used
                                (IAuthorizeAttribute)builder.Build(currentAuthorizationAttributeType).Invoke(null);

                            // Copy all properties
                            ObjectCopier.Copy(authorizeAttribute, subclassedAttribute);

                            if (!subclassedAttribute.IsAuthorized(controllerContext.HttpContext))
                            {
                                return(false);
                            }
                        }
                        catch
                        {
                            // do not allow on exception
                            return(false);
                        }
                    }
                }

                // No objection.
                return(true);
            }
            finally
            {
                // Restore HttpContext
                httpContext.RewritePath(originalPath, true);

                // Release controller
                if (factoryBuiltController)
                {
                    ControllerBuilder.Current.GetControllerFactory().ReleaseController(controllerContext.Controller);
                }
            }
        }
Exemplo n.º 10
0
 public IReadOnlyList <IFilter> GetFilters(DictionaryToken dictionary)
 => inner.GetFilters(dictionary);
        public void WithCustomConstructor_OnlyCustomActionDescriptorFilterProvidersAreUsed()
        {
            Mock<IFilterProvider> mockFilterProvider = new Mock<IFilterProvider>();
            mockFilterProvider.Setup(p => p.GetFilters(It.IsAny<HttpConfiguration>(), It.IsAny<HttpActionDescriptor>())).Returns(() => Enumerable.Empty<FilterInfo>());

            IFilter testGlobalFilter = new UnorderedFilter();
            _configuration.Filters.Add(testGlobalFilter);

            _filterProvider = new OrderedFilterProvider(new[] { mockFilterProvider.Object });
            var filters = _filterProvider.GetFilters(_configuration, _mockActionDescriptor.Object);

            filters.ShouldNotContain(f => f.Instance == testGlobalFilter);
            _mockControllerDescriptor.Verify(d => d.GetFilters(), Times.Never(), "Controller Filters should not have been requested");
            _mockActionDescriptor.Verify(d => d.GetFilters(), Times.Never(), "Action Filters should not have been requested");
        }
Exemplo n.º 12
0
 IEnumerable <Filter> IFilterProvider.GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
 {
     return(_filterProvider.GetFilters(controllerContext, actionDescriptor).Select(objFilter => (objFilter.Instance is TFilter) ? new Filter(_dependencyResolver.GetService(objFilter.Instance.GetType()), objFilter.Scope, objFilter.Order) : objFilter));
 }
Exemplo n.º 13
0
        public static XObjectImage ReadImage(XObjectContentRecord xObject, IPdfTokenScanner pdfScanner,
                                             IFilterProvider filterProvider,
                                             IResourceStore resourceStore)
        {
            if (xObject == null)
            {
                throw new ArgumentNullException(nameof(xObject));
            }

            if (xObject.Type != XObjectType.Image)
            {
                throw new InvalidOperationException($"Cannot create an image from an XObject with type: {xObject.Type}.");
            }

            var dictionary = xObject.Stream.StreamDictionary;

            var bounds = xObject.AppliedTransformation.Transform(new PdfRectangle(new PdfPoint(0, 0), new PdfPoint(1, 1)));

            var width  = dictionary.Get <NumericToken>(NameToken.Width, pdfScanner).Int;
            var height = dictionary.Get <NumericToken>(NameToken.Height, pdfScanner).Int;

            var isImageMask = dictionary.TryGet(NameToken.ImageMask, pdfScanner, out BooleanToken isMaskToken) &&
                              isMaskToken.Data;

            var isJpxDecode = dictionary.TryGet(NameToken.Filter, out var token) &&
                              token is NameToken filterName &&
                              filterName.Equals(NameToken.JpxDecode);

            int bitsPerComponent = 0;

            if (!isImageMask && !isJpxDecode)
            {
                if (!dictionary.TryGet(NameToken.BitsPerComponent, pdfScanner, out NumericToken bitsPerComponentToken))
                {
                    throw new PdfDocumentFormatException($"No bits per component defined for image: {dictionary}.");
                }

                bitsPerComponent = bitsPerComponentToken.Int;
            }
            else if (isImageMask)
            {
                bitsPerComponent = 1;
            }

            var intent = xObject.DefaultRenderingIntent;

            if (dictionary.TryGet(NameToken.Intent, out NameToken renderingIntentToken))
            {
                intent = renderingIntentToken.Data.ToRenderingIntent();
            }

            var interpolate = dictionary.TryGet(NameToken.Interpolate, pdfScanner, out BooleanToken interpolateToken) &&
                              interpolateToken.Data;

            DictionaryToken filterDictionary = xObject.Stream.StreamDictionary;

            if (xObject.Stream.StreamDictionary.TryGet(NameToken.Filter, out var filterToken) &&
                filterToken is IndirectReferenceToken)
            {
                if (filterDictionary.TryGet(NameToken.Filter, pdfScanner, out ArrayToken filterArray))
                {
                    filterDictionary = filterDictionary.With(NameToken.Filter, filterArray);
                }
                else if (filterDictionary.TryGet(NameToken.Filter, pdfScanner, out NameToken filterNameToken))
                {
                    filterDictionary = filterDictionary.With(NameToken.Filter, filterNameToken);
                }
                else
                {
                    filterDictionary = null;
                }
            }

            var supportsFilters = filterDictionary != null;

            if (filterDictionary != null)
            {
                var filters = filterProvider.GetFilters(filterDictionary);
                foreach (var filter in filters)
                {
                    if (!filter.IsSupported)
                    {
                        supportsFilters = false;
                        break;
                    }
                }
            }

            var decodedBytes = supportsFilters ? new Lazy <IReadOnlyList <byte> >(() => xObject.Stream.Decode(filterProvider))
                : null;

            var decode = EmptyArray <decimal> .Instance;

            if (dictionary.TryGet(NameToken.Decode, pdfScanner, out ArrayToken decodeArrayToken))
            {
                decode = decodeArrayToken.Data.OfType <NumericToken>()
                         .Select(x => x.Data)
                         .ToArray();
            }

            var colorSpace = default(ColorSpace?);

            if (!isImageMask)
            {
                if (dictionary.TryGet(NameToken.ColorSpace, pdfScanner, out NameToken colorSpaceNameToken) &&
                    TryMapColorSpace(colorSpaceNameToken, resourceStore, out var colorSpaceResult))
                {
                    colorSpace = colorSpaceResult;
                }
                else if (dictionary.TryGet(NameToken.ColorSpace, pdfScanner, out ArrayToken colorSpaceArrayToken) &&
                         colorSpaceArrayToken.Length > 0)
                {
                    var first = colorSpaceArrayToken.Data[0];

                    if ((first is NameToken firstColorSpaceName) && TryMapColorSpace(firstColorSpaceName, resourceStore, out colorSpaceResult))
                    {
                        colorSpace = colorSpaceResult;
                    }
                }
                else if (!isJpxDecode)
                {
                    colorSpace = xObject.DefaultColorSpace;
                }
            }

            return(new XObjectImage(bounds, width, height, bitsPerComponent, colorSpace, isJpxDecode, isImageMask, intent, interpolate, decode,
                                    dictionary, xObject.Stream.Data, decodedBytes));
        }
Exemplo n.º 14
0
 protected Filter(IFilterProvider <T> filterProvider)
 {
     Predicates = filterProvider.GetFilters();
 }