<commit_before>/*
 * Copyright 2002-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.security.web.server.csrf;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import reactor.test.publisher.PublisherProbe;

import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.mock.web.server.MockServerWebExchange.from;
import static org.springframework.web.reactive.function.BodyInserters.fromMultipartData;

/**
 * @author <NAME>
 * @author <NAME>
 * @since 5.0
 */
@RunWith(MockitoJUnitRunner.class)
public class CsrfWebFilterTests {
	@Mock
	private WebFilterChain chain;
	@Mock
	private ServerCsrfTokenRepository repository;

	private CsrfToken token = new DefaultCsrfToken("csrf", "CSRF", "a");

	private CsrfWebFilter csrfFilter = new CsrfWebFilter();

	private MockServerWebExchange get = from(
		MockServerHttpRequest.get("/"));

	private ServerWebExchange post = from(
		MockServerHttpRequest.post("/"));

	@Test
	public void filterWhenGetThenSessionNotCreatedAndChainContinues() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		when(this.chain.filter(this.get)).thenReturn(chainResult.mono());

		Mono<Void> result = this.csrfFilter.filter(this.get, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		Mono<Boolean> isSessionStarted = this.get.getSession()
			.map(WebSession::isStarted);
		StepVerifier.create(isSessionStarted)
			.expectNext(false)
			.verifyComplete();

		chainResult.assertWasSubscribed();
	}

	@Test
	public void filterWhenPostAndNoTokenThenCsrfException() {
		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndRequestMissingTokenThenCsrfException() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		when(this.repository.loadToken(any()))
			.thenReturn(Mono.just(this.token));

		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);


		StepVerifier.create(result)
			.verifyComplete();

		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamInvalidTokenThenCsrfException() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		when(this.repository.loadToken(any()))
			.thenReturn(Mono.just(this.token));
		this.post = from(MockServerHttpRequest.post("/")
			.body(this.token.getParameterName() + "="+this.token.getToken()+"INVALID"));

		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamValidTokenThenContinues() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		when(this.chain.filter(any())).thenReturn(chainResult.mono());

		this.csrfFilter.setCsrfTokenRepository(this.repository);
		when(this.repository.loadToken(any()))
			.thenReturn(Mono.just(this.token));
		when(this.repository.generateToken(any()))
			.thenReturn(Mono.just(this.token));
		this.post = from(MockServerHttpRequest.post("/")
			.contentType(MediaType.APPLICATION_FORM_URLENCODED)
			.body(this.token.getParameterName() + "="+this.token.getToken()));

		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		chainResult.assertWasSubscribed();
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndHeaderInvalidTokenThenCsrfException() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		when(this.repository.loadToken(any()))
			.thenReturn(Mono.just(this.token));
		this.post = from(MockServerHttpRequest.post("/")
			.header(this.token.getHeaderName(), this.token.getToken()+"INVALID"));

		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndHeaderValidTokenThenContinues() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		when(this.chain.filter(any())).thenReturn(chainResult.mono());

		this.csrfFilter.setCsrfTokenRepository(this.repository);
		when(this.repository.loadToken(any()))
			.thenReturn(Mono.just(this.token));
		when(this.repository.generateToken(any()))
			.thenReturn(Mono.just(this.token));
		this.post = from(MockServerHttpRequest.post("/")
			.header(this.token.getHeaderName(), this.token.getToken()));

		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		chainResult.assertWasSubscribed();
	}

	@Test
	// gh-8452
	public void matchesRequireCsrfProtectionWhenNonStandardHTTPMethodIsUsed() {
		HttpMethod customHttpMethod = HttpMethod.resolve("non-standard-http-method");
		MockServerWebExchange nonStandardHttpRequest = from(MockServerHttpRequest.method(customHttpMethod, "/"));

		ServerWebExchangeMatcher serverWebExchangeMatcher = CsrfWebFilter.DEFAULT_CSRF_MATCHER;
		assertThat(serverWebExchangeMatcher.matches(nonStandardHttpRequest).map(MatchResult::isMatch).block()).isTrue();
	}

	@Test
	public void doFilterWhenSkipExchangeInvokedThenSkips() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		when(this.chain.filter(any())).thenReturn(chainResult.mono());

		ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
		this.csrfFilter.setRequireCsrfProtectionMatcher(matcher);

		MockServerWebExchange exchange = from(MockServerHttpRequest.post("/post").build());
		CsrfWebFilter.skipExchange(exchange);
		this.csrfFilter.filter(exchange, this.chain).block();
<commit_msg>Mock request with non-standard HTTP method in test<commit_after>/*
 * Copyright 2002-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.security.web.server.csrf;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import reactor.test.publisher.PublisherProbe;

import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.mock.web.server.MockServerWebExchange.from;
import static org.springframework.web.reactive.function.BodyInserters.fromMultipartData;

/**
 * @author <NAME>
 * @author <NAME>
 * @since 5.0
 */
@RunWith(MockitoJUnitRunner.class)
public class CsrfWebFilterTests {
	@Mock
	private WebFilterChain chain;
	@Mock
	private ServerCsrfTokenRepository repository;

	private CsrfToken token = new DefaultCsrfToken("csrf", "CSRF", "a");

	private CsrfWebFilter csrfFilter = new CsrfWebFilter();

	private MockServerWebExchange get = from(
		MockServerHttpRequest.get("/"));

	private ServerWebExchange post = from(
		MockServerHttpRequest.post("/"));

	@Test
	public void filterWhenGetThenSessionNotCreatedAndChainContinues() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		when(this.chain.filter(this.get)).thenReturn(chainResult.mono());

		Mono<Void> result = this.csrfFilter.filter(this.get, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		Mono<Boolean> isSessionStarted = this.get.getSession()
			.map(WebSession::isStarted);
		StepVerifier.create(isSessionStarted)
			.expectNext(false)
			.verifyComplete();

		chainResult.assertWasSubscribed();
	}

	@Test
	public void filterWhenPostAndNoTokenThenCsrfException() {
		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndRequestMissingTokenThenCsrfException() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		when(this.repository.loadToken(any()))
			.thenReturn(Mono.just(this.token));

		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);


		StepVerifier.create(result)
			.verifyComplete();

		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamInvalidTokenThenCsrfException() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		when(this.repository.loadToken(any()))
			.thenReturn(Mono.just(this.token));
		this.post = from(MockServerHttpRequest.post("/")
			.body(this.token.getParameterName() + "="+this.token.getToken()+"INVALID"));

		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamValidTokenThenContinues() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		when(this.chain.filter(any())).thenReturn(chainResult.mono());

		this.csrfFilter.setCsrfTokenRepository(this.repository);
		when(this.repository.loadToken(any()))
			.thenReturn(Mono.just(this.token));
		when(this.repository.generateToken(any()))
			.thenReturn(Mono.just(this.token));
		this.post = from(MockServerHttpRequest.post("/")
			.contentType(MediaType.APPLICATION_FORM_URLENCODED)
			.body(this.token.getParameterName() + "="+this.token.getToken()));

		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		chainResult.assertWasSubscribed();
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndHeaderInvalidTokenThenCsrfException() {
		this.csrfFilter.setCsrfTokenRepository(this.repository);
		when(this.repository.loadToken(any()))
			.thenReturn(Mono.just(this.token));
		this.post = from(MockServerHttpRequest.post("/")
			.header(this.token.getHeaderName(), this.token.getToken()+"INVALID"));

		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void filterWhenPostAndEstablishedCsrfTokenAndHeaderValidTokenThenContinues() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		when(this.chain.filter(any())).thenReturn(chainResult.mono());

		this.csrfFilter.setCsrfTokenRepository(this.repository);
		when(this.repository.loadToken(any()))
			.thenReturn(Mono.just(this.token));
		when(this.repository.generateToken(any()))
			.thenReturn(Mono.just(this.token));
		this.post = from(MockServerHttpRequest.post("/")
			.header(this.token.getHeaderName(), this.token.getToken()));

		Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);

		StepVerifier.create(result)
			.verifyComplete();

		chainResult.assertWasSubscribed();
	}

	@Test
	// gh-8452
	public void matchesRequireCsrfProtectionWhenNonStandardHTTPMethodIsUsed() {
		ServerHttpRequest nonStandardHttpRequest = mock(ServerHttpRequest.class);
		ServerWebExchange nonStandardHttpExchange = mock(ServerWebExchange.class);
		when(nonStandardHttpExchange.getRequest()).thenReturn(nonStandardHttpRequest);

		ServerWebExchangeMatcher serverWebExchangeMatcher = CsrfWebFilter.DEFAULT_CSRF_MATCHER;
		assertThat(serverWebExchangeMatcher.matches(nonStandardHttpExchange).map(MatchResult::isMatch).block()).isTrue();
	}

	@Test
	public void doFilterWhenSkipExchangeInvokedThenSkips() {
		PublisherProbe<Void> chainResult = PublisherProbe.empty();
		when(this.chain.filter(any())).thenReturn(chainResult.mono());

		ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
		this.csrfFilter.setRequireCsrfProtectionMatcher(matcher);

		MockServerWebExchange exchange = from(MockServerHttpRequest.post("/post").build());
		CsrfWebFilter.skipExchange(exchange);
		this.csrfFilter.filter(exchange, this.chain).block();

{'fraction_non_alphanumeric': 0.12073099604691855, 'fraction_numerical': 0.0023329661071868316, 'mean_word_length': 6.345073774393146, 'pattern_counts': {'":': 0, '<': 31, '<?xml version=': 0, '>': 31, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6651808', 'n_tokens_mistral': 5022, 'n_tokens_neox': 4635, 'n_words': 716}