Example #1
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.WithOrigins("*");           // Noncompliant
                    builder.WithOrigins(Star);          // Noncompliant
                    builder.WithOrigins("*", "*", "*"); // Noncompliant
                });

                options.AddPolicy("EnableAllPolicy", builder =>
                {
                    builder.WithOrigins("https://trustedwebsite.com", "*"); // Noncompliant
                });

                options.AddPolicy("OtherPolicy", builder =>
                {
                    builder.AllowAnyOrigin(); // Noncompliant
                });

                options.AddPolicy("Safe", builder =>
                {
                    builder.WithOrigins("https://trustedwebsite.com", "https://anothertrustedwebsite.com");
                });

                options.AddPolicy("MyAllowSubdomainPolicy", builder =>
                {
                    builder.WithOrigins("https://*.example.com")
                    .SetIsOriginAllowedToAllowWildcardSubdomains();
                });

                var unsafeBuilder = new CorsPolicyBuilder("*"); // Noncompliant
                options.AddPolicy("UnsafeBuilder", unsafeBuilder.Build());

                var unsafeBuilderWithAlias = new CPB("*"); // FN - for performance reasons type alias is not supported
                options.AddPolicy("UnsafeBuilderWithAlias", unsafeBuilderWithAlias.Build());

                var safeBuilder = new CorsPolicyBuilder("https://trustedwebsite.com");
                options.AddPolicy("SafeBuilder", safeBuilder.Build());

                CorsPolicyBuilder builder = new ("*"); // FN

                builder = new CorsPolicyBuilder {
                };
            });

            services.AddControllers();
        }
        public void AllowAnyHeaders_AllowsAny()
        {
            // Arrange
            var builder = new CorsPolicyBuilder();

            // Act
            builder.AllowAnyHeader();

            // Assert
            var corsPolicy = builder.Build();

            Assert.True(corsPolicy.AllowAnyHeader);
            Assert.Equal(new List <string>()
            {
                "*"
            }, corsPolicy.Headers);
        }
        public void WithHeaders_AddsHeaders()
        {
            // Arrange
            var builder = new CorsPolicyBuilder();

            // Act
            builder.WithHeaders("example1", "example2");

            // Assert
            var corsPolicy = builder.Build();

            Assert.False(corsPolicy.AllowAnyHeader);
            Assert.Equal(new List <string>()
            {
                "example1", "example2"
            }, corsPolicy.Headers);
        }
        public void WithMethods_AddsMethods()
        {
            // Arrange
            var builder = new CorsPolicyBuilder();

            // Act
            builder.WithMethods("PUT", "GET");

            // Assert
            var corsPolicy = builder.Build();

            Assert.False(corsPolicy.AllowAnyOrigin);
            Assert.Equal(new List <string>()
            {
                "PUT", "GET"
            }, corsPolicy.Methods);
        }
        public void WithOrigins_AddsOrigins()
        {
            // Arrange
            var builder = new CorsPolicyBuilder();

            // Act
            builder.WithOrigins("http://example.com", "http://example2.com");

            // Assert
            var corsPolicy = builder.Build();

            Assert.False(corsPolicy.AllowAnyOrigin);
            Assert.Equal(new List <string>()
            {
                "http://example.com", "http://example2.com"
            }, corsPolicy.Origins);
        }
Example #6
0
        /// <summary>
        /// Adds a new policy.
        /// </summary>
        /// <param name="name">The name of the policy.</param>
        /// <param name="configurePolicy">A delegate which can use a policy builder to build a policy.</param>
        public void AddPolicy(string name, Action <CorsPolicyBuilder> configurePolicy)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (configurePolicy == null)
            {
                throw new ArgumentNullException(nameof(configurePolicy));
            }

            var policyBuilder = new CorsPolicyBuilder();

            configurePolicy(policyBuilder);
            PolicyMap[name] = policyBuilder.Build();
        }
Example #7
0
        public async Task Invoke_WithCustomPolicyProviderThatReturnsAsynchronously_Works()
        {
            // Arrange
            var corsService   = new CorsService(Options.Create(new CorsOptions()), NullLoggerFactory.Instance);
            var mockProvider  = new Mock <ICorsPolicyProvider>();
            var loggerFactory = NullLoggerFactory.Instance;
            var policy        = new CorsPolicyBuilder()
                                .WithOrigins(OriginUrl)
                                .WithHeaders("AllowedHeader")
                                .Build();

            mockProvider.Setup(o => o.GetPolicyAsync(It.IsAny <HttpContext>(), It.IsAny <string>()))
            .ReturnsAsync(policy, TimeSpan.FromMilliseconds(10));

            var middleware = new CorsMiddleware(
                Mock.Of <RequestDelegate>(),
                corsService,
                loggerFactory,
                "DefaultPolicyName");

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Method = "OPTIONS";
            httpContext.Request.Headers.Add(CorsConstants.Origin, new[] { OriginUrl });
            httpContext.Request.Headers.Add(CorsConstants.AccessControlRequestMethod, new[] { "PUT" });

            // Act
            await middleware.Invoke(httpContext, mockProvider.Object);

            // Assert
            var response = httpContext.Response;

            Assert.Collection(
                response.Headers.OrderBy(o => o.Key),
                kvp =>
            {
                Assert.Equal(CorsConstants.AccessControlAllowHeaders, kvp.Key);
                Assert.Equal("AllowedHeader", Assert.Single(kvp.Value));
            },
                kvp =>
            {
                Assert.Equal(CorsConstants.AccessControlAllowOrigin, kvp.Key);
                Assert.Equal(OriginUrl, Assert.Single(kvp.Value));
            });
        }
Example #8
0
        public void Constructor_WithNoOrigin()
        {
            // Arrange & Act
            var builder = new CorsPolicyBuilder();

            // Assert
            var corsPolicy = builder.Build();

            Assert.False(corsPolicy.AllowAnyHeader);
            Assert.False(corsPolicy.AllowAnyMethod);
            Assert.False(corsPolicy.AllowAnyOrigin);
            Assert.False(corsPolicy.SupportsCredentials);
            Assert.Empty(corsPolicy.ExposedHeaders);
            Assert.Empty(corsPolicy.Headers);
            Assert.Empty(corsPolicy.Methods);
            Assert.Empty(corsPolicy.Origins);
            Assert.Null(corsPolicy.PreflightMaxAge);
        }
Example #9
0
        public void Constructor_WithParamsOrigin_InitializesOrigin(string origin)
        {
            // Arrange
            var origins = origin.Split(',');

            // Act
            var builder = new CorsPolicyBuilder(origins);

            // Assert
            var corsPolicy = builder.Build();

            Assert.False(corsPolicy.AllowAnyHeader);
            Assert.False(corsPolicy.AllowAnyMethod);
            Assert.False(corsPolicy.AllowAnyOrigin);
            Assert.False(corsPolicy.SupportsCredentials);
            Assert.Empty(corsPolicy.ExposedHeaders);
            Assert.Empty(corsPolicy.Headers);
            Assert.Empty(corsPolicy.Methods);
            Assert.Equal(origins.ToList(), corsPolicy.Origins);
            Assert.Null(corsPolicy.PreflightMaxAge);
        }
Example #10
0
        public async Task Invoke_HasEndpointRequireCorsMetadata_MiddlewareHasPolicy_RunsCorsWithPolicyName()
        {
            // Arrange
            var defaultPolicy   = new CorsPolicyBuilder().Build();
            var metadataPolicy  = new CorsPolicyBuilder().Build();
            var mockCorsService = new Mock <ICorsService>();
            var mockProvider    = new Mock <ICorsPolicyProvider>();
            var loggerFactory   = NullLoggerFactory.Instance;

            mockProvider.Setup(o => o.GetPolicyAsync(It.IsAny <HttpContext>(), It.IsAny <string>()))
            .Returns(Task.FromResult <CorsPolicy>(null))
            .Verifiable();
            mockCorsService.Setup(o => o.EvaluatePolicy(It.IsAny <HttpContext>(), It.IsAny <CorsPolicy>()))
            .Returns(new CorsResult())
            .Verifiable();

            var middleware = new CorsMiddleware(
                Mock.Of <RequestDelegate>(),
                mockCorsService.Object,
                defaultPolicy,
                loggerFactory);

            var httpContext = new DefaultHttpContext();

            httpContext.SetEndpoint(new Endpoint(c => Task.CompletedTask, new EndpointMetadataCollection(new CorsPolicyMetadata(metadataPolicy)), "Test endpoint"));
            httpContext.Request.Headers.Add(CorsConstants.Origin, new[] { "http://example.com" });

            // Act
            await middleware.Invoke(httpContext, mockProvider.Object);

            // Assert
            mockProvider.Verify(
                o => o.GetPolicyAsync(It.IsAny <HttpContext>(), It.IsAny <string>()),
                Times.Never);
            mockCorsService.Verify(
                o => o.EvaluatePolicy(It.IsAny <HttpContext>(), metadataPolicy),
                Times.Once);
        }
Example #11
0
        public void ConstructorWithPolicy_HavingNullPreflightMaxAge_AddsTheGivenPolicy()
        {
            // Arrange
            var originalPolicy = new CorsPolicy();

            originalPolicy.Origins.Add("http://existing.com");

            // Act
            var builder = new CorsPolicyBuilder(originalPolicy);

            // Assert
            var corsPolicy = builder.Build();

            Assert.Null(corsPolicy.PreflightMaxAge);
            Assert.False(corsPolicy.AllowAnyHeader);
            Assert.False(corsPolicy.AllowAnyMethod);
            Assert.False(corsPolicy.AllowAnyOrigin);
            Assert.NotSame(originalPolicy.Origins, corsPolicy.Origins);
            Assert.Equal(originalPolicy.Origins, corsPolicy.Origins);
            Assert.Empty(corsPolicy.Headers);
            Assert.Empty(corsPolicy.Methods);
            Assert.Empty(corsPolicy.ExposedHeaders);
        }
Example #12
0
        public async Task PreFlight_WithCredentialsAllowed_ReflectsRequestHeaders()
        {
            // Arrange
            var policy = new CorsPolicyBuilder(OriginUrl)
                         .AllowAnyHeader()
                         .AllowAnyMethod()
                         .AllowCredentials()
                         .Build();

            var hostBuilder = new WebHostBuilder()
                              .Configure(app =>
            {
                app.UseCors("customPolicy");
                app.Run(async context =>
                {
                    await context.Response.WriteAsync("Cross origin response");
                });
            })
                              .ConfigureServices(services =>
            {
                services.AddCors(options =>
                {
                    options.AddPolicy("customPolicy", policy);
                });
            });

            using (var server = new TestServer(hostBuilder))
            {
                // Act
                // Preflight request.
                var response = await server.CreateRequest("/")
                               .AddHeader(CorsConstants.Origin, OriginUrl)
                               .AddHeader(CorsConstants.AccessControlRequestMethod, "PUT")
                               .AddHeader(CorsConstants.AccessControlRequestHeaders, "X-Test1,X-Test2")
                               .SendAsync(CorsConstants.PreflightHttpMethod);

                // Assert
                response.EnsureSuccessStatusCode();
                Assert.Collection(
                    response.Headers.OrderBy(h => h.Key),
                    kvp =>
                {
                    Assert.Equal(CorsConstants.AccessControlAllowCredentials, kvp.Key);
                    Assert.Equal(new[] { "true" }, kvp.Value);
                },
                    kvp =>
                {
                    Assert.Equal(CorsConstants.AccessControlAllowHeaders, kvp.Key);
                    Assert.Equal(new[] { "X-Test1,X-Test2" }, kvp.Value);
                },
                    kvp =>
                {
                    Assert.Equal(CorsConstants.AccessControlAllowMethods, kvp.Key);
                    Assert.Equal(new[] { "PUT" }, kvp.Value);
                },
                    kvp =>
                {
                    Assert.Equal(CorsConstants.AccessControlAllowOrigin, kvp.Key);
                    Assert.Equal(new[] { OriginUrl }, kvp.Value);
                });
            }
        }