public void GetT_UnknownTypeWithTryParseAndMissingValue_Null()
        {
            var context = new DefaultHttpContext();

            var result = context.Request.GetTypedHeaders().Get<TestHeaderValue>("custom");
            Assert.Null(result);
        }
        public void GetT_UnknownTypeWithoutTryParse_Throws()
        {
            var context = new DefaultHttpContext();
            context.Request.Headers["custom"] = "valid";

            Assert.Throws<NotSupportedException>(() => context.Request.GetTypedHeaders().Get<object>("custom"));
        }
        public void EmptyUserIsNeverNull()
        {
            var context = new DefaultHttpContext(new FeatureCollection());
            Assert.NotNull(context.User);
            Assert.Equal(1, context.User.Identities.Count());
            Assert.True(object.ReferenceEquals(context.User, context.User));
            Assert.False(context.User.Identity.IsAuthenticated);
            Assert.True(string.IsNullOrEmpty(context.User.Identity.AuthenticationType));

            context.User = null;
            Assert.NotNull(context.User);
            Assert.Equal(1, context.User.Identities.Count());
            Assert.True(object.ReferenceEquals(context.User, context.User));
            Assert.False(context.User.Identity.IsAuthenticated);
            Assert.True(string.IsNullOrEmpty(context.User.Identity.AuthenticationType));

            context.User = new ClaimsPrincipal();
            Assert.NotNull(context.User);
            Assert.Equal(0, context.User.Identities.Count());
            Assert.True(object.ReferenceEquals(context.User, context.User));
            Assert.Null(context.User.Identity);

            context.User = new ClaimsPrincipal(new ClaimsIdentity("SomeAuthType"));
            Assert.Equal("SomeAuthType", context.User.Identity.AuthenticationType);
            Assert.True(context.User.Identity.IsAuthenticated);
        }
        public void GetT_KnownTypeWithMissingValue_Null()
        {
            var context = new DefaultHttpContext();

            var result = context.Request.GetTypedHeaders().Get<MediaTypeHeaderValue>(HeaderNames.ContentType);

            Assert.Null(result);
        }
        public void GetT_UnknownTypeWithTryParseAndValidValue_Success()
        {
            var context = new DefaultHttpContext();
            context.Request.Headers["custom"] = "valid";

            var result = context.Request.GetTypedHeaders().Get<TestHeaderValue>("custom");
            Assert.NotNull(result);
        }
        public void GetT_KnownTypeWithValidValue_Success()
        {
            var context = new DefaultHttpContext();
            context.Request.Headers[HeaderNames.ContentType] = "text/plain";

            var result = context.Request.GetTypedHeaders().Get<MediaTypeHeaderValue>(HeaderNames.ContentType);

            var expected = new MediaTypeHeaderValue("text/plain");
            Assert.Equal(expected, result);
        }
        public async Task SendFileWorks()
        {
            var context = new DefaultHttpContext();
            var response = context.Response;
            var fakeFeature = new FakeSendFileFeature();
            context.Features.Set<IHttpSendFileFeature>(fakeFeature);

            await response.SendFileAsync("bob", 1, 3, CancellationToken.None);

            Assert.Equal("bob", fakeFeature.name);
            Assert.Equal(1, fakeFeature.offset);
            Assert.Equal(3, fakeFeature.length);
            Assert.Equal(CancellationToken.None, fakeFeature.token);
        }
Example #8
0
        public void HttpStatusCodeResult_ExecuteResultSetsResponseStatusCode()
        {
            // Arrange
            var result = new HttpStatusCodeResult(404);

            var httpContext = new DefaultHttpContext();
            var routeData = new RouteData();
            var actionDescriptor = new ActionDescriptor();

            var context = new ActionContext(httpContext, routeData, actionDescriptor);

            // Act
            result.ExecuteResult(context);

            // Assert
            Assert.Equal(404, httpContext.Response.StatusCode);
        }
        public async void CreatePdf()
        {
            var guid      = Guid.NewGuid();
            var id        = guid.ToString();
            var modelMock = new Schedule()
            {
                Id = guid, User = new User(), Vehicle = new Vehicle()
            };

            _service.Setup(s => s.FindAsync(
                               id, include => include.User, include => include.Vehicle,
                               include => include.Vehicle.VehicleBrand,
                               include => include.Vehicle.VehicleModel,
                               include => include.Vehicle.VehicleCategory
                               ))
            .Returns(Task.FromResult(modelMock));

            _nodeService.Setup(s => s.InvokeAsync <byte[]>("./pdf"))
            .Returns(Task.FromResult(Array.Empty <byte>()));

            var httpContext = new DefaultHttpContext();

            _controller.ControllerContext = new ControllerContext()
            {
                HttpContext = httpContext
            };
            await _controller.CreatePdf(id, _nodeService.Object);

            Assert.Equal("application/pdf", _controller.HttpContext.Response.ContentType);
            Assert.Equal(200, _controller.HttpContext.Response.StatusCode);
            Assert.Equal(
                "Contrato de Locacao.pdf",
                _controller.HttpContext.Response.Headers["x-filename"]
                );
            Assert.Equal(
                "x-filename",
                _controller.HttpContext.Response.Headers["Access-Control-Expose-Headers"]
                );
        }
        public async Task UsesPreferredServerEncodingForEqualQualityValues()
        {
            var             encoding         = "gzip, deflate, br";
            var             expectedPath     = "/_framework/blazor.boot.json.br";
            var             expectedEncoding = "br";
            RequestDelegate next             = (ctx) => Task.CompletedTask;

            var negotiator = new ContentEncodingNegotiator(next, CreateWebHostEnvironment());

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Path = "/_framework/blazor.boot.json";
            httpContext.Request.Headers.Append(HeaderNames.AcceptEncoding, encoding);

            await negotiator.InvokeAsync(httpContext);

            Assert.Equal(expectedPath, httpContext.Request.Path);
            Assert.True(httpContext.Response.Headers.TryGetValue(HeaderNames.ContentEncoding, out var selectedEncoding));
            Assert.Equal(expectedEncoding, selectedEncoding);
            Assert.True(httpContext.Response.Headers.TryGetValue(HeaderNames.Vary, out var varyHeader));
            Assert.Contains(HeaderNames.ContentEncoding, varyHeader.ToArray());
        }
Example #11
0
        public async void CreateExternalService_ReturnsCreatedExternalService()
        {
            _externalServiceService
            .Setup(s => s.AddExternalService(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(1);
            _externalServiceService.Setup(s => s.GetExternalService(It.IsAny <int>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((int id, CancellationToken cancellationToken) =>
                          new ExternalService
            {
                Id   = id,
                Name = "my connection"
            });

            var httpContext = new DefaultHttpContext()
            {
                User = new ClaimsPrincipal(new[]
                {
                    new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "1") })
                })
            };

            var controller = new ExternalServiceController(_externalServiceService.Object, _mapper, _logger.Object)
            {
                ControllerContext = new ControllerContext {
                    HttpContext = httpContext
                }
            };

            var dto = new CreateExternalServiceDto
            {
                Name = "my connection"
            };
            var result = await controller.CreateExternalService(dto);

            var createAtRouteActionResult = Assert.IsType <CreatedAtRouteResult>(result);
            var returnValue = Assert.IsType <ExternalServiceDto>(createAtRouteActionResult.Value);

            Assert.Equal(1, returnValue.Id);
        }
        public async Task SkipsNonExistingFiles()
        {
            var             encoding         = "gzip;q=0.5, deflate;q=0.3, br";
            var             expectedPath     = "/_framework/blazor.boot.json.gz";
            var             expectedEncoding = "gzip";
            RequestDelegate next             = (ctx) => Task.CompletedTask;

            var negotiator = new ContentEncodingNegotiator(next, CreateWebHostEnvironment(brotliExists: false));

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Path = "/_framework/blazor.boot.json";
            httpContext.Request.Headers.Append(HeaderNames.AcceptEncoding, encoding);

            await negotiator.InvokeAsync(httpContext);

            Assert.Equal(expectedPath, httpContext.Request.Path);
            Assert.True(httpContext.Response.Headers.TryGetValue(HeaderNames.ContentEncoding, out var selectedEncoding));
            Assert.Equal(expectedEncoding, selectedEncoding);
            Assert.True(httpContext.Response.Headers.TryGetValue(HeaderNames.Vary, out var varyHeader));
            Assert.Contains(HeaderNames.ContentEncoding, varyHeader.ToArray());
        }
        public async Task TestEchoService()
        {
            // Arrange
            var middleware = new ReverseMiddleware(null, CreateLoadBalancerFromConfig());

            var context = new DefaultHttpContext();

            context.Request.Method = HttpMethod.Get.Method;
            context.Request.Host   = new HostString("echo.com");
            context.Response.Body  = new MemoryStream();

            //Act
            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader     = new StreamReader(context.Response.Body);
            var streamText = reader.ReadToEnd();

            Assert.True(context.Response.StatusCode == 200);
            Assert.False(String.IsNullOrEmpty(streamText));
            Assert.True(streamText.Contains("foo", StringComparison.CurrentCultureIgnoreCase));
        }
Example #14
0
        public async Task ExecuteAsync_WithOneProvidedContentType_FromResponseContentType_NoFallback()
        {
            // Arrange
            var executor      = CreateCustomObjectResultExecutor();
            var httpContext   = new DefaultHttpContext();
            var actionContext = new ActionContext()
            {
                HttpContext = httpContext
            };

            httpContext.Request.Headers[HeaderNames.Accept] = "application/xml"; // This will not be used
            httpContext.Response.ContentType = "application/json";
            var result = new ObjectResult("input");

            result.Formatters.Add(new TestXmlOutputFormatter());

            // Act
            await executor.ExecuteAsync(actionContext, result);

            // Assert
            Assert.Null(executor.SelectedOutputFormatter);
        }
Example #15
0
        public async Task KeepsScopeSeparate()
        {
            var router = _provider.GetService <IRouter>();

            router.Map(r => r.Get <ScopeController>("/test"));
            var middleware =
                ActivatorUtilities.CreateInstance <TreeRouter.Http.Middleware>(_provider, router, _emptyNext);
            var http = new DefaultHttpContext();

            http.Request.Path = "/test";
            await middleware.Invoke(http, _provider.GetService <IServiceScopeFactory>());

            var service = _provider.GetService <SimpleService>();

            Assert.Null(service.Value);
            var nonscoped = new NonscopedMiddleware(GenerateNext("somethingelse"));

            nonscoped.Invoke(new DefaultHttpContext()).Wait();
            var service2 = _provider.GetService <SimpleService>();

            Assert.Equal("somethingelse", service2.Value);
        }
Example #16
0
        public async Task <string> RenderToStringAsync(string viewName, object model)
        {
            var httpContext = new DefaultHttpContext {
                RequestServices = _serviceProvider
            };
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            using (var sw = new StringWriter())
            {
                // var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);
                int index             = viewName.LastIndexOf('/') + 1;
                var executingFilePath = viewName.Substring(0, index);
                var viewPath          = viewName.Substring(index, viewName.Length - index);
                var viewResult        = _razorViewEngine.GetView(executingFilePath, viewPath, false);
                if (viewResult.View == null)
                {
                    throw new ArgumentNullException($"{viewName} không tìm thấy.");
                }

                var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(),
                                                            new ModelStateDictionary())
                {
                    Model = model
                };

                var viewContext = new ViewContext(
                    actionContext,
                    viewResult.View,
                    viewDictionary,
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    sw,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(sw.ToString());
            }
        }
        public async Task valid_paths_should_call_policy_service(string path)
        {
            _allowedPaths.AddRange(new string[] {
                "/foo",
                "/bar/",
                "/baz/quux",
                "/baz/quux/"
            });
            Init();

            var ctx = new DefaultHttpContext();

            ctx.Request.Scheme = "https";
            ctx.Request.Host   = new HostString("server");
            ctx.Request.Path   = new PathString(path);
            ctx.Request.Headers.Add("Origin", "http://notserver");

            var response = await _subject.GetPolicyAsync(ctx, _options.Cors.CorsPolicyName);

            _mockPolicy.WasCalled.Should().BeTrue();
            _mockInner.WasCalled.Should().BeFalse();
        }
    public async Task BindModel_BuiltInInputFormatters_ThrowingNonInputFormatterException_Throws(
        IInputFormatter formatter,
        string contentType)
    {
        // Arrange
        var httpContext = new DefaultHttpContext();

        httpContext.Request.Body        = new MemoryStream(Encoding.UTF8.GetBytes("valid data!"));
        httpContext.Request.ContentType = contentType;

        var metadataProvider = new TestModelMetadataProvider();

        metadataProvider.ForType <Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);

        var bindingContext = GetBindingContext(typeof(Person), httpContext, metadataProvider);
        var binder         = CreateBinder(new[] { formatter }, new MvcOptions());

        // Act & Assert
        var exception = await Assert.ThrowsAsync <IOException>(() => binder.BindModelAsync(bindingContext));

        Assert.Equal("Unable to read input stream!!", exception.Message);
    }
Example #19
0
        private static ViewContext CreateViewContext(TextWriter writer = null)
        {
            writer = writer ?? new StringWriter();
            var httpContext     = new DefaultHttpContext();
            var serviceProvider = new ServiceCollection()
                                  .AddSingleton <IViewBufferScope, TestViewBufferScope>()
                                  .BuildServiceProvider();

            httpContext.RequestServices = serviceProvider;
            var actionContext = new ActionContext(
                httpContext,
                new RouteData(),
                new ActionDescriptor());

            return(new ViewContext(
                       actionContext,
                       Mock.Of <IView>(),
                       new ViewDataDictionary(new EmptyModelMetadataProvider()),
                       Mock.Of <ITempDataDictionary>(),
                       writer,
                       new HtmlHelperOptions()));
        }
        public async Task InvalidAuthenticateRequestTest_InvalidToken()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId       = "device_2";
            string moduleId       = "module_1";
            var    httpContext    = new DefaultHttpContext();

            httpContext.Request.Headers.Add(HeaderNames.Authorization, new StringValues("invalidSasToken"));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");

            var authenticator = new Mock <IAuthenticator>();

            authenticator.Setup(a => a.AuthenticateAsync(It.IsAny <IClientCredentials>())).ReturnsAsync(true);

            var identityFactory = new ClientCredentialsFactory(new IdentityProvider(iothubHostName));

            var            httpRequestAuthenticator = new HttpRequestAuthenticator(authenticator.Object, identityFactory, iothubHostName);
            HttpAuthResult result = await httpRequestAuthenticator.AuthenticateAsync(deviceId, Option.Some(moduleId), Option.None <string>(), httpContext);

            Assert.False(result.Authenticated);
            Assert.Equal("Invalid Authorization header. Only SharedAccessSignature is supported.", result.ErrorMessage);
        }
        public void CreateRequestLogMatchesWithHttpRequest()
        {
            _options.Setup(o => o.Value).Returns(new RaccoonLogHttpOptions());

            var factory = new HttpLogMessageFactory(_options.Object, NullProtector.Value);
            var context = new DefaultHttpContext();
            var request = new FakeHttpRequest();
            var cookies = new FakeRequestCookies();

            context.Features.Set <IHttpRequestFeature>(request);
            context.Features.Set <IRequestCookiesFeature>(cookies);

            var requestLog = factory.Create(context.Request);

            Assert.Equal(context.Request.Method, requestLog.Method);
            Assert.Equal(context.Request.Headers.Keys, requestLog.Headers.Select(h => h.Key).ToList());
            Assert.Equal(context.Request.Cookies, requestLog.Cookies);
            Assert.Equal(context.Request.Scheme, requestLog.Url.Scheme);
            Assert.Equal(context.Request.Host.Port, requestLog.Url.Port);
            Assert.Equal(context.Request.Host.Host, requestLog.Url.Host);
            Assert.Equal($"{context.Request.PathBase}{context.Request.Path}", requestLog.Url.Path);
        }
Example #22
0
        public void ConsolidateTrailers_AppendsStatus_PercentEncodesMessage()
        {
            // Arrange
            var errorMessage = "\t\ntest with whitespace\r\nand Unicode BMP ☺ and non-BMP 😈\t\n";
            var httpContext  = new DefaultHttpContext();

            httpContext.Features.Set <IHttpResponseTrailersFeature>(new TestHttpResponseTrailersFeature());
            httpContext.Features.Set <IHttpResponseFeature>(new TestHttpResponseFeature(hasStarted: true));
            var serverCallContext = CreateServerCallContext(httpContext);

            serverCallContext.Status = new Status(StatusCode.Internal, errorMessage);

            // Act
            httpContext.Response.ConsolidateTrailers(serverCallContext);

            // Assert
            var responseTrailers = httpContext.Features.Get <IHttpResponseTrailersFeature>().Trailers;

            Assert.AreEqual(2, responseTrailers.Count);
            Assert.AreEqual(StatusCode.Internal.ToString("D"), responseTrailers[GrpcProtocolConstants.StatusTrailer]);
            Assert.AreEqual(PercentEncodingHelpers.PercentEncode(errorMessage), responseTrailers[GrpcProtocolConstants.MessageTrailer].ToString());
        }
Example #23
0
        public async Task SSEWritesMessages()
        {
            using (StartVerifiableLog())
            {
                var pair       = DuplexPipe.CreateConnectionPair(PipeOptions.Default, new PipeOptions(readerScheduler: PipeScheduler.Inline));
                var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application);
                var context    = new DefaultHttpContext();

                var ms = new MemoryStream();
                context.Response.Body = ms;
                var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: string.Empty, LoggerFactory);

                var task = sse.ProcessRequestAsync(context, context.RequestAborted);

                await connection.Transport.Output.WriteAsync(Encoding.ASCII.GetBytes("Hello"));

                connection.Transport.Output.Complete();
                await task.OrTimeout();

                Assert.Equal(":\r\ndata: Hello\r\n\r\n", Encoding.ASCII.GetString(ms.ToArray()));
            }
        }
Example #24
0
        public async Task ExplicitlySet_ChunkedEncodingHeader_IsIgnored()
        {
            // Arrange
            var transferEncodingHeaderKey = "Transfer-Encoding";
            var httpResponseMessage       = new HttpResponseMessage();

            httpResponseMessage.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("Hello, World")));
            httpResponseMessage.Headers.Add(transferEncodingHeaderKey, "chunked");

            var httpContext            = new DefaultHttpContext();
            var formatter              = new HttpResponseMessageOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(
                httpResponseMessage,
                typeof(HttpResponseMessage),
                httpContext);
            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            Assert.False(httpContext.Response.Headers.ContainsKey(transferEncodingHeaderKey));
            Assert.NotNull(httpContext.Response.ContentLength);
        }
        public async Task Process_OK()
        {
            _mockBlogConfig.Setup(p => p.AdvancedSettings).Returns(new AdvancedSettings
            {
                EnablePingBackReceive = true
            });

            _mockPingbackService
            .Setup(p => p.ReceivePingAsync(It.IsAny <string>(), It.IsAny <string>(),
                                           It.IsAny <Action <PingbackEntity> >())).Returns(Task.FromResult(PingbackResponse.Success));

            var pingbackController = CreatePingbackController();

            pingbackController.ControllerContext = new()
            {
                HttpContext = new DefaultHttpContext()
            };

            var result = await pingbackController.Process();

            Assert.IsInstanceOf(typeof(PingbackResult), result);
        }
        public void PostResetPasswordFails()
        {
            //Arrange
            Setup();

            const string code     = "1234";
            const string email    = "*****@*****.**";
            const string password = "******";

            var resetPasswordViewModel = new ResetPasswordViewModel
            {
                Code     = code,
                Email    = email,
                Password = password
            };

            var context      = new DefaultHttpContext();
            var mockTempData = new TempDataDictionary(context, Mock.Of <ITempDataProvider>())
            {
                ["Error"] = ""
            };

            _mockUserManager.Setup(x => x.FindByEmailAsync(It.IsAny <string>())).Returns(Task.FromResult <User>(null));

            var accountController = new AccountController(_mockUserManager.Object, null, null, null, null)
            {
                TempData = mockTempData
            };

            //Act
            var response = accountController.ResetPassword(resetPasswordViewModel).Result;

            //Assert
            var result = Assert.IsType <RedirectToActionResult>(response);

            _mockUserManager.Verify(x => x.FindByEmailAsync(email), Times.Once);
            Assert.Contains(nameof(accountController.Register), result.ActionName);
            Assert.Equal("No user with that email address found.", accountController.TempData["Error"]);
        }
Example #27
0
        public static async Task <HttpRequest> ToServerSideHttpRequest(this HttpRequestMessage clientRequest)
        {
            if (clientRequest == null)
            {
                return(null);
            }

            var request = new DefaultHttpContext().Request;

            request.Method = clientRequest.Method.Method;
            request.Scheme = clientRequest.RequestUri.IsAbsoluteUri ? clientRequest.RequestUri.Scheme : null;
            request.Host   = clientRequest.RequestUri.IsAbsoluteUri ? new HostString(clientRequest.RequestUri.Host, clientRequest.RequestUri.Port) : new HostString();
            request.Path   = clientRequest.RequestUri.IsAbsoluteUri ? clientRequest.RequestUri.AbsolutePath : clientRequest.RequestUri.OriginalString.Split('?')[0];
            request.Headers["Authorization"] = clientRequest.Headers.Authorization.Scheme + " " + clientRequest.Headers.Authorization.Parameter;

            var bodyTask = clientRequest.Content?.ReadAsStreamAsync();

            if (bodyTask != null)
            {
                request.Body = await bodyTask;
            }

            if (clientRequest.Headers.Contains("Dalion-App-Id"))
            {
                request.Headers.Add("Dalion-App-Id", clientRequest.Headers.GetValues("Dalion-App-Id").ToArray());
            }

            if (clientRequest.Headers.Contains(HeaderName.PredefinedHeaderNames.Digest))
            {
                request.Headers.Add(HeaderName.PredefinedHeaderNames.Digest, clientRequest.Headers.GetValues(HeaderName.PredefinedHeaderNames.Digest).ToArray());
            }

            if (clientRequest.Headers.Contains(HeaderName.PredefinedHeaderNames.Date))
            {
                request.Headers.Add(HeaderName.PredefinedHeaderNames.Date, clientRequest.Headers.GetValues(HeaderName.PredefinedHeaderNames.Date).ToArray());
            }

            return(request);
        }
        public async Task HtmlHelper_Redirects_WhenComponentNavigates()
        {
            // Arrange
            var ctx = new DefaultHttpContext();

            ctx.Request.Scheme      = "http";
            ctx.Request.Host        = new HostString("localhost");
            ctx.Request.PathBase    = "/base";
            ctx.Request.Path        = "/path";
            ctx.Request.QueryString = new QueryString("?query=value");
            var helper = CreateHelper(ctx);

            // Act
            await helper.RenderComponentAsync <RedirectComponent>(new
            {
                RedirectUri = "http://localhost/redirect"
            });

            // Assert
            Assert.Equal(302, ctx.Response.StatusCode);
            Assert.Equal("http://localhost/redirect", ctx.Response.Headers[HeaderNames.Location]);
        }
Example #29
0
        public T GetController <T>(string userId = null, string storeId = null, Claim[] additionalClaims = null) where T : Controller
        {
            var context = new DefaultHttpContext();

            context.Request.Host     = new HostString("127.0.0.1", Port);
            context.Request.Scheme   = "http";
            context.Request.Protocol = "http";
            if (userId != null)
            {
                List <Claim> claims = new List <Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, userId));
                if (additionalClaims != null)
                {
                    claims.AddRange(additionalClaims);
                }
                context.User = new ClaimsPrincipal(new ClaimsIdentity(claims.ToArray(), Policies.CookieAuthentication));
            }
            if (storeId != null)
            {
                context.SetStoreData(GetService <StoreRepository>().FindStore(storeId, userId).GetAwaiter().GetResult());
            }
            var scope    = (IServiceScopeFactory)_Host.Services.GetService(typeof(IServiceScopeFactory));
            var provider = scope.CreateScope().ServiceProvider;

            context.RequestServices = provider;

            var httpAccessor = provider.GetRequiredService <IHttpContextAccessor>();

            httpAccessor.HttpContext = context;

            var controller = (T)ActivatorUtilities.CreateInstance(provider, typeof(T));

            controller.Url = new UrlHelperMock(new Uri($"http://{HostName}:{Port}/"));
            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = context
            };
            return(controller);
        }
        public void GivenABundleBeingProcessed_WhenUrlIsResolvedWithQuery_ThenTheCorrectValueIsReturned()
        {
            string inputQueryString = "?param1=value1&param2=value2";

            Tuple <string, string>[] unsupportedSearchParams = null;
            string continuationToken   = "continue";
            var    expectedRouteValues = new Dictionary <string, object>()
            {
                { "param3", new StringValues("value3") },
                { "param4", new StringValues("value4") },
                { ContinuationTokenQueryParamName, continuationToken },
            };

            var bundleHttpContext = new DefaultHttpContext();

            bundleHttpContext.Request.QueryString = new QueryString("?param3=value3&param4=value4");
            bundleHttpContext.Request.Scheme      = Scheme;
            bundleHttpContext.Request.Host        = new HostString(Host);
            _bundleHttpContextAccessor.HttpContext.Returns(bundleHttpContext);

            TestAndValidateRouteWithQueryParameter(inputQueryString, unsupportedSearchParams, unsupportedSortingParameters: null, continuationToken, expectedRouteValues);
        }
Example #31
0
        public async Task OpenIdClaimsTest()
        {
            const string mail = "*****@*****.**";
            const string sub  = "123-456";

            var payloadSender = new MockPayloadSender();

            using (var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)))
            {
                var context = new DefaultHttpContext
                {
                    User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("email", mail), new Claim("sub", sub) }, "someAuthTypeName"))
                };

                var middleware = new ApmMiddleware(async innerHttpContext => { await Task.Delay(1); }, agent.TracerInternal, agent);

                await middleware.InvokeAsync(context);
            }

            payloadSender.FirstTransaction.Context.User.Email.Should().Be(mail);
            payloadSender.FirstTransaction.Context.User.Id.Should().Be(sub);
        }
Example #32
0
    public void GetLargeChunkedCookieWithMissingChunk_ThrowingEnabled_Throws()
    {
        HttpContext context = new DefaultHttpContext();

        context.Request.Headers["Cookie"] = new[]
        {
            "TestCookie=chunks-7",
            "TestCookieC1=abcdefghi",
            // Missing chunk "TestCookieC2=jklmnopqr",
            "TestCookieC3=stuvwxyz0",
            "TestCookieC4=123456789",
            "TestCookieC5=ABCDEFGHI",
            "TestCookieC6=JKLMNOPQR",
            "TestCookieC7=STUVWXYZ"
        };

        Assert.Throws <FormatException>(() => new ChunkingCookieManager()
        {
            ThrowForPartialCookies = true
        }
                                        .GetRequestCookie(context, "TestCookie"));
    }
        public async Task HpkpHeaderIsNotIncluded_WhenRequestHeadersAlreadyContainHpkpHeader()
        {
            RequestDelegate mockNext = (HttpContext ctx) =>
            {
                return(Task.CompletedTask);
            };
            var options = Options.Create(new HpkpOptions()
            {
                MaxAgeSeconds = 60,
                Pins          = new List <string> {
                    "a"
                }
            });
            var sut         = new HpkpMiddleware(mockNext, options);
            var mockContext = new DefaultHttpContext();

            mockContext.Response.Headers.Add("Public-Key-Pins", "abc; max-age=60");

            await sut.Invoke(mockContext);

            //Invoke throws System.ArgumentException if it tries to add the header again
        }
Example #34
0
        public async Task MatchAsync_InvalidRouteConstraint_NoEndpointMatched()
        {
            // Arrange
            var endpointDataSource = new DefaultEndpointDataSource(new List <Endpoint>
            {
                CreateEndpoint("/{p:int}", 0)
            });

            var matcher = CreateDfaMatcher(endpointDataSource);

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Path = "/One";

            var endpointFeature = new EndpointFeature();

            // Act
            await matcher.MatchAsync(httpContext, endpointFeature);

            // Assert
            Assert.Null(endpointFeature.Endpoint);
        }
Example #35
0
        public async Task AutoRedirectSessionEndpoint_ReturnsBadRequest_WhenCannotReadTheRequestBody()
        {
            // Arrange
            var session               = new Mock <IUserSession>();
            var endSessionValidator   = new Mock <IEndSessionRequestValidator>();
            var identityServerOptions = Options.Create(new IdentityServerOptions());

            var endpoint = new AutoRedirectEndSessionEndpoint(new TestLogger <AutoRedirectEndSessionEndpoint>(), endSessionValidator.Object, identityServerOptions, session.Object);
            var ctx      = new DefaultHttpContext();

            SetupRequestServices(ctx);
            ctx.Request.Method = HttpMethods.Post;

            // Act & Assert
            var response = await endpoint.ProcessAsync(ctx);

            // Assert
            Assert.NotNull(response);
            var statusCode = Assert.IsType <StatusCodeResult>(response);

            Assert.Equal(StatusCodes.Status400BadRequest, statusCode.StatusCode);
        }
Example #36
0
        public async Task Invoke_ErrorFlow_CallFailurePolicy(AffinityStatus affinityStatus, bool keepProcessing)
        {
            var          cluster         = GetCluster();
            var          endpoint        = GetEndpoint(cluster);
            var          providers       = RegisterAffinityProviders(true, cluster.Destinations.Values.ToList(), cluster.ClusterId, ("Mode-B", affinityStatus, null, _ => { }));
            var          invokedPolicy   = string.Empty;
            const string expectedPolicy  = "Policy-1";
            var          failurePolicies = RegisterFailurePolicies(
                affinityStatus,
                ("Policy-0", false, p => throw new InvalidOperationException($"Policy {p.Name} call is not expected.")),
                (expectedPolicy, keepProcessing, p => invokedPolicy = p.Name));
            var nextInvoked = false;
            var logger      = AffinityTestHelper.GetLogger <SessionAffinityMiddleware>();
            var middleware  = new SessionAffinityMiddleware(c => {
                nextInvoked = true;
                return(Task.CompletedTask);
            },
                                                            providers.Select(p => p.Object), failurePolicies.Select(p => p.Object),
                                                            logger.Object);
            var context            = new DefaultHttpContext();
            var destinationFeature = GetDestinationsFeature(cluster.Destinations.Values.ToList(), cluster.Config);

            context.SetEndpoint(endpoint);
            context.Features.Set(destinationFeature);

            await middleware.Invoke(context);

            Assert.Equal(expectedPolicy, invokedPolicy);
            Assert.Equal(keepProcessing, nextInvoked);
            failurePolicies[0].VerifyGet(p => p.Name, Times.Once);
            failurePolicies[0].VerifyNoOtherCalls();
            failurePolicies[1].VerifyAll();
            if (!keepProcessing)
            {
                logger.Verify(
                    l => l.Log(LogLevel.Warning, EventIds.AffinityResolutionFailedForCluster, It.IsAny <It.IsAnyType>(), null, (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                    Times.Once);
            }
        }
Example #37
0
        public void ConsolidateTrailers_Base64EncodesBinaryTrailers(string trailerName)
        {
            // Arrange
            var trailerBytes = new byte[] { 0x01, 0x02, 0x03, 0x04 };
            var httpContext  = new DefaultHttpContext();

            httpContext.Features.Set <IHttpResponseTrailersFeature>(new TestHttpResponseTrailersFeature());
            httpContext.Features.Set <IHttpResponseFeature>(new TestHttpResponseFeature(hasStarted: true));
            var serverCallContext = CreateServerCallContext(httpContext);

            serverCallContext.ResponseTrailers.Add(trailerName, trailerBytes);

            // Act
            httpContext.Response.ConsolidateTrailers(serverCallContext);

            // Assert
            var responseTrailers = httpContext.Features.Get <IHttpResponseTrailersFeature>().Trailers;

            Assert.AreEqual(2, responseTrailers.Count);
            Assert.AreEqual(StatusCode.OK.ToString("D"), responseTrailers[GrpcProtocolConstants.StatusTrailer]);
            Assert.AreEqual(Convert.ToBase64String(trailerBytes), responseTrailers["trailer-bin"]);
        }
Example #38
0
        public void TakeHeader_RemovesAndReturnsHttpResponseHeader(bool copiedHeaders)
        {
            var httpContext = new DefaultHttpContext();

            httpContext.Response.Headers.Add("name", "value0");
            var proxyResponse = new HttpResponseMessage();

            proxyResponse.Headers.Add("Name", "value1");
            proxyResponse.Content = new StringContent("hello world");
            proxyResponse.Content.Headers.Add("Name", "value2");
            var result = ResponseTransform.TakeHeader(new ResponseTransformContext()
            {
                HttpContext   = httpContext,
                ProxyResponse = proxyResponse,
                HeadersCopied = copiedHeaders,
            }, "name");

            Assert.Equal("value0", result);
            Assert.False(httpContext.Response.Headers.TryGetValue("name", out var _));
            Assert.Equal(new[] { "value1" }, proxyResponse.Headers.GetValues("name"));
            Assert.Equal(new[] { "value2" }, proxyResponse.Content.Headers.GetValues("name"));
        }
        public void GetListT_UnknownTypeWithTryParseListAndValidValue_Success()
        {
            var context = new DefaultHttpContext();
            context.Request.Headers["custom"] = "valid";

            var results = context.Request.GetTypedHeaders().GetList<TestHeaderValue>("custom");
            Assert.NotNull(results);
            Assert.Equal(new[] { new TestHeaderValue() }.ToList(), results);
        }
Example #40
0
 private static ViewContext CreateViewContext(RazorView view)
 {
     var httpContext = new DefaultHttpContext();
     var actionContext = new ActionContext(httpContext, routeData: null, actionDescriptor: null);
     return new ViewContext(
         actionContext,
         view,
         new ViewDataDictionary(Mock.Of<IModelMetadataProvider>()),
         new StringWriter());
 }
 private HttpContext CreateContext()
 {
     var context = new DefaultHttpContext();
     return context;
 }
        public void GetListT_KnownTypeWithValidValue_Success()
        {
            var context = new DefaultHttpContext();
            context.Request.Headers[HeaderNames.Accept] = "text/plain; q=0.9, text/other, */*";

            var result = context.Request.GetTypedHeaders().GetList<MediaTypeHeaderValue>(HeaderNames.Accept);

            var expected = new[] {
                new MediaTypeHeaderValue("text/plain", 0.9),
                new MediaTypeHeaderValue("text/other"),
                new MediaTypeHeaderValue("*/*"),
            }.ToList();
            Assert.Equal(expected, result);
        }
        public void GetListT_KnownTypeWithInvalidValue_Null()
        {
            var context = new DefaultHttpContext();
            context.Request.Headers[HeaderNames.Accept] = "invalid";

            var result = context.Request.GetTypedHeaders().GetList<MediaTypeHeaderValue>(HeaderNames.Accept);

            Assert.Null(result);
        }
        public void GetListT_UnknownTypeWithTryParseListAndInvalidValue_Null()
        {
            var context = new DefaultHttpContext();
            context.Request.Headers["custom"] = "invalid";

            var results = context.Request.GetTypedHeaders().GetList<TestHeaderValue>("custom");
            Assert.Null(results);
        }
 private static HttpResponse CreateResponse(IHeaderDictionary headers)
 {
     var context = new DefaultHttpContext();
     context.Features.Get<IHttpResponseFeature>().Headers = headers;
     return context.Response;
 }
 public Task SendFileWhenFileNotFoundThrows()
 {
     var response = new DefaultHttpContext().Response;
     return Assert.ThrowsAsync<FileNotFoundException>(() => response.SendFileAsync("foo"));
 }