public void IsLocal_should_return_false_if_urlString_is_empty()
        {
            // Given when
            var request = new FakeRequest("GET", string.Empty, string.Empty, string.Empty);

            // Then
            Assert.False(request.IsLocal());
        }
        public void IsLocal_should_return_false_if_userHostAddr_is_not_localhost()
        {
            // Given when
            var request = new FakeRequest("GET", "/", string.Empty, "86.13.73.12");

            // Then
            Assert.False(request.IsLocal());
        }
        public void IsLocal_should_return_true_if_userHostAddr_is_localhost_IPV4()
        {
            // Given when
            var request = new FakeRequest("POST", "/", string.Empty, "127.0.0.1");

            // Then
            Assert.True(request.IsLocal());
        }
        public void IsAjaxRequest_should_return_false_if_request_is_not_ajax()
        {
            // Given when
            var request = new FakeRequest("POST", "/");

            // Then
            Assert.False(request.IsAjaxRequest());
        }
        public void IsLocal_should_return_true_if_userHostAddr_is_localhost_IPV6()
        {
            // Given when
            var request = new FakeRequest("GET", "/", string.Empty, "::1");
            request.Url.HostName = "localhost";

            // Then
            Assert.True(request.IsLocal());
        }
Example #6
0
 public TokenizerFixture()
 {
     context = new NancyContext();
     request = new FakeRequest("GET", "/",
                               new Dictionary<string, IEnumerable<string>>
                               {
                                   {"User-Agent", new[] {"a fake user agent"}}
                               });
     context.Request = request;
 }
        public void Request_should_be_available_to_request_startup()
        {
            this.bootstrapper.Initialise();
            var engine = this.bootstrapper.GetEngine();
            var request = new FakeRequest("GET", "/");

            engine.HandleRequest(request);

            this.bootstrapper.RequestStartupLastRequest.ShouldNotBeNull();
            this.bootstrapper.RequestStartupLastRequest.ShouldBeSameAs(request);
        }
        public void Request_should_be_available_to_configure_request_container()
        {
            this.bootstrapper.Initialise();
            var engine = this.bootstrapper.GetEngine();
            var request = new FakeRequest("GET", "/");

            engine.HandleRequest(request);

            this.bootstrapper.ConfigureRequestContainerLastRequest.ShouldNotBeNull();
            this.bootstrapper.ConfigureRequestContainerLastRequest.ShouldBeSameAs(request);
        }
Example #9
0
        public void Should_set_url_scheme_to_https_if_Forwarded_header_exists()
        {
            var request = new FakeRequest("GET", "/",
               new Dictionary<string, IEnumerable<string>> { { "Forwarded", new[] { "for=192.0.2.60", "proto=https", "by=203.0.113.43" } } });

            var context = new NancyContext { Request = request };

            this.pipelines.BeforeRequest.Invoke(context, new CancellationToken());

            request.Url.Scheme.ShouldEqual("https");
        }
        public void Should_only_initialise_request_container_once_per_request()
        {
            this.bootstrapper.Initialise();
            var engine = this.bootstrapper.GetEngine();
            var request = new FakeRequest("GET", "/");
            var request2 = new FakeRequest("GET", "/");

            engine.HandleRequest(request);
            engine.HandleRequest(request2);

            bootstrapper.RequestContainerInitialisations.Any(kvp => kvp.Value > 1).ShouldBeFalse();
        }
        public void IsAjaxRequest_should_return_true_if_request_is_ajax()
        {
            // Given
            var headers = new Dictionary<string, IEnumerable<string>>
            {
                { "X-Requested-With", new[] { "XMLHttpRequest" } }
            };

            // When
            var request = new FakeRequest("POST", "/", headers);

            // Then
            Assert.True(request.IsAjaxRequest());
        }
        public void Should_allow_head_request_when_route_is_defined_for_get()
        {
            var request = new FakeRequest("HEAD", "/foo/bar");
            var routeCache = new FakeRouteCache(x =>
            {
                x.AddGetRoute("/foo/bar");
            });

            var resolvedRoute = this.resolver.Resolve(request, routeCache);

            resolvedRoute.ShouldNotBeNull();
            resolvedRoute.ShouldNotBeOfType<NotFoundRoute>();
            resolvedRoute.ShouldNotBeOfType<MethodNotAllowedRoute>();
        }
        public void Should_allow_options_request_when_route_is_defined()
        {
            // Given
            var request = new FakeRequest("OPTIONS", "/foo/bar");
            var context = new NancyContext { Request = request };
            var resolver = CreateResolver(x => x.AddGetRoute("/foo/bar"));

            // When
            var resolvedRoute = resolver.Resolve(context);

            // Then
            resolvedRoute.ShouldNotBeNull();
            resolvedRoute.Item1.ShouldBeOfType<OptionsRoute>();
        }
        public async Task Should_only_initialise_request_container_once_per_request()
        {
            // Given
            this.bootstrapper.Initialise();
            var engine = this.bootstrapper.GetEngine();
            var request = new FakeRequest("GET", "/");
            var request2 = new FakeRequest("GET", "/");

            // When
            await engine.HandleRequest(request);
            await engine.HandleRequest(request2);

            // Then
            bootstrapper.RequestContainerInitialisations.Any(kvp => kvp.Value > 1).ShouldBeFalse();
        }
        public void Should_allow_head_request_when_route_is_defined_for_get()
        {
            // Given
            var request = new FakeRequest("HEAD", "/foo/bar");
            var context = new NancyContext { Request = request };
            var resolver = CreateResolver(x => x.AddGetRoute("/bar/foo"));

            // When
            var resolvedRoute = resolver.Resolve(context);

            // Then
            resolvedRoute.ShouldNotBeNull();
            resolvedRoute.ShouldNotBeOfType<NotFoundRoute>();
            resolvedRoute.ShouldNotBeOfType<MethodNotAllowedRoute>();
        }
        public void Should_ignore_method_casing_when_resolving_routes()
        {
            var request = new FakeRequest("GeT", "/foo/bar");
            var routeCache = new FakeRouteCache(x =>
            {
                x.AddGetRoute("/foo/bar");
            });

            // When
            var resolvedRoute = this.resolver.Resolve(request, routeCache);

            // Then
            resolvedRoute.ShouldNotBeNull();
            resolvedRoute.ShouldNotBeOfType<NotFoundRoute>();
            resolvedRoute.ShouldNotBeOfType<MethodNotAllowedRoute>();
        }
        public void Should_allow_head_request_when_route_is_defined_for_get()
        {
            // Given
            var request = new FakeRequest("HEAD", "/foo/bar");
            var context = new NancyContext();
            context.Request = request;
            var routeCache = new FakeRouteCache(x =>
            {
                x.AddGetRoute("/foo/bar");
            });

            // When
            var resolvedRoute = this.resolver.Resolve(context, routeCache);

            // Then
            resolvedRoute.ShouldNotBeNull();
            resolvedRoute.ShouldNotBeOfType<NotFoundRoute>();
            resolvedRoute.ShouldNotBeOfType<MethodNotAllowedRoute>();
        }
Example #18
0
        public CsrfFixture()
        {
            this.pipelines = new MockPipelines();

            this.cryptographyConfiguration = CryptographyConfiguration.Default;
            this.objectSerializer = new DefaultObjectSerializer();
            var csrfStartup = new CsrfApplicationStartup(
                this.cryptographyConfiguration,
                this.objectSerializer,
                new DefaultCsrfTokenValidator(this.cryptographyConfiguration));

            csrfStartup.Initialize(this.pipelines);
            Csrf.Enable(this.pipelines);

            this.request = new FakeRequest("GET", "/");

            this.optionsRequest = new FakeRequest("OPTIONS", "/");

            this.response = new Response();
        }
        public void Should_choose_root_route_over_one_with_capture_if_requesting_root_uri()
        {
            var request = new FakeRequest("get", "/");
            var context = new NancyContext { Request = request };
            var routeCache = new FakeRouteCache(x =>
            {
                x.AddGetRoute("/{name}", "module-key-second");
                x.AddGetRoute("/", "module-key-first");
                x.AddGetRoute("/{name}", "module-key-second");
            });
            A.CallTo(() => this.matcher.Match(request.Path, "/")).Returns(
                new FakeRoutePatternMatchResult(x => x.IsMatch(true)));
            A.CallTo(() => this.matcher.Match(request.Path, "/{name}")).Returns(
                new FakeRoutePatternMatchResult(x => x.IsMatch(true).AddParameter("name", "fake values")));

            // When
            this.resolver.Resolve(context, routeCache);

            // Then
            A.CallTo(() => this.catalog.GetModuleByKey("module-key-first", context)).MustHaveHappened();
        }
        public void Should_return_route_whos_filter_returns_true_when_there_is_also_a_matching_route_with_a_failing_filter()
        {
            // Given
            var moduleCatalog = new FakeModuleCatalog();
            var routeCache = new RouteCache(moduleCatalog, new FakeModuleKeyGenerator(), A.Fake<INancyContextFactory>());
            var specificResolver = new DefaultRouteResolver(moduleCatalog, this.matcher, this.moduleBuilder);
            var request = new FakeRequest("GET", "/filt");
            var context = new NancyContext {Request = request};

            // When
            var route = specificResolver.Resolve(context, routeCache).Item1;

            // Then
            route.Description.Condition(context).ShouldBeTrue();
        }
        public void Should_set_parameters_on_resolved_route_to_parameteres_that_was_matched()
        {
            // Given
            var request = new FakeRequest("get", "/foo/bar");
            var context = new NancyContext();
            context.Request = request;
            var routeCache = new FakeRouteCache(x =>
            {
                x.AddGetRoute("/foo/bar", "module-key");
            });

            // When
            var resolvedRoute = this.resolver.Resolve(context, routeCache);

            // Then
            resolvedRoute.ShouldNotBeOfType<NotFoundRoute>();
            resolvedRoute.ShouldNotBeOfType<MethodNotAllowedRoute>();
            ((string)resolvedRoute.Item2["foo"]).ShouldEqual("bar");
        }
        public void Should_set_action_on_resolved_route()
        {
            // Given
            var request = new FakeRequest("get", "/foo/bar");
            var context = new NancyContext();
            context.Request = request;
            var routeCache = new FakeRouteCache(x =>
            {
                x.AddGetRoute("/foo/bar", "module-key");
            });

            // When
            var resolvedRoute = this.resolver.Resolve(context, routeCache).Item1;

            // Then
            resolvedRoute.ShouldNotBeOfType<NotFoundRoute>();
            resolvedRoute.ShouldNotBeOfType<MethodNotAllowedRoute>();
            resolvedRoute.Action.ShouldBeSameAs(this.expectedAction);
        }
        public void Should_return_the_route_with_the_most_specific_path_matches()
        {
            // The most specific path match is the one with the most matching segments (delimited by '/') and the
            // least parameter captures (i.e. the most exact matching segments)
            // Given
            var request = new FakeRequest("get", "/foo/bar/me");
            var context = new NancyContext {Request = request};
            var routeCache = new FakeRouteCache(x =>
            {
                x.AddGetRoute("/foo/{bar}", "module-key-first");
                x.AddGetRoute("/foo/{bar}/{two}", "module-key-third");
                x.AddGetRoute("/foo/bar/{two}", "module-key-second");
                x.AddGetRoute("/foo/{bar}/{two}", "module-key-third");
            });

            this.expectedModule = new FakeNancyModule(x => x.AddGetRoute("/foo/bar/{two}", this.expectedAction));

            A.CallTo(() => this.matcher.Match(request.Path, "/foo/bar/{two}")).Returns(
                new FakeRoutePatternMatchResult(x => x.IsMatch(true).AddParameter("two", "fake values")));

            A.CallTo(() => this.matcher.Match(request.Path, "/foo/{bar}/{two}")).Returns(
                new FakeRoutePatternMatchResult(x => x.IsMatch(true)
                    .AddParameter("bar", "fake values")
                    .AddParameter("two", "fake values")));

            A.CallTo(() => this.matcher.Match(request.Path, "/foo/{bar}")).Returns(
                new FakeRoutePatternMatchResult(x => x.IsMatch(true).AddParameter("bar", "fake value")));

            // When
            this.resolver.Resolve(context, routeCache);

            // Then
            A.CallTo(() => this.catalog.GetModuleByKey("module-key-second", context)).MustHaveHappened();
        }
        public void Should_return_the_first_route_that_is_an_exact_match_over_any_other()
        {
            // Given
            var request = new FakeRequest("get", "/foo/bar");
            var context = new NancyContext {Request = request};
            var routeCache = new FakeRouteCache(x =>
            {
                x.AddGetRoute("/foo/{bar}", "module-key-parameters");
                x.AddGetRoute("/{foo}/{bar}", "module-key-two-parameters");
                x.AddGetRoute("/foo/bar", "module-key-no-parameters");
                x.AddGetRoute("/foo/bar", "module-key-no-parameters-second");
                x.AddGetRoute("/foo/{bar}", "module-key-parameters");
                x.AddGetRoute("/{foo}/{bar}", "module-key-two-parameters");
            });

            A.CallTo(() => this.matcher.Match(request.Path, "/foo/bar")).Returns(
                new FakeRoutePatternMatchResult(x => x.IsMatch(true)));

            A.CallTo(() => this.matcher.Match(request.Path, "/foo/{bar}")).Returns(
                new FakeRoutePatternMatchResult(x => x.IsMatch(true).AddParameter("bar", "fake value")));

            A.CallTo(() => this.matcher.Match(request.Path, "/foo/{bar}")).Returns(
                new FakeRoutePatternMatchResult(x => x.IsMatch(true)
                    .AddParameter("foo", "fake value")
                    .AddParameter("bar", "fake value")));
            // When
            this.resolver.Resolve(context, routeCache);

            // Then
            A.CallTo(() => this.catalog.GetModuleByKey("module-key-no-parameters", context)).MustHaveHappened();
        }
        public void Should_return_route_with_path_set_to_request_uri_when_single_route_could_be_resolved()
        {
            // Given
            var request = new FakeRequest("GET", "/foo/bar");
            var context = new NancyContext();
            context.Request = request;
            var routeCache = new FakeRouteCache(x =>
            {
                x.AddGetRoute("/foo/bar");
            });

            // When
            var resolvedRoute = this.resolver.Resolve(context, routeCache);

            // Then
            resolvedRoute.ShouldNotBeOfType<NotFoundRoute>();
            resolvedRoute.Item1.Description.Path.ShouldEqual(request.Path);
        }
        public void Should_return_prereq_and_postreq_from_module()
        {
            // Given
            var moduleCatalog = A.Fake<INancyModuleCatalog>();
            A.CallTo(() => moduleCatalog.GetAllModules(A<NancyContext>.Ignored)).Returns(new[] { new FakeNancyModuleWithPreAndPostHooks() });
            A.CallTo(() => moduleCatalog.GetModuleByKey(A<string>.Ignored, A<NancyContext>.Ignored)).Returns(
                new FakeNancyModuleWithPreAndPostHooks());

            var routeCache = new RouteCache(moduleCatalog, new FakeModuleKeyGenerator(), A.Fake<INancyContextFactory>());
            var specificResolver = new DefaultRouteResolver(moduleCatalog, this.matcher, this.moduleBuilder);
            var request = new FakeRequest("GET", "/PrePost");
            var context = new NancyContext { Request = request };

            // When
            var result = specificResolver.Resolve(context, routeCache);

            // Then
            result.Item3.ShouldNotBeNull();
            result.Item4.ShouldNotBeNull();
        }
Example #27
0
        public void Should_fail_to_detokenize_when_additional_items_do_not_match()
        {
            var tokenizer = CreateTokenizer();

            var identity = new FakeUserIdentity
            {
                UserName = "******",
                Claims = new[] { "claim1", "claim2" }
            };

            var token = tokenizer.Tokenize(identity, context);

            var badRequest = new FakeRequest("GET", "/",
                                             new Dictionary<string, IEnumerable<string>>
                                             {
                                                 {"User-Agent", new[] {"uh oh! no matchey!"}}
                                             });
            var badContext = new NancyContext
            {
                Request = badRequest
            };

            var detokenizedIdentity = tokenizer.Detokenize(token, badContext);

            detokenizedIdentity.ShouldBeNull();
        }
        public void Should_return_route_with_module_returned_by_module_builder()
        {
            // Given
            var request = new FakeRequest("GET", "/foo/bar");
            var context = new NancyContext { Request = request };
            var routeCache = new FakeRouteCache(x => x.AddGetRoute("/foo/bar"));

            var moduleReturnedByBuilder = new FakeNancyModule(x => x.AddGetRoute("/bar/foo"));
            A.CallTo(() => this.moduleBuilder.BuildModule(A<NancyModule>.Ignored, A<NancyContext>.Ignored)).Returns(
                moduleReturnedByBuilder);

            // When
            var route = this.resolver.Resolve(context, routeCache);

            // Then
            route.Item1.Description.Path.ShouldEqual("/bar/foo");
        }
        public async Task Should_invoke_route_resolver_with_passed_in_accept_headers_when_path_does_not_contain_file_extensions()
        {
            // Given
            var expectedAcceptHeaders = new List<Tuple<string, decimal>>
            {
                { new Tuple<string, decimal>("application/json", 0.8m) },
                { new Tuple<string, decimal>("application/xml", 0.4m) }
            };

            var requestedAcceptHeaders =
                new List<Tuple<string, decimal>>();

            var request = new FakeRequest("GET", "/")
            {
                Headers = { Accept = expectedAcceptHeaders }
            };

            var context =
                new NancyContext { Request = request };

            var resolvedRoute = new ResolveResult(
               new FakeRoute(),
               DynamicDictionary.Empty,
               null,
               null,
               null);

            A.CallTo(() => this.routeResolver.Resolve(context))
                .Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())
                .Returns(resolvedRoute);

            // When
            await this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            requestedAcceptHeaders.ShouldHaveCount(2);
            requestedAcceptHeaders[0].Item1.ShouldEqual("application/json");
            requestedAcceptHeaders[0].Item2.ShouldEqual(0.8m);
            requestedAcceptHeaders[1].Item1.ShouldEqual("application/xml");
            requestedAcceptHeaders[1].Item2.ShouldEqual(0.4m);
        }
        public void Should_return_route_with_most_parameter_captures_when_multiple_matches_with_parameters_are_available()
        {
            // Given
            var request = new FakeRequest("get", "/foo/bar/foo");
            var context = new NancyContext {Request = request};
            var routeCache = new FakeRouteCache(x =>
            {
                x.AddGetRoute("/foo/{bar}/{foo}", "module-key-two-parameters");
                x.AddGetRoute("/foo/{bar}", "module-key-one-parameter");
            });

            A.CallTo(() => this.matcher.Match(request.Path, "/foo/{bar}")).Returns(
                new FakeRoutePatternMatchResult(x => x.IsMatch(true).AddParameter("bar", "fake value")));

            A.CallTo(() => this.matcher.Match(request.Path, "/foo/{bar}/{foo}")).Returns(
                new FakeRoutePatternMatchResult(x => x.IsMatch(true)
                    .AddParameter("foo", "fake value")
                    .AddParameter("bar", "fake value 2")));

            // When
            this.resolver.Resolve(context, routeCache);

            // Then
            A.CallTo(() => this.catalog.GetModuleByKey("module-key-two-parameters", context)).MustHaveHappened();
        }