org.springframework.mock.web.server.MockServerWebExchange Java Examples

The following examples show how to use org.springframework.mock.web.server.MockServerWebExchange. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RequestHeaderToRequestUriGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 7 votes vote down vote up
@Test
public void filterDoesNotChangeRequestUriIfHeaderIsInvalid() throws Exception {
	RequestHeaderToRequestUriGatewayFilterFactory factory = new RequestHeaderToRequestUriGatewayFilterFactory();
	GatewayFilter filter = factory.apply(c -> c.setName("X-CF-Forwarded-Url"));
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.header("X-CF-Forwarded-Url", "example").build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR,
			URI.create("http://localhost"));
	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);
	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());
	filter.filter(exchange, filterChain);
	ServerWebExchange webExchange = captor.getValue();
	URI uri = (URI) webExchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).isNotNull();
	assertThat(uri.toURL().toString()).isEqualTo("http://localhost");
}
 
Example #2
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultPort() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.header(HttpHeaders.HOST, "myhost").build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers).containsKeys(X_FORWARDED_FOR_HEADER, X_FORWARDED_HOST_HEADER,
			X_FORWARDED_PORT_HEADER, X_FORWARDED_PROTO_HEADER);

	assertThat(headers.getFirst(X_FORWARDED_FOR_HEADER)).isEqualTo("10.0.0.1");
	assertThat(headers.getFirst(X_FORWARDED_HOST_HEADER)).isEqualTo("localhost");
	assertThat(headers.getFirst(X_FORWARDED_PORT_HEADER)).isEqualTo("80");
	assertThat(headers.getFirst(X_FORWARDED_PROTO_HEADER)).isEqualTo("http");
}
 
Example #3
Source File: RemoveRequestParameterGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void removeRequestParameterFilterShouldHandleRemainingParamsWhichRequiringEncoding() {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.queryParam("foo", "bar").queryParam("aaa", "abc xyz")
			.queryParam("bbb", "[xyz").queryParam("ccc", ",xyz").build();
	exchange = MockServerWebExchange.from(request);
	NameConfig config = new NameConfig();
	config.setName("foo");
	GatewayFilter filter = new RemoveRequestParameterGatewayFilterFactory()
			.apply(config);

	filter.filter(exchange, filterChain);

	ServerHttpRequest actualRequest = captor.getValue().getRequest();
	assertThat(actualRequest.getQueryParams()).doesNotContainKey("foo");
	assertThat(actualRequest.getQueryParams()).containsEntry("aaa",
			singletonList("abc xyz"));
	assertThat(actualRequest.getQueryParams()).containsEntry("bbb",
			singletonList("[xyz"));
	assertThat(actualRequest.getQueryParams()).containsEntry("ccc",
			singletonList(",xyz"));
}
 
Example #4
Source File: RemoveRequestParameterGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void removeRequestParameterFilterShouldOnlyRemoveSpecifiedParam() {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.queryParam("foo", "bar").queryParam("abc", "xyz").build();
	exchange = MockServerWebExchange.from(request);
	NameConfig config = new NameConfig();
	config.setName("foo");
	GatewayFilter filter = new RemoveRequestParameterGatewayFilterFactory()
			.apply(config);

	filter.filter(exchange, filterChain);

	ServerHttpRequest actualRequest = captor.getValue().getRequest();
	assertThat(actualRequest.getQueryParams()).doesNotContainKey("foo");
	assertThat(actualRequest.getQueryParams()).containsEntry("abc",
			singletonList("xyz"));
}
 
Example #5
Source File: CookieCsrfFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cookieNotSetIfTokenInRequest() {
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            assertThat(filterExchange.getResponse().getCookies().getFirst(CSRF_COOKIE_NAME)).isNull();
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest
            .post(TEST_URL)
            .cookie(new HttpCookie(CSRF_COOKIE_NAME, "csrf_token"))
    );
    exchange.getAttributes().put(CsrfToken.class.getName(), Mono.just(new DefaultCsrfToken(CSRF_COOKIE_NAME, "_csrf", "some token")));
    this.filter.filter(exchange, filterChain).block();
}
 
Example #6
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void appendsValues() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost:8080/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.header(X_FORWARDED_FOR_HEADER, "192.168.0.2")
			.header(X_FORWARDED_HOST_HEADER, "example.com")
			.header(X_FORWARDED_PORT_HEADER, "443")
			.header(X_FORWARDED_PROTO_HEADER, "https").build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers).containsKeys(X_FORWARDED_FOR_HEADER, X_FORWARDED_HOST_HEADER,
			X_FORWARDED_PORT_HEADER, X_FORWARDED_PROTO_HEADER);

	assertThat(headers.getFirst(X_FORWARDED_FOR_HEADER))
			.isEqualTo("192.168.0.2,10.0.0.1");
	assertThat(headers.getFirst(X_FORWARDED_HOST_HEADER))
			.isEqualTo("example.com,localhost:8080");
	assertThat(headers.getFirst(X_FORWARDED_PORT_HEADER)).isEqualTo("443,8080");
	assertThat(headers.getFirst(X_FORWARDED_PROTO_HEADER)).isEqualTo("https,http");
}
 
Example #7
Source File: SetPathGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void testFilter(String template, String expectedPath,
		HashMap<String, String> variables) {
	GatewayFilter filter = new SetPathGatewayFilterFactory()
			.apply(c -> c.setTemplate(template));

	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.build();

	ServerWebExchange exchange = MockServerWebExchange.from(request);
	ServerWebExchangeUtils.putUriTemplateVariables(exchange, variables);

	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);

	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());

	filter.filter(exchange, filterChain);

	ServerWebExchange webExchange = captor.getValue();

	assertThat(webExchange.getRequest().getURI()).hasPath(expectedPath);
	LinkedHashSet<URI> uris = webExchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	assertThat(uris).contains(request.getURI());
}
 
Example #8
Source File: RequestHeaderToRequestUriGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void filterDoesNotChangeRequestUriIfHeaderIsAbsent() {
	RequestHeaderToRequestUriGatewayFilterFactory factory = new RequestHeaderToRequestUriGatewayFilterFactory();
	GatewayFilter filter = factory.apply(c -> c.setName("X-CF-Forwarded-Url"));
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR,
			URI.create("http://localhost"));
	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);
	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());
	filter.filter(exchange, filterChain);
	ServerWebExchange webExchange = captor.getValue();
	URI uri = (URI) webExchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).isNotNull();
	assertThat(uri.toString()).isEqualTo("http://localhost");
}
 
Example #9
Source File: RequestHeaderToRequestUriGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void filterChangeRequestUri() {
	RequestHeaderToRequestUriGatewayFilterFactory factory = new RequestHeaderToRequestUriGatewayFilterFactory();
	GatewayFilter filter = factory.apply(c -> c.setName("X-CF-Forwarded-Url"));
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.header("X-CF-Forwarded-Url", "https://example.com").build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR,
			URI.create("http://localhost"));
	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);
	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());
	filter.filter(exchange, filterChain);
	ServerWebExchange webExchange = captor.getValue();
	URI uri = (URI) webExchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).isNotNull();
	assertThat(uri.toString()).isEqualTo("https://example.com");
}
 
Example #10
Source File: CachingHttpHeadersFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheHeadersSetWhenPathMatches() {
    long now = System.currentTimeMillis();
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            HttpHeaders headers = filterExchange.getResponse().getHeaders();
            assertThat(headers.getPragma()).isEqualTo("cache");
            assertThat(headers.getCacheControl()).isEqualTo("max-age=172800000, public");
            assertThat(headers.getExpires() - now).isBetween(ttl - 1000, ttl + 1000);
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest.get("/app/foo")
    );
    this.filter.filter(exchange, filterChain).block();
}
 
Example #11
Source File: CachingHttpHeadersFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheHeadersNotSetWhenPathDoesntMatch() {
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            HttpHeaders headers = filterExchange.getResponse().getHeaders();
            assertThat(headers.getPragma()).isNull();
            assertThat(headers.getCacheControl()).isNull();;
            assertThat(headers.getExpires()).isEqualTo(-1);
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest.get("/foo/foo")
    );
    this.filter.filter(exchange, filterChain).block();
}
 
Example #12
Source File: CookieCsrfFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cookieSetInResponse() {
    final String token = "test_token";
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            ResponseCookie cookie = filterExchange.getResponse().getCookies().getFirst(CSRF_COOKIE_NAME);
            assertThat(cookie).isNotNull();
            assertThat(cookie.getName()).isEqualTo(CSRF_COOKIE_NAME);
            assertThat(cookie.getValue()).isEqualTo(token);
            assertThat(cookie.getPath()).isEqualTo("/");
            assertThat(cookie.getMaxAge()).isEqualTo(Duration.ofSeconds(-1));
            assertThat(cookie.isHttpOnly()).isFalse();
            assertThat(cookie.isSecure()).isFalse();
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest.post(TEST_URL)
    );
    exchange.getAttributes().put(CsrfToken.class.getName(), Mono.just(new DefaultCsrfToken(CSRF_COOKIE_NAME, "_csrf", token)));
    this.filter.filter(exchange, filterChain).block();
}
 
Example #13
Source File: ForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void unresolvedRemoteAddressFallsBackToHostName() throws UnknownHostException {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/get")
			.remoteAddress(
					InetSocketAddress.createUnresolved("unresolvable-hostname", 80))
			.build();

	ForwardedHeadersFilter filter = new ForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers.get(FORWARDED_HEADER)).hasSize(1);

	List<Forwarded> forwardeds = ForwardedHeadersFilter
			.parse(headers.get(FORWARDED_HEADER));

	assertThat(forwardeds).hasSize(1);
	Forwarded forwarded = forwardeds.get(0);

	assertThat(forwarded.getValues()).containsEntry("proto", "http")
			.containsEntry("for", "\"unresolvable-hostname:80\"");
}
 
Example #14
Source File: ApiVersionWebFilterTest.java    From spring-cloud-open-service-broker with Apache License 2.0 6 votes vote down vote up
private void setUpVersionResponse(String version) {
	MockServerHttpRequest request;
	if (version == null) {
		request = MockServerHttpRequest
				.get(V2_API_PATH_PATTERN)
				.build();
	}
	else {
		request = MockServerHttpRequest
				.get(V2_API_PATH_PATTERN)
				.header("header", version)
				.build();
	}
	this.exchange = MockServerWebExchange.from(request);
	MockitoAnnotations.initMocks(this);
	exchange.getResponse().setStatusCode(HttpStatus.OK);
	given(chain.filter(exchange))
			.willReturn(Mono.empty());
}
 
Example #15
Source File: ForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void noHostHeader() throws UnknownHostException {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.build();

	ForwardedHeadersFilter filter = new ForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers.get(FORWARDED_HEADER)).hasSize(1);

	List<Forwarded> forwardeds = ForwardedHeadersFilter
			.parse(headers.get(FORWARDED_HEADER));

	assertThat(forwardeds).hasSize(1);
	Forwarded forwarded = forwardeds.get(0);

	assertThat(forwarded.getValues()).containsEntry("proto", "http")
			.containsEntry("for", "\"10.0.0.1:80\"");
}
 
Example #16
Source File: TraceResponseHttpHeadersFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_report_span_when_span_was_present_in_attribute() {
	HttpHeadersFilter filter = TraceResponseHttpHeadersFilter
			.create(this.httpTracing);
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.set("b3", "52f112af7472aff0-53e6ab6fc5dfee58");
	MockServerHttpRequest request = MockServerHttpRequest.post("foo/bar")
			.headers(httpHeaders).build();
	MockServerWebExchange exchange = MockServerWebExchange.builder(request).build();
	exchange.getAttributes().put(TraceResponseHttpHeadersFilter.SPAN_ATTRIBUTE,
			this.tracing.tracer().nextSpan());

	filter.filter(httpHeaders, exchange);

	BDDAssertions.then(this.spans).isNotEmpty();
}
 
Example #17
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void prefixAddedWithoutTrailingSlash() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("https://originalhost:8080/foo/bar")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();
	filter.setPrefixAppend(true);
	filter.setPrefixEnabled(true);

	ServerWebExchange exchange = MockServerWebExchange.from(request);
	LinkedHashSet<URI> originalUris = new LinkedHashSet<>();
	originalUris.add(UriComponentsBuilder
			.fromUriString("https://originalhost:8080/foo/bar").build().toUri());
	exchange.getAttributes().put(GATEWAY_ORIGINAL_REQUEST_URL_ATTR, originalUris);
	URI requestUri = UriComponentsBuilder.fromUriString("https://routedservice:8090/")
			.build().toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUri);

	HttpHeaders headers = filter.filter(request.getHeaders(), exchange);

	assertThat(headers.getFirst(X_FORWARDED_PREFIX_HEADER)).isEqualTo("/foo/bar");
}
 
Example #18
Source File: PrefixPathGatewayFilterFactoryTest.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void testPrefixPathFilter(String prefix, String path, String expectedPath) {
	GatewayFilter filter = new PrefixPathGatewayFilterFactory()
			.apply(c -> c.setPrefix(prefix));
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost" + path).build();

	ServerWebExchange exchange = MockServerWebExchange.from(request);

	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);

	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());

	filter.filter(exchange, filterChain);

	ServerWebExchange webExchange = captor.getValue();

	assertThat(webExchange.getRequest().getURI()).hasPath(expectedPath);
	LinkedHashSet<URI> uris = webExchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	assertThat(uris).contains(request.getURI());
}
 
Example #19
Source File: TraceRequestHttpHeadersFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_set_tracing_headers() {
	HttpHeadersFilter filter = TraceRequestHttpHeadersFilter.create(this.httpTracing);
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.set("X-Hello", "World");
	MockServerHttpRequest request = MockServerHttpRequest.post("foo/bar")
			.headers(httpHeaders).build();
	MockServerWebExchange exchange = MockServerWebExchange.builder(request).build();

	HttpHeaders filteredHeaders = filter.filter(requestHeaders(httpHeaders),
			exchange);

	BDDAssertions.then(filteredHeaders.get("X-B3-TraceId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-B3-SpanId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-Hello"))
			.isEqualTo(Collections.singletonList("World"));
	BDDAssertions.then(filteredHeaders.get("X-Hello-Request"))
			.isEqualTo(Collections.singletonList("Request World"));
	BDDAssertions
			.then((Object) exchange
					.getAttribute(TraceRequestHttpHeadersFilter.SPAN_ATTRIBUTE))
			.isNotNull();
}
 
Example #20
Source File: TraceRequestHttpHeadersFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_reuse_headers_only_from_input_since_exchange_may_contain_already_ignored_headers() {
	HttpHeadersFilter filter = TraceRequestHttpHeadersFilter.create(this.httpTracing);
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.set("X-Hello", "World");
	MockServerHttpRequest request = MockServerHttpRequest.post("foo/bar")
			.headers(httpHeaders).build();
	MockServerWebExchange exchange = MockServerWebExchange.builder(request).build();

	HttpHeaders filteredHeaders = filter.filter(requestHeaders(), exchange);

	BDDAssertions.then(filteredHeaders.get("X-B3-TraceId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-B3-SpanId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-Hello")).isNullOrEmpty();
	BDDAssertions
			.then((Object) exchange
					.getAttribute(TraceRequestHttpHeadersFilter.SPAN_ATTRIBUTE))
			.isNotNull();
}
 
Example #21
Source File: PropertiesTagsProviderTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
	contextRunner
			.withConfiguration(
					AutoConfigurations.of(GatewayMetricsAutoConfiguration.class))
			.withPropertyValues("spring.cloud.gateway.metrics.tags.foo1=bar1",
					"spring.cloud.gateway.metrics.tags.foo2=bar2")
			.run(context -> {
				PropertiesTagsProvider provider = context
						.getBean(PropertiesTagsProvider.class);
				Tags tags = provider.apply(MockServerWebExchange
						.from(MockServerHttpRequest.get("").build()));
				assertThat(tags).isEqualTo(Tags.of("foo1", "bar1", "foo2", "bar2"));
			});

}
 
Example #22
Source File: TraceRequestHttpHeadersFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_set_tracing_headers_with_multiple_values() {
	HttpHeadersFilter filter = TraceRequestHttpHeadersFilter.create(this.httpTracing);
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.add("X-Hello-Request", "Request World");
	httpHeaders.addAll("X-Hello", Arrays.asList("World1", "World2"));
	MockServerHttpRequest request = MockServerHttpRequest.post("foo/bar")
			.headers(httpHeaders).build();
	MockServerWebExchange exchange = MockServerWebExchange.builder(request).build();

	HttpHeaders filteredHeaders = filter.filter(httpHeaders, exchange);

	BDDAssertions.then(filteredHeaders.get("X-B3-TraceId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-B3-SpanId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-Hello"))
			.isEqualTo(Arrays.asList("World1", "World2"));
	BDDAssertions.then(filteredHeaders.get("X-Hello-Request"))
			.isEqualTo(Collections.singletonList("Request World"));
	BDDAssertions
			.then((Object) exchange
					.getAttribute(TraceRequestHttpHeadersFilter.SPAN_ATTRIBUTE))
			.isNotNull();
}
 
Example #23
Source File: ForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void forwardedHeaderDoesNotExist() throws UnknownHostException {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.header(HttpHeaders.HOST, "myhost").build();

	ForwardedHeadersFilter filter = new ForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers.get(FORWARDED_HEADER)).hasSize(1);

	List<Forwarded> forwardeds = ForwardedHeadersFilter
			.parse(headers.get(FORWARDED_HEADER));

	assertThat(forwardeds).hasSize(1);
	Forwarded forwarded = forwardeds.get(0);

	assertThat(forwarded.getValues()).containsEntry("host", "myhost")
			.containsEntry("proto", "http").containsEntry("for", "\"10.0.0.1:80\"");
}
 
Example #24
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void allDisabled() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost:8080/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();
	filter.setForEnabled(false);
	filter.setHostEnabled(false);
	filter.setPortEnabled(false);
	filter.setProtoEnabled(false);
	filter.setPrefixEnabled(false);

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers).isEmpty();
}
 
Example #25
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void remoteAddressIsNull() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost:8080/get").header(HttpHeaders.HOST, "myhost")
			.build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers).containsKeys(X_FORWARDED_HOST_HEADER, X_FORWARDED_PORT_HEADER,
			X_FORWARDED_PROTO_HEADER);

	assertThat(headers.getFirst(X_FORWARDED_HOST_HEADER)).isEqualTo("localhost:8080");
	assertThat(headers.getFirst(X_FORWARDED_PORT_HEADER)).isEqualTo("8080");
	assertThat(headers.getFirst(X_FORWARDED_PROTO_HEADER)).isEqualTo("http");
}
 
Example #26
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void xForwardedHeadersDoNotExist() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost:8080/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.header(HttpHeaders.HOST, "myhost").build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers).containsKeys(X_FORWARDED_FOR_HEADER, X_FORWARDED_HOST_HEADER,
			X_FORWARDED_PORT_HEADER, X_FORWARDED_PROTO_HEADER);

	assertThat(headers.getFirst(X_FORWARDED_FOR_HEADER)).isEqualTo("10.0.0.1");
	assertThat(headers.getFirst(X_FORWARDED_HOST_HEADER)).isEqualTo("localhost:8080");
	assertThat(headers.getFirst(X_FORWARDED_PORT_HEADER)).isEqualTo("8080");
	assertThat(headers.getFirst(X_FORWARDED_PROTO_HEADER)).isEqualTo("http");
}
 
Example #27
Source File: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void happyPathWithAttributeRatherThanScheme() {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("ws://localhost/get?a=b").build();

	URI lbUri = URI.create("ws://service1?a=b");

	exchange = MockServerWebExchange.from(request);
	exchange.getAttributes().put(GATEWAY_SCHEME_PREFIX_ATTR, "lb");

	ServerWebExchange webExchange = testFilter(exchange, lbUri);
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("ws").hasHost("service1-host1").hasParameter("a", "b");
}
 
Example #28
Source File: HttpHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void httpHeadersFilterTests() {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost:8080/get").header("X-A", "aValue")
			.header("X-B", "bValue").header("X-C", "cValue").build();

	List<HttpHeadersFilter> filters = Arrays.asList(
			(h, e) -> HttpHeadersFilterTests.this.filter(h, "X-A"),
			(h, e) -> HttpHeadersFilterTests.this.filter(h, "X-B"));

	HttpHeaders headers = HttpHeadersFilter.filterRequest(filters,
			MockServerWebExchange.from(request));

	assertThat(headers).containsOnlyKeys("X-C");
}
 
Example #29
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void noPrefixToInfer() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("https://originalhost:8080/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();
	filter.setPrefixAppend(true);
	filter.setPrefixEnabled(true);
	filter.setForEnabled(false);
	filter.setHostEnabled(false);
	filter.setPortEnabled(false);
	filter.setProtoEnabled(false);

	ServerWebExchange exchange = MockServerWebExchange.from(request);
	LinkedHashSet<URI> originalUris = new LinkedHashSet<>();
	originalUris.add(UriComponentsBuilder
			.fromUriString("https://originalhost:8080/get/").build().toUri());
	exchange.getAttributes().put(GATEWAY_ORIGINAL_REQUEST_URL_ATTR, originalUris);
	URI requestUri = UriComponentsBuilder
			.fromUriString("https://routedservice:8090/get").build().toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUri);

	HttpHeaders headers = filter.filter(request.getHeaders(), exchange);

	assertThat(headers).isEmpty();
}
 
Example #30
Source File: HttpHeadersFilterMixedTypeTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void relevantDownstreamFiltersShouldActOnHeaders() {
	MockServerHttpRequest mockRequest = MockServerHttpRequest.get("/get")
			.header("header1", "value1").header("header2", "value2")
			.header("header3", "value3").build();

	HttpHeadersFilter filter1 = filterRemovingHeaders(Type.RESPONSE, "header1");

	HttpHeadersFilter filter2 = filterRemovingHeaders(Type.REQUEST, "header2");

	HttpHeaders result = HttpHeadersFilter.filterRequest(
			Arrays.asList(filter1, filter2), MockServerWebExchange.from(mockRequest));

	assertThat(result).containsOnlyKeys("header1", "header3");
}