Add CsrfTokenRepository (#3805)

* Create LazyCsrfTokenRepository

Fixes gh-3790

* Add CookieCsrfTokenRepository

Fixes gh-3009
This commit is contained in:
Rob Winch
2016-04-12 16:26:53 -05:00
committed by Joe Grandja
parent e9cb92bb74
commit d3a9cc6eae
14 changed files with 1461 additions and 857 deletions

View File

@@ -0,0 +1,189 @@
/*
* Copyright 2012-2016 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
*
* http://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.csrf;
import javax.servlet.http.Cookie;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
* @since 4.1
*/
public class CookieCsrfTokenRepositoryTests {
CookieCsrfTokenRepository repository;
MockHttpServletResponse response;
MockHttpServletRequest request;
@Before
public void setup() {
this.repository = new CookieCsrfTokenRepository();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.request.setContextPath("/context");
}
@Test
public void generateToken() {
CsrfToken generateToken = this.repository.generateToken(this.request);
assertThat(generateToken).isNotNull();
assertThat(generateToken.getHeaderName())
.isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_HEADER_NAME);
assertThat(generateToken.getParameterName())
.isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_PARAMETER_NAME);
assertThat(generateToken.getToken()).isNotEmpty();
}
@Test
public void generateTokenCustom() {
String headerName = "headerName";
String parameterName = "paramName";
this.repository.setHeaderName(headerName);
this.repository.setParameterName(parameterName);
CsrfToken generateToken = this.repository.generateToken(this.request);
assertThat(generateToken).isNotNull();
assertThat(generateToken.getHeaderName()).isEqualTo(headerName);
assertThat(generateToken.getParameterName()).isEqualTo(parameterName);
assertThat(generateToken.getToken()).isNotEmpty();
}
@Test
public void saveToken() {
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response
.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getMaxAge()).isEqualTo(-1);
assertThat(tokenCookie.getName())
.isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
assertThat(tokenCookie.getSecure()).isEqualTo(this.request.isSecure());
assertThat(tokenCookie.getValue()).isEqualTo(token.getToken());
}
@Test
public void saveTokenSecure() {
this.request.setSecure(true);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response
.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getSecure()).isTrue();
}
@Test
public void saveTokenNull() {
this.request.setSecure(true);
this.repository.saveToken(null, this.request, this.response);
Cookie tokenCookie = this.response
.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getMaxAge()).isEqualTo(0);
assertThat(tokenCookie.getName())
.isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
assertThat(tokenCookie.getSecure()).isEqualTo(this.request.isSecure());
assertThat(tokenCookie.getValue()).isEmpty();
}
@Test
public void loadTokenNoCookiesNull() {
assertThat(this.repository.loadToken(this.request)).isNull();
}
@Test
public void loadTokenCookieIncorrectNameNull() {
this.request.setCookies(new Cookie("other", "name"));
assertThat(this.repository.loadToken(this.request)).isNull();
}
@Test
public void loadTokenCookieValueEmptyString() {
this.request.setCookies(
new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, ""));
assertThat(this.repository.loadToken(this.request)).isNull();
}
@Test
public void loadToken() {
CsrfToken generateToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME,
generateToken.getToken()));
CsrfToken loadToken = this.repository.loadToken(this.request);
assertThat(loadToken).isNotNull();
assertThat(loadToken.getHeaderName()).isEqualTo(generateToken.getHeaderName());
assertThat(loadToken.getParameterName())
.isEqualTo(generateToken.getParameterName());
assertThat(loadToken.getToken()).isNotEmpty();
}
@Test
public void loadTokenCustom() {
String cookieName = "cookieName";
String value = "value";
String headerName = "headerName";
String parameterName = "paramName";
this.repository.setHeaderName(headerName);
this.repository.setParameterName(parameterName);
this.repository.setCookieName(cookieName);
this.request.setCookies(new Cookie(cookieName, value));
CsrfToken loadToken = this.repository.loadToken(this.request);
assertThat(loadToken).isNotNull();
assertThat(loadToken.getHeaderName()).isEqualTo(headerName);
assertThat(loadToken.getParameterName()).isEqualTo(parameterName);
assertThat(loadToken.getToken()).isEqualTo(value);
}
@Test(expected = IllegalArgumentException.class)
public void setCookieNameNullIllegalArgumentException() {
this.repository.setCookieName(null);
}
@Test(expected = IllegalArgumentException.class)
public void setParameterNameNullIllegalArgumentException() {
this.repository.setParameterName(null);
}
@Test(expected = IllegalArgumentException.class)
public void setHeaderNameNullIllegalArgumentException() {
this.repository.setHeaderName(null);
}
}

View File

@@ -15,13 +15,6 @@
*/
package org.springframework.security.web.csrf;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -30,10 +23,18 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.TestingAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
*
@@ -55,11 +56,12 @@ public class CsrfAuthenticationStrategyTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
strategy = new CsrfAuthenticationStrategy(csrfTokenRepository);
existingToken = new DefaultCsrfToken("_csrf", "_csrf", "1");
generatedToken = new DefaultCsrfToken("_csrf", "_csrf", "2");
this.response = new MockHttpServletResponse();
this.request = new MockHttpServletRequest();
this.request.setAttribute(HttpServletResponse.class.getName(), this.response);
this.strategy = new CsrfAuthenticationStrategy(this.csrfTokenRepository);
this.existingToken = new DefaultCsrfToken("_csrf", "_csrf", "1");
this.generatedToken = new DefaultCsrfToken("_csrf", "_csrf", "2");
}
@Test(expected = IllegalArgumentException.class)
@@ -69,51 +71,61 @@ public class CsrfAuthenticationStrategyTests {
@Test
public void logoutRemovesCsrfTokenAndSavesNew() {
when(csrfTokenRepository.loadToken(request)).thenReturn(existingToken);
when(csrfTokenRepository.generateToken(request)).thenReturn(generatedToken);
strategy.onAuthentication(new TestingAuthenticationToken("user", "password",
"ROLE_USER"), request, response);
when(this.csrfTokenRepository.loadToken(this.request))
.thenReturn(this.existingToken);
when(this.csrfTokenRepository.generateToken(this.request))
.thenReturn(this.generatedToken);
this.strategy.onAuthentication(
new TestingAuthenticationToken("user", "password", "ROLE_USER"),
this.request, this.response);
verify(csrfTokenRepository).saveToken(null, request, response);
verify(csrfTokenRepository, never()).saveToken(eq(generatedToken),
verify(this.csrfTokenRepository).saveToken(null, this.request, this.response);
verify(this.csrfTokenRepository).saveToken(eq(this.generatedToken),
any(HttpServletRequest.class), any(HttpServletResponse.class));
// SEC-2404, SEC-2832
CsrfToken tokenInRequest = (CsrfToken) request.getAttribute(CsrfToken.class
.getName());
assertThat(tokenInRequest.getToken()).isSameAs(generatedToken.getToken());
assertThat(tokenInRequest.getHeaderName()).isSameAs(
generatedToken.getHeaderName());
assertThat(tokenInRequest.getParameterName()).isSameAs(
generatedToken.getParameterName());
assertThat(request.getAttribute(generatedToken.getParameterName())).isSameAs(
tokenInRequest);
CsrfToken tokenInRequest = (CsrfToken) this.request
.getAttribute(CsrfToken.class.getName());
assertThat(tokenInRequest.getToken()).isSameAs(this.generatedToken.getToken());
assertThat(tokenInRequest.getHeaderName())
.isSameAs(this.generatedToken.getHeaderName());
assertThat(tokenInRequest.getParameterName())
.isSameAs(this.generatedToken.getParameterName());
assertThat(this.request.getAttribute(this.generatedToken.getParameterName()))
.isSameAs(tokenInRequest);
}
// SEC-2872
@Test
public void delaySavingCsrf() {
when(csrfTokenRepository.loadToken(request)).thenReturn(existingToken);
when(csrfTokenRepository.generateToken(request)).thenReturn(generatedToken);
strategy.onAuthentication(new TestingAuthenticationToken("user", "password",
"ROLE_USER"), request, response);
this.strategy = new CsrfAuthenticationStrategy(
new LazyCsrfTokenRepository(this.csrfTokenRepository));
verify(csrfTokenRepository).saveToken(null, request, response);
verify(csrfTokenRepository, never()).saveToken(eq(generatedToken),
when(this.csrfTokenRepository.loadToken(this.request))
.thenReturn(this.existingToken);
when(this.csrfTokenRepository.generateToken(this.request))
.thenReturn(this.generatedToken);
this.strategy.onAuthentication(
new TestingAuthenticationToken("user", "password", "ROLE_USER"),
this.request, this.response);
verify(this.csrfTokenRepository).saveToken(null, this.request, this.response);
verify(this.csrfTokenRepository, never()).saveToken(eq(this.generatedToken),
any(HttpServletRequest.class), any(HttpServletResponse.class));
CsrfToken tokenInRequest = (CsrfToken) request.getAttribute(CsrfToken.class
.getName());
CsrfToken tokenInRequest = (CsrfToken) this.request
.getAttribute(CsrfToken.class.getName());
tokenInRequest.getToken();
verify(csrfTokenRepository).saveToken(eq(generatedToken),
verify(this.csrfTokenRepository).saveToken(eq(this.generatedToken),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void logoutRemovesNoActionIfNullToken() {
strategy.onAuthentication(new TestingAuthenticationToken("user", "password",
"ROLE_USER"), request, response);
this.strategy.onAuthentication(
new TestingAuthenticationToken("user", "password", "ROLE_USER"),
this.request, this.response);
verify(csrfTokenRepository, never()).saveToken(any(CsrfToken.class),
verify(this.csrfTokenRepository, never()).saveToken(any(CsrfToken.class),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
}

View File

@@ -15,14 +15,6 @@
*/
package org.springframework.security.web.csrf;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Arrays;
@@ -38,11 +30,21 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
*
@@ -67,16 +69,21 @@ public class CsrfFilterTests {
@Before
public void setup() {
token = new DefaultCsrfToken("headerName", "paramName", "csrfTokenValue");
this.token = new DefaultCsrfToken("headerName", "paramName", "csrfTokenValue");
resetRequestResponse();
filter = new CsrfFilter(tokenRepository);
filter.setRequireCsrfProtectionMatcher(requestMatcher);
filter.setAccessDeniedHandler(deniedHandler);
this.filter = createCsrfFilter(this.tokenRepository);
}
private CsrfFilter createCsrfFilter(CsrfTokenRepository repository) {
CsrfFilter filter = new CsrfFilter(repository);
filter.setRequireCsrfProtectionMatcher(this.requestMatcher);
filter.setAccessDeniedHandler(this.deniedHandler);
return filter;
}
private void resetRequestResponse() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}
@Test(expected = IllegalArgumentException.class)
@@ -86,282 +93,319 @@ public class CsrfFilterTests {
// SEC-2276
@Test
public void doFilterDoesNotSaveCsrfTokenUntilAccessed() throws ServletException,
IOException {
when(requestMatcher.matches(request)).thenReturn(false);
when(tokenRepository.generateToken(request)).thenReturn(token);
public void doFilterDoesNotSaveCsrfTokenUntilAccessed()
throws ServletException, IOException {
this.filter = createCsrfFilter(new LazyCsrfTokenRepository(this.tokenRepository));
when(this.requestMatcher.matches(this.request)).thenReturn(false);
when(this.tokenRepository.generateToken(this.request)).thenReturn(this.token);
filter.doFilter(request, response, filterChain);
CsrfToken attrToken = (CsrfToken) request.getAttribute(token.getParameterName());
this.filter.doFilter(this.request, this.response, this.filterChain);
CsrfToken attrToken = (CsrfToken) this.request
.getAttribute(this.token.getParameterName());
// no CsrfToken should have been saved yet
verify(tokenRepository, times(0)).saveToken(any(CsrfToken.class),
verify(this.tokenRepository, times(0)).saveToken(any(CsrfToken.class),
any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(filterChain).doFilter(request, response);
verify(this.filterChain).doFilter(this.request, this.response);
// access the token
attrToken.getToken();
// now the CsrfToken should have been saved
verify(tokenRepository).saveToken(eq(token), any(HttpServletRequest.class),
any(HttpServletResponse.class));
verify(this.tokenRepository).saveToken(eq(this.token),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterAccessDeniedNoTokenPresent() throws ServletException, IOException {
when(requestMatcher.matches(request)).thenReturn(true);
when(tokenRepository.loadToken(request)).thenReturn(token);
public void doFilterAccessDeniedNoTokenPresent()
throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertThat(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
verify(deniedHandler).handle(eq(request), eq(response),
verify(this.deniedHandler).handle(eq(this.request), eq(this.response),
any(InvalidCsrfTokenException.class));
verifyZeroInteractions(filterChain);
verifyZeroInteractions(this.filterChain);
}
@Test
public void doFilterAccessDeniedIncorrectTokenPresent() throws ServletException,
IOException {
when(requestMatcher.matches(request)).thenReturn(true);
when(tokenRepository.loadToken(request)).thenReturn(token);
request.setParameter(token.getParameterName(), token.getToken() + " INVALID");
public void doFilterAccessDeniedIncorrectTokenPresent()
throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.setParameter(this.token.getParameterName(),
this.token.getToken() + " INVALID");
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertThat(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
verify(deniedHandler).handle(eq(request), eq(response),
verify(this.deniedHandler).handle(eq(this.request), eq(this.response),
any(InvalidCsrfTokenException.class));
verifyZeroInteractions(filterChain);
verifyZeroInteractions(this.filterChain);
}
@Test
public void doFilterAccessDeniedIncorrectTokenPresentHeader()
throws ServletException, IOException {
when(requestMatcher.matches(request)).thenReturn(true);
when(tokenRepository.loadToken(request)).thenReturn(token);
request.addHeader(token.getHeaderName(), token.getToken() + " INVALID");
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.addHeader(this.token.getHeaderName(),
this.token.getToken() + " INVALID");
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertThat(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
verify(deniedHandler).handle(eq(request), eq(response),
verify(this.deniedHandler).handle(eq(this.request), eq(this.response),
any(InvalidCsrfTokenException.class));
verifyZeroInteractions(filterChain);
verifyZeroInteractions(this.filterChain);
}
@Test
public void doFilterAccessDeniedIncorrectTokenPresentHeaderPreferredOverParameter()
throws ServletException, IOException {
when(requestMatcher.matches(request)).thenReturn(true);
when(tokenRepository.loadToken(request)).thenReturn(token);
request.setParameter(token.getParameterName(), token.getToken());
request.addHeader(token.getHeaderName(), token.getToken() + " INVALID");
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken());
this.request.addHeader(this.token.getHeaderName(),
this.token.getToken() + " INVALID");
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertThat(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
verify(deniedHandler).handle(eq(request), eq(response),
verify(this.deniedHandler).handle(eq(this.request), eq(this.response),
any(InvalidCsrfTokenException.class));
verifyZeroInteractions(filterChain);
verifyZeroInteractions(this.filterChain);
}
@Test
public void doFilterNotCsrfRequestExistingToken() throws ServletException,
IOException {
when(requestMatcher.matches(request)).thenReturn(false);
when(tokenRepository.loadToken(request)).thenReturn(token);
public void doFilterNotCsrfRequestExistingToken()
throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(false);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertThat(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
verify(filterChain).doFilter(request, response);
verifyZeroInteractions(deniedHandler);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
@Test
public void doFilterNotCsrfRequestGenerateToken() throws ServletException,
IOException {
when(requestMatcher.matches(request)).thenReturn(false);
when(tokenRepository.generateToken(request)).thenReturn(token);
public void doFilterNotCsrfRequestGenerateToken()
throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(false);
when(this.tokenRepository.generateToken(this.request)).thenReturn(this.token);
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertToken(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertToken(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertToken(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertToken(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
verify(filterChain).doFilter(request, response);
verifyZeroInteractions(deniedHandler);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
@Test
public void doFilterIsCsrfRequestExistingTokenHeader() throws ServletException,
IOException {
when(requestMatcher.matches(request)).thenReturn(true);
when(tokenRepository.loadToken(request)).thenReturn(token);
request.addHeader(token.getHeaderName(), token.getToken());
public void doFilterIsCsrfRequestExistingTokenHeader()
throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.addHeader(this.token.getHeaderName(), this.token.getToken());
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertThat(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
verify(filterChain).doFilter(request, response);
verifyZeroInteractions(deniedHandler);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
@Test
public void doFilterIsCsrfRequestExistingTokenHeaderPreferredOverInvalidParam()
throws ServletException, IOException {
when(requestMatcher.matches(request)).thenReturn(true);
when(tokenRepository.loadToken(request)).thenReturn(token);
request.setParameter(token.getParameterName(), token.getToken() + " INVALID");
request.addHeader(token.getHeaderName(), token.getToken());
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.setParameter(this.token.getParameterName(),
this.token.getToken() + " INVALID");
this.request.addHeader(this.token.getHeaderName(), this.token.getToken());
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertThat(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
verify(filterChain).doFilter(request, response);
verifyZeroInteractions(deniedHandler);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
@Test
public void doFilterIsCsrfRequestExistingToken() throws ServletException, IOException {
when(requestMatcher.matches(request)).thenReturn(true);
when(tokenRepository.loadToken(request)).thenReturn(token);
request.setParameter(token.getParameterName(), token.getToken());
public void doFilterIsCsrfRequestExistingToken()
throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken());
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertThat(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
verify(filterChain).doFilter(request, response);
verifyZeroInteractions(deniedHandler);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
verify(this.tokenRepository, never()).saveToken(any(CsrfToken.class),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterIsCsrfRequestGenerateToken() throws ServletException, IOException {
when(requestMatcher.matches(request)).thenReturn(true);
when(tokenRepository.generateToken(request)).thenReturn(token);
request.setParameter(token.getParameterName(), token.getToken());
public void doFilterIsCsrfRequestGenerateToken()
throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.generateToken(this.request)).thenReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken());
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertToken(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertToken(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertToken(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertToken(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
verify(filterChain).doFilter(request, response);
verifyZeroInteractions(deniedHandler);
// LazyCsrfTokenRepository requires the response as an attribute
assertThat(this.request.getAttribute(HttpServletResponse.class.getName()))
.isEqualTo(this.response);
verify(this.filterChain).doFilter(this.request, this.response);
verify(this.tokenRepository).saveToken(this.token, this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
@Test
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethods()
throws ServletException, IOException {
filter = new CsrfFilter(tokenRepository);
filter.setAccessDeniedHandler(deniedHandler);
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setAccessDeniedHandler(this.deniedHandler);
for (String method : Arrays.asList("GET", "TRACE", "OPTIONS", "HEAD")) {
resetRequestResponse();
when(tokenRepository.loadToken(request)).thenReturn(token);
request.setMethod(method);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.setMethod(method);
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(filterChain).doFilter(request, response);
verifyZeroInteractions(deniedHandler);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
}
/**
* SEC-2292 Should not allow other cases through since spec states HTTP method is case
* sensitive http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1
* @throws Exception if an error occurs
*
* @throws ServletException
* @throws IOException
*/
@Test
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethodsCaseSensitive()
throws ServletException, IOException {
filter = new CsrfFilter(tokenRepository);
filter.setAccessDeniedHandler(deniedHandler);
throws Exception {
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setAccessDeniedHandler(this.deniedHandler);
for (String method : Arrays.asList("get", "TrAcE", "oPTIOnS", "hEaD")) {
resetRequestResponse();
when(tokenRepository.loadToken(request)).thenReturn(token);
request.setMethod(method);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.setMethod(method);
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(deniedHandler).handle(eq(request), eq(response),
verify(this.deniedHandler).handle(eq(this.request), eq(this.response),
any(InvalidCsrfTokenException.class));
verifyZeroInteractions(filterChain);
verifyZeroInteractions(this.filterChain);
}
}
@Test
public void doFilterDefaultRequireCsrfProtectionMatcherDeniedMethods()
throws ServletException, IOException {
filter = new CsrfFilter(tokenRepository);
filter.setAccessDeniedHandler(deniedHandler);
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setAccessDeniedHandler(this.deniedHandler);
for (String method : Arrays.asList("POST", "PUT", "PATCH", "DELETE", "INVALID")) {
resetRequestResponse();
when(tokenRepository.loadToken(request)).thenReturn(token);
request.setMethod(method);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.setMethod(method);
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(deniedHandler).handle(eq(request), eq(response),
verify(this.deniedHandler).handle(eq(this.request), eq(this.response),
any(InvalidCsrfTokenException.class));
verifyZeroInteractions(filterChain);
verifyZeroInteractions(this.filterChain);
}
}
@Test
public void doFilterDefaultAccessDenied() throws ServletException, IOException {
filter = new CsrfFilter(tokenRepository);
filter.setRequireCsrfProtectionMatcher(requestMatcher);
when(requestMatcher.matches(request)).thenReturn(true);
when(tokenRepository.loadToken(request)).thenReturn(token);
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setRequireCsrfProtectionMatcher(this.requestMatcher);
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
assertThat(this.request.getAttribute(this.token.getParameterName()))
.isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName()))
.isEqualTo(this.token);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
verifyZeroInteractions(filterChain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
verifyZeroInteractions(this.filterChain);
}
@Test(expected = IllegalArgumentException.class)
public void setRequireCsrfProtectionMatcherNull() {
filter.setRequireCsrfProtectionMatcher(null);
this.filter.setRequireCsrfProtectionMatcher(null);
}
@Test(expected = IllegalArgumentException.class)
public void setAccessDeniedHandlerNull() {
filter.setAccessDeniedHandler(null);
this.filter.setAccessDeniedHandler(null);
}
private static final CsrfTokenAssert assertToken(Object token) {
return new CsrfTokenAssert((CsrfToken) token);
}
private static class CsrfTokenAssert extends
AbstractObjectAssert<CsrfTokenAssert, CsrfToken> {
private static class CsrfTokenAssert
extends AbstractObjectAssert<CsrfTokenAssert, CsrfToken> {
/**
* Creates a new </code>{@link ObjectAssert}</code>.
@@ -369,13 +413,14 @@ public class CsrfFilterTests {
* @param actual the target to verify.
*/
protected CsrfTokenAssert(CsrfToken actual) {
super(actual,CsrfTokenAssert.class);
super(actual, CsrfTokenAssert.class);
}
public CsrfTokenAssert isEqualTo(CsrfToken expected) {
assertThat(actual.getHeaderName()).isEqualTo(expected.getHeaderName());
assertThat(actual.getParameterName()).isEqualTo(expected.getParameterName());
assertThat(actual.getToken()).isEqualTo(expected.getToken());
assertThat(this.actual.getHeaderName()).isEqualTo(expected.getHeaderName());
assertThat(this.actual.getParameterName())
.isEqualTo(expected.getParameterName());
assertThat(this.actual.getToken()).isEqualTo(expected.getToken());
return this;
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright 2012-2016 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
*
* http://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.csrf;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
*/
@RunWith(MockitoJUnitRunner.class)
public class LazyCsrfTokenRepositoryTests {
@Mock
CsrfTokenRepository delegate;
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@InjectMocks
LazyCsrfTokenRepository repository;
DefaultCsrfToken token;
@Before
public void setup() {
this.token = new DefaultCsrfToken("header", "param", "token");
when(this.delegate.generateToken(this.request)).thenReturn(this.token);
when(this.request.getAttribute(HttpServletResponse.class.getName()))
.thenReturn(this.response);
}
@Test(expected = IllegalArgumentException.class)
public void constructNullDelegateThrowsIllegalArgumentException() {
new LazyCsrfTokenRepository(null);
}
@Test(expected = IllegalArgumentException.class)
public void generateTokenNullResponseAttribute() {
this.repository.generateToken(mock(HttpServletRequest.class));
}
@Test
public void generateTokenGetTokenSavesToken() {
CsrfToken newToken = this.repository.generateToken(this.request);
newToken.getToken();
verify(this.delegate).saveToken(this.token, this.request, this.response);
}
@Test
public void saveNonNullDoesNothing() {
this.repository.saveToken(this.token, this.request, this.response);
verifyZeroInteractions(this.delegate);
}
@Test
public void saveNullDelegates() {
this.repository.saveToken(null, this.request, this.response);
verify(this.delegate).saveToken(null, this.request, this.response);
}
@Test
public void loadTokenDelegates() {
when(this.delegate.loadToken(this.request)).thenReturn(this.token);
CsrfToken loadToken = this.repository.loadToken(this.request);
assertThat(loadToken).isSameAs(this.token);
verify(this.delegate).loadToken(this.request);
}
}