repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/util/matcher/NegatedServerWebExchangeMatcherTests.java
/* * Copyright 2002-2018 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.util.matcher; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; /** * @author Tao Qian * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class NegatedServerWebExchangeMatcherTests { @Mock ServerWebExchange exchange; @Mock ServerWebExchangeMatcher matcher1; NegatedServerWebExchangeMatcher matcher; @BeforeEach public void setUp() { this.matcher = new NegatedServerWebExchangeMatcher(this.matcher1); } @Test public void matchesWhenFalseThenTrue() { given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); assertThat(matches.isMatch()).isTrue(); assertThat(matches.getVariables()).isEmpty(); verify(this.matcher1).matches(this.exchange); } @Test public void matchesWhenTrueThenFalse() { given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); assertThat(matches.isMatch()).isFalse(); assertThat(matches.getVariables()).isEmpty(); verify(this.matcher1).matches(this.exchange); } }
2,241
31.028571
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/util/matcher/IpAddressServerWebExchangeMatcherTests.java
/* * Copyright 2002-2021 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.util.matcher; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link IpAddressServerWebExchangeMatcher} * * @author Guirong Hu */ @ExtendWith(MockitoExtension.class) public class IpAddressServerWebExchangeMatcherTests { @Test public void matchesWhenIpv6RangeAndIpv6AddressThenTrue() throws UnknownHostException { ServerWebExchange ipv6Exchange = exchange("fe80::21f:5bff:fe33:bd68"); ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("fe80::21f:5bff:fe33:bd68") .matches(ipv6Exchange).block(); assertThat(matches.isMatch()).isTrue(); } @Test public void matchesWhenIpv6RangeAndIpv4AddressThenFalse() throws UnknownHostException { ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("fe80::21f:5bff:fe33:bd68") .matches(ipv4Exchange).block(); assertThat(matches.isMatch()).isFalse(); } @Test public void matchesWhenIpv4RangeAndIpv4AddressThenTrue() throws UnknownHostException { ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("192.168.1.104") .matches(ipv4Exchange).block(); assertThat(matches.isMatch()).isTrue(); } @Test public void matchesWhenIpv4SubnetAndIpv4AddressThenTrue() throws UnknownHostException { ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("192.168.1.0/24"); assertThat(matcher.matches(ipv4Exchange).block().isMatch()).isTrue(); } @Test public void matchesWhenIpv4SubnetAndIpv4AddressThenFalse() throws UnknownHostException { ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("192.168.1.128/25"); assertThat(matcher.matches(ipv4Exchange).block().isMatch()).isFalse(); } @Test public void matchesWhenIpv6SubnetAndIpv6AddressThenTrue() throws UnknownHostException { ServerWebExchange ipv6Exchange = exchange("2001:DB8:0:FFFF:FFFF:FFFF:FFFF:FFFF"); IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("2001:DB8::/48"); assertThat(matcher.matches(ipv6Exchange).block().isMatch()).isTrue(); } @Test public void matchesWhenIpv6SubnetAndIpv6AddressThenFalse() throws UnknownHostException { ServerWebExchange ipv6Exchange = exchange("2001:DB8:1:0:0:0:0:0"); IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("2001:DB8::/48"); assertThat(matcher.matches(ipv6Exchange).block().isMatch()).isFalse(); } @Test public void matchesWhenZeroMaskAndAnythingThenTrue() throws UnknownHostException { IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("0.0.0.0/0"); assertThat(matcher.matches(exchange("123.4.5.6")).block().isMatch()).isTrue(); assertThat(matcher.matches(exchange("192.168.0.159")).block().isMatch()).isTrue(); matcher = new IpAddressServerWebExchangeMatcher("192.168.0.159/0"); assertThat(matcher.matches(exchange("123.4.5.6")).block().isMatch()).isTrue(); assertThat(matcher.matches(exchange("192.168.0.159")).block().isMatch()).isTrue(); } @Test public void matchesWhenIpv4UnresolvedThenTrue() throws UnknownHostException { ServerWebExchange ipv4Exchange = exchange("192.168.1.104", true); ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("192.168.1.104") .matches(ipv4Exchange).block(); assertThat(matches.isMatch()).isTrue(); } @Test public void matchesWhenIpv6UnresolvedThenTrue() throws UnknownHostException { ServerWebExchange ipv6Exchange = exchange("fe80::21f:5bff:fe33:bd68", true); ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("fe80::21f:5bff:fe33:bd68") .matches(ipv6Exchange).block(); assertThat(matches.isMatch()).isTrue(); } @Test public void constructorWhenIpv4AddressMaskTooLongThenIllegalArgumentException() { String ipv4AddressWithTooLongMask = "192.168.1.104/33"; assertThatIllegalArgumentException() .isThrownBy(() -> new IpAddressServerWebExchangeMatcher(ipv4AddressWithTooLongMask)) .withMessage(String.format("IP address %s is too short for bitmask of length %d", "192.168.1.104", 33)); } @Test public void constructorWhenIpv6AddressMaskTooLongThenIllegalArgumentException() { String ipv6AddressWithTooLongMask = "fe80::21f:5bff:fe33:bd68/129"; assertThatIllegalArgumentException() .isThrownBy(() -> new IpAddressServerWebExchangeMatcher(ipv6AddressWithTooLongMask)) .withMessage(String.format("IP address %s is too short for bitmask of length %d", "fe80::21f:5bff:fe33:bd68", 129)); } private static ServerWebExchange exchange(String ipAddress) throws UnknownHostException { return exchange(ipAddress, false); } private static ServerWebExchange exchange(String ipAddress, boolean unresolved) throws UnknownHostException { return MockServerWebExchange.builder(MockServerHttpRequest.get("/") .remoteAddress(unresolved ? InetSocketAddress.createUnresolved(ipAddress, 8080) : new InetSocketAddress(InetAddress.getByName(ipAddress), 8080))) .build(); } }
6,486
42.536913
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatchersTests.java
/* * Copyright 2002-2017 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.util.matcher; import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @since 5.0 */ public class ServerWebExchangeMatchersTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); @Test public void pathMatchersWhenSingleAndSamePatternThenMatches() { assertThat(ServerWebExchangeMatchers.pathMatchers("/").matches(this.exchange).block().isMatch()).isTrue(); } @Test public void pathMatchersWhenSingleAndSamePatternAndMethodThenMatches() { assertThat(ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/").matches(this.exchange).block().isMatch()) .isTrue(); } @Test public void pathMatchersWhenSingleAndSamePatternAndDiffMethodThenDoesNotMatch() { assertThat( ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/").matches(this.exchange).block().isMatch()) .isFalse(); } @Test public void pathMatchersWhenSingleAndDifferentPatternThenDoesNotMatch() { assertThat(ServerWebExchangeMatchers.pathMatchers("/foobar").matches(this.exchange).block().isMatch()) .isFalse(); } @Test public void pathMatchersWhenMultiThenMatches() { assertThat(ServerWebExchangeMatchers.pathMatchers("/foobar", "/").matches(this.exchange).block().isMatch()) .isTrue(); } @Test public void anyExchangeWhenMockThenMatches() { ServerWebExchange mockExchange = mock(ServerWebExchange.class); assertThat(ServerWebExchangeMatchers.anyExchange().matches(mockExchange).block().isMatch()).isTrue(); verifyNoMoreInteractions(mockExchange); } /** * If a LinkedMap is used and anyRequest equals anyRequest then the following is * added: anyRequest() -> authenticated() pathMatchers("/admin/**") -> * hasRole("ADMIN") anyRequest() -> permitAll * * will result in the first entry being overridden */ @Test public void anyExchangeWhenTwoCreatedThenDifferentToPreventIssuesInMap() { assertThat(ServerWebExchangeMatchers.anyExchange()).isNotEqualTo(ServerWebExchangeMatchers.anyExchange()); } }
3,076
33.965909
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/util/matcher/PathPatternParserServerWebExchangeMatcherTests.java
/* * Copyright 2002-2023 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.util.matcher; import org.junit.jupiter.api.Test; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PathPatternParserServerWebExchangeMatcher} * * @author Marcus da Coregio */ class PathPatternParserServerWebExchangeMatcherTests { @Test void matchesWhenConfiguredWithNoTrailingSlashAndPathContainsSlashThenMatches() { PathPatternParserServerWebExchangeMatcher matcher = new PathPatternParserServerWebExchangeMatcher("user/**"); MockServerHttpRequest request = MockServerHttpRequest.get("/user/test").build(); assertThat(matcher.matches(MockServerWebExchange.from(request)).block().isMatch()).isTrue(); } }
1,468
34.829268
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/util/matcher/AndServerWebExchangeMatcherTests.java
/* * Copyright 2002-2017 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.util.matcher; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class AndServerWebExchangeMatcherTests { @Mock ServerWebExchange exchange; @Mock ServerWebExchangeMatcher matcher1; @Mock ServerWebExchangeMatcher matcher2; AndServerWebExchangeMatcher matcher; @BeforeEach public void setUp() { this.matcher = new AndServerWebExchangeMatcher(this.matcher1, this.matcher2); } @Test public void matchesWhenTrueTrueThenTrue() { Map<String, Object> params1 = Collections.singletonMap("foo", "bar"); Map<String, Object> params2 = Collections.singletonMap("x", "y"); given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params1)); given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params2)); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); assertThat(matches.isMatch()).isTrue(); assertThat(matches.getVariables()).hasSize(2); assertThat(matches.getVariables()).containsAllEntriesOf(params1); assertThat(matches.getVariables()).containsAllEntriesOf(params2); verify(this.matcher1).matches(this.exchange); verify(this.matcher2).matches(this.exchange); } @Test public void matchesWhenFalseFalseThenFalseAndMatcher2NotInvoked() { given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); assertThat(matches.isMatch()).isFalse(); assertThat(matches.getVariables()).isEmpty(); verify(this.matcher1).matches(this.exchange); verify(this.matcher2, never()).matches(this.exchange); } @Test public void matchesWhenTrueFalseThenFalse() { Map<String, Object> params = Collections.singletonMap("foo", "bar"); given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params)); given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); assertThat(matches.isMatch()).isFalse(); assertThat(matches.getVariables()).isEmpty(); verify(this.matcher1).matches(this.exchange); verify(this.matcher2).matches(this.exchange); } @Test public void matchesWhenFalseTrueThenFalse() { given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); assertThat(matches.isMatch()).isFalse(); assertThat(matches.getVariables()).isEmpty(); verify(this.matcher1).matches(this.exchange); verify(this.matcher2, never()).matches(this.exchange); } }
3,995
36.698113
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilterTests.java
/* * Copyright 2002-2022 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.ui; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; public class LogoutPageGeneratingWebFilterTests { @Test public void filterWhenLogoutWithContextPathThenActionContainsContextPath() throws Exception { LogoutPageGeneratingWebFilter filter = new LogoutPageGeneratingWebFilter(); MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/test/logout").contextPath("/test")); filter.filter(exchange, (e) -> Mono.empty()).block(); assertThat(exchange.getResponse().getBodyAsString().block()).contains("action=\"/test/logout\""); } @Test public void filterWhenLogoutWithNoContextPathThenActionDoesNotContainsContextPath() throws Exception { LogoutPageGeneratingWebFilter filter = new LogoutPageGeneratingWebFilter(); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/logout")); filter.filter(exchange, (e) -> Mono.empty()).block(); assertThat(exchange.getResponse().getBodyAsString().block()).contains("action=\"/logout\""); } }
1,920
39.87234
103
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/ui/LoginPageGeneratingWebFilterTests.java
/* * 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.ui; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; public class LoginPageGeneratingWebFilterTests { @Test public void filterWhenLoginWithContextPathThenActionContainsContextPath() throws Exception { LoginPageGeneratingWebFilter filter = new LoginPageGeneratingWebFilter(); filter.setFormLoginEnabled(true); MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/test/login").contextPath("/test")); filter.filter(exchange, (e) -> Mono.empty()).block(); assertThat(exchange.getResponse().getBodyAsString().block()).contains("action=\"/test/login\""); } @Test public void filterWhenLoginWithNoContextPathThenActionDoesNotContainsContextPath() throws Exception { LoginPageGeneratingWebFilter filter = new LoginPageGeneratingWebFilter(); filter.setFormLoginEnabled(true); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/login")); filter.filter(exchange, (e) -> Mono.empty()).block(); assertThat(exchange.getResponse().getBodyAsString().block()).contains("action=\"/login\""); } }
1,981
39.44898
102
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/csrf/CookieServerCsrfTokenRepositoryTests.java
/* * Copyright 2002-2022 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 java.security.cert.X509Certificate; import java.time.Duration; import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpCookie; import org.springframework.http.ResponseCookie; import org.springframework.http.server.reactive.SslInfo; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Eric Deandrea * @author Thomas Vitale * @author Alonso Araya * @author Alex Montoya * @since 5.1 */ class CookieServerCsrfTokenRepositoryTests { private CookieServerCsrfTokenRepository csrfTokenRepository; private MockServerHttpRequest.BaseBuilder<?> request; private String expectedHeaderName = CookieServerCsrfTokenRepository.DEFAULT_CSRF_HEADER_NAME; private String expectedParameterName = CookieServerCsrfTokenRepository.DEFAULT_CSRF_PARAMETER_NAME; private Duration expectedMaxAge = Duration.ofSeconds(-1); private String expectedDomain = null; private String expectedPath = "/"; private boolean expectedSecure = false; private boolean expectedHttpOnly = true; private String expectedCookieName = CookieServerCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME; private String expectedCookieValue = "csrfToken"; private String expectedSameSitePolicy = null; @BeforeEach void setUp() { this.csrfTokenRepository = new CookieServerCsrfTokenRepository(); this.request = MockServerHttpRequest.get("/someUri"); } @Test void generateTokenWhenDefaultThenDefaults() { generateTokenAndAssertExpectedValues(); } @Test void generateTokenWhenCustomHeaderThenCustomHeader() { setExpectedHeaderName("someHeader"); generateTokenAndAssertExpectedValues(); } @Test void generateTokenWhenCustomParameterThenCustomParameter() { setExpectedParameterName("someParam"); generateTokenAndAssertExpectedValues(); } @Test void generateTokenWhenCustomHeaderAndParameterThenCustomHeaderAndParameter() { setExpectedHeaderName("someHeader"); setExpectedParameterName("someParam"); generateTokenAndAssertExpectedValues(); } @Test void saveTokenWhenNoSubscriptionThenNotWritten() { MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.csrfTokenRepository.saveToken(exchange, createToken()); assertThat(exchange.getResponse().getCookies().getFirst(this.expectedCookieName)).isNull(); } @Test void saveTokenWhenDefaultThenDefaults() { saveAndAssertExpectedValues(createToken()); } @Test void saveTokenWhenNullThenDeletes() { saveAndAssertExpectedValues(null); } @Test void saveTokenWhenHttpOnlyFalseThenHttpOnlyFalse() { setExpectedHttpOnly(false); saveAndAssertExpectedValues(createToken()); } @Test void saveTokenWhenCookieMaxAgeThenCookieMaxAge() { setExpectedCookieMaxAge(3600); saveAndAssertExpectedValues(createToken()); } @Test void saveTokenWhenSameSiteThenCookieSameSite() { setExpectedSameSitePolicy("Lax"); saveAndAssertExpectedValues(createToken()); } @Test void saveTokenWhenCustomPropertiesThenCustomProperties() { setExpectedDomain("spring.io"); setExpectedCookieName("csrfCookie"); setExpectedPath("/some/path"); setExpectedHeaderName("headerName"); setExpectedParameterName("paramName"); setExpectedSameSitePolicy("Strict"); setExpectedCookieMaxAge(3600); saveAndAssertExpectedValues(createToken()); } @Test void saveTokenWhenCustomPropertiesThenCustomPropertiesUsingCustomizer() { String expectedDomain = "spring.io"; int expectedMaxAge = 3600; String expectedPath = "/some/path"; String expectedSameSite = "Strict"; setExpectedCookieName("csrfCookie"); setExpectedHeaderName("headerName"); setExpectedParameterName("paramName"); CsrfToken token = createToken(); this.csrfTokenRepository.setCookieCustomizer((customizer) -> { customizer.domain(expectedDomain); customizer.maxAge(expectedMaxAge); customizer.path(expectedPath); customizer.sameSite(expectedSameSite); }); MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.csrfTokenRepository.saveToken(exchange, token).block(); ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName); assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isEqualTo(Duration.of(expectedMaxAge, ChronoUnit.SECONDS)); assertThat(cookie.getDomain()).isEqualTo(expectedDomain); assertThat(cookie.getPath()).isEqualTo(expectedPath); assertThat(cookie.getSameSite()).isEqualTo(expectedSameSite); assertThat(cookie.isSecure()).isEqualTo(this.expectedSecure); assertThat(cookie.isHttpOnly()).isEqualTo(this.expectedHttpOnly); assertThat(cookie.getName()).isEqualTo(this.expectedCookieName); assertThat(cookie.getValue()).isEqualTo(this.expectedCookieValue); } @Test void saveTokenWhenSslInfoPresentThenSecure() { this.request.sslInfo(new MockSslInfo()); MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.csrfTokenRepository.saveToken(exchange, createToken()).block(); ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName); assertThat(cookie).isNotNull(); assertThat(cookie.isSecure()).isTrue(); } @Test void saveTokenWhenSslInfoNullThenNotSecure() { MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.csrfTokenRepository.saveToken(exchange, createToken()).block(); ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName); assertThat(cookie).isNotNull(); assertThat(cookie.isSecure()).isFalse(); } @Test void saveTokenWhenSecureFlagTrueThenSecure() { MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.csrfTokenRepository.setSecure(true); this.csrfTokenRepository.saveToken(exchange, createToken()).block(); ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName); assertThat(cookie).isNotNull(); assertThat(cookie.isSecure()).isTrue(); } @Test void saveTokenWhenSecureFlagTrueThenSecureUsingCustomizer() { MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.csrfTokenRepository.setCookieCustomizer((customizer) -> customizer.secure(true)); this.csrfTokenRepository.saveToken(exchange, createToken()).block(); ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName); assertThat(cookie).isNotNull(); assertThat(cookie.isSecure()).isTrue(); } @Test void saveTokenWhenSecureFlagFalseThenNotSecure() { MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.csrfTokenRepository.setSecure(false); this.csrfTokenRepository.saveToken(exchange, createToken()).block(); ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName); assertThat(cookie).isNotNull(); assertThat(cookie.isSecure()).isFalse(); } @Test void saveTokenWhenSecureFlagFalseThenNotSecureUsingCustomizer() { MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.csrfTokenRepository.setCookieCustomizer((customizer) -> customizer.secure(false)); this.csrfTokenRepository.saveToken(exchange, createToken()).block(); ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName); assertThat(cookie).isNotNull(); assertThat(cookie.isSecure()).isFalse(); } @Test void saveTokenWhenSecureFlagFalseAndSslInfoThenNotSecure() { MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.request.sslInfo(new MockSslInfo()); this.csrfTokenRepository.setSecure(false); this.csrfTokenRepository.saveToken(exchange, createToken()).block(); ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName); assertThat(cookie).isNotNull(); assertThat(cookie.isSecure()).isFalse(); } @Test void saveTokenWhenSecureFlagFalseAndSslInfoThenNotSecureUsingCustomizer() { MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.request.sslInfo(new MockSslInfo()); this.csrfTokenRepository.setCookieCustomizer((customizer) -> customizer.secure(false)); this.csrfTokenRepository.saveToken(exchange, createToken()).block(); ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName); assertThat(cookie).isNotNull(); assertThat(cookie.isSecure()).isFalse(); } @Test void loadTokenWhenCookieExistThenTokenFound() { loadAndAssertExpectedValues(); } @Test void loadTokenWhenCustomThenTokenFound() { setExpectedParameterName("paramName"); setExpectedHeaderName("headerName"); setExpectedCookieName("csrfCookie"); saveAndAssertExpectedValues(createToken()); } @Test void loadTokenWhenNoCookiesThenNullToken() { MockServerWebExchange exchange = MockServerWebExchange.from(this.request); CsrfToken csrfToken = this.csrfTokenRepository.loadToken(exchange).block(); assertThat(csrfToken).isNull(); } @Test void loadTokenWhenCookieExistsWithNoValue() { setExpectedCookieValue(""); loadAndAssertExpectedValues(); } @Test void loadTokenWhenCookieExistsWithNullValue() { setExpectedCookieValue(null); loadAndAssertExpectedValues(); } private void setExpectedHeaderName(String expectedHeaderName) { this.csrfTokenRepository.setHeaderName(expectedHeaderName); this.expectedHeaderName = expectedHeaderName; } private void setExpectedParameterName(String expectedParameterName) { this.csrfTokenRepository.setParameterName(expectedParameterName); this.expectedParameterName = expectedParameterName; } private void setExpectedDomain(String expectedDomain) { this.csrfTokenRepository.setCookieDomain(expectedDomain); this.expectedDomain = expectedDomain; } private void setExpectedPath(String expectedPath) { this.csrfTokenRepository.setCookiePath(expectedPath); this.expectedPath = expectedPath; } private void setExpectedHttpOnly(boolean expectedHttpOnly) { this.expectedHttpOnly = expectedHttpOnly; this.csrfTokenRepository.setCookieHttpOnly(expectedHttpOnly); } private void setExpectedCookieName(String expectedCookieName) { this.expectedCookieName = expectedCookieName; this.csrfTokenRepository.setCookieName(expectedCookieName); } private void setExpectedCookieMaxAge(int expectedCookieMaxAge) { this.csrfTokenRepository.setCookieMaxAge(expectedCookieMaxAge); this.expectedMaxAge = Duration.ofSeconds(expectedCookieMaxAge); } private void setExpectedSameSitePolicy(String sameSitePolicy) { this.csrfTokenRepository.setCookieCustomizer((customizer) -> customizer.sameSite(sameSitePolicy)); this.expectedSameSitePolicy = sameSitePolicy; } private void setExpectedCookieValue(String expectedCookieValue) { this.expectedCookieValue = expectedCookieValue; } private void loadAndAssertExpectedValues() { MockServerHttpRequest.BodyBuilder request = MockServerHttpRequest.post("/someUri") .cookie(new HttpCookie(this.expectedCookieName, this.expectedCookieValue)); MockServerWebExchange exchange = MockServerWebExchange.from(request); CsrfToken csrfToken = this.csrfTokenRepository.loadToken(exchange).block(); if (StringUtils.hasText(this.expectedCookieValue)) { assertThat(csrfToken).isNotNull(); assertThat(csrfToken.getHeaderName()).isEqualTo(this.expectedHeaderName); assertThat(csrfToken.getParameterName()).isEqualTo(this.expectedParameterName); assertThat(csrfToken.getToken()).isEqualTo(this.expectedCookieValue); } else { assertThat(csrfToken).isNull(); } } private void saveAndAssertExpectedValues(CsrfToken token) { if (token == null) { this.expectedMaxAge = Duration.ofSeconds(0); this.expectedCookieValue = ""; } MockServerWebExchange exchange = MockServerWebExchange.from(this.request); this.csrfTokenRepository.saveToken(exchange, token).block(); ResponseCookie cookie = exchange.getResponse().getCookies().getFirst(this.expectedCookieName); assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isEqualTo(this.expectedMaxAge); assertThat(cookie.getDomain()).isEqualTo(this.expectedDomain); assertThat(cookie.getPath()).isEqualTo(this.expectedPath); assertThat(cookie.isSecure()).isEqualTo(this.expectedSecure); assertThat(cookie.isHttpOnly()).isEqualTo(this.expectedHttpOnly); assertThat(cookie.getName()).isEqualTo(this.expectedCookieName); assertThat(cookie.getValue()).isEqualTo(this.expectedCookieValue); assertThat(cookie.getSameSite()).isEqualTo(this.expectedSameSitePolicy); } private void generateTokenAndAssertExpectedValues() { MockServerWebExchange exchange = MockServerWebExchange.from(this.request); CsrfToken csrfToken = this.csrfTokenRepository.generateToken(exchange).block(); assertThat(csrfToken).isNotNull(); assertThat(csrfToken.getHeaderName()).isEqualTo(this.expectedHeaderName); assertThat(csrfToken.getParameterName()).isEqualTo(this.expectedParameterName); assertThat(csrfToken.getToken()).isNotBlank(); } private CsrfToken createToken() { return createToken(this.expectedHeaderName, this.expectedParameterName, this.expectedCookieValue); } private static CsrfToken createToken(String headerName, String parameterName, String tokenValue) { return new DefaultCsrfToken(headerName, parameterName, tokenValue); } static class MockSslInfo implements SslInfo { @Override public String getSessionId() { return "sessionId"; } @Override public X509Certificate[] getPeerCertificates() { return new X509Certificate[] {}; } } }
14,416
34.685644
100
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/csrf/CsrfWebFilterTests.java
/* * Copyright 2002-2022 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.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.test.publisher.PublisherProbe; 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.reactive.function.BodyInserters; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.WebSession; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @author Parikshit Dutta * @since 5.0 */ @ExtendWith(MockitoExtension.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 = MockServerWebExchange.from(MockServerHttpRequest.get("/")); private MockServerWebExchange post = MockServerWebExchange.from(MockServerHttpRequest.post("/")); @Test public void setRequestHandlerWhenNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.csrfFilter.setRequestHandler(null)) .withMessage("requestHandler cannot be null"); // @formatter:on } @Test public void filterWhenGetThenSessionNotCreatedAndChainContinues() { PublisherProbe<Void> chainResult = PublisherProbe.empty(); given(this.chain.filter(this.get)).willReturn(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); given(this.repository.loadToken(any())).willReturn(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); StepVerifier.create(this.post.getResponse().getBodyAsString()) .assertNext((body) -> assertThat(body).contains("An expected CSRF token cannot be found")); } @Test public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamInvalidTokenThenCsrfException() { this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); this.post = MockServerWebExchange.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(); given(this.chain.filter(any())).willReturn(chainResult.mono()); this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); CsrfToken csrfToken = createXorCsrfToken(); this.post = MockServerWebExchange .from(MockServerHttpRequest.post("/").contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(csrfToken.getParameterName() + "=" + csrfToken.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); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); this.post = MockServerWebExchange.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(); given(this.chain.filter(any())).willReturn(chainResult.mono()); this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); CsrfToken csrfToken = createXorCsrfToken(); this.post = MockServerWebExchange .from(MockServerHttpRequest.post("/").header(csrfToken.getHeaderName(), csrfToken.getToken())); Mono<Void> result = this.csrfFilter.filter(this.post, this.chain); StepVerifier.create(result).verifyComplete(); chainResult.assertWasSubscribed(); } @Test public void filterWhenRequestHandlerSetThenUsed() { ServerCsrfTokenRequestHandler requestHandler = mock(ServerCsrfTokenRequestHandler.class); given(requestHandler.resolveCsrfTokenValue(any(ServerWebExchange.class), any(CsrfToken.class))) .willReturn(Mono.just(this.token.getToken())); this.csrfFilter.setRequestHandler(requestHandler); PublisherProbe<Void> chainResult = PublisherProbe.empty(); given(this.chain.filter(any())).willReturn(chainResult.mono()); this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); this.post = MockServerWebExchange .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(); verify(requestHandler).handle(eq(this.post), any()); verify(requestHandler).resolveCsrfTokenValue(this.post, this.token); } @Test public void filterWhenXorServerCsrfTokenRequestAttributeHandlerAndValidTokenThenSuccess() { PublisherProbe<Void> chainResult = PublisherProbe.empty(); given(this.chain.filter(any())).willReturn(chainResult.mono()); this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); CsrfToken csrfToken = createXorCsrfToken(); this.post = MockServerWebExchange .from(MockServerHttpRequest.post("/").header(csrfToken.getHeaderName(), csrfToken.getToken())); StepVerifier.create(this.csrfFilter.filter(this.post, this.chain)).verifyComplete(); chainResult.assertWasSubscribed(); } @Test public void filterWhenXorServerCsrfTokenRequestAttributeHandlerAndRawTokenThenAccessDeniedException() { PublisherProbe<Void> chainResult = PublisherProbe.empty(); this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); XorServerCsrfTokenRequestAttributeHandler requestHandler = new XorServerCsrfTokenRequestAttributeHandler(); this.csrfFilter.setRequestHandler(requestHandler); this.post = MockServerWebExchange .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.assertWasNotSubscribed(); assertThat(this.post.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test // gh-8452 public void matchesRequireCsrfProtectionWhenNonStandardHTTPMethodIsUsed() { MockServerWebExchange nonStandardHttpExchange = MockServerWebExchange .from(MockServerHttpRequest.method("non-standard-http-method", "/")); ServerWebExchangeMatcher serverWebExchangeMatcher = CsrfWebFilter.DEFAULT_CSRF_MATCHER; assertThat(serverWebExchangeMatcher.matches(nonStandardHttpExchange).map(MatchResult::isMatch).block()) .isTrue(); } @Test public void doFilterWhenSkipExchangeInvokedThenSkips() { PublisherProbe<Void> chainResult = PublisherProbe.empty(); given(this.chain.filter(any())).willReturn(chainResult.mono()); ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class); this.csrfFilter.setRequireCsrfProtectionMatcher(matcher); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/post").build()); CsrfWebFilter.skipExchange(exchange); this.csrfFilter.filter(exchange, this.chain).block(); verifyNoMoreInteractions(matcher); } @Test public void filterWhenMultipartFormDataAndNotEnabledThenDenied() { this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); client.post().uri("/").contentType(MediaType.MULTIPART_FORM_DATA) .body(BodyInserters.fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange() .expectStatus().isForbidden(); } @Test public void filterWhenMultipartFormDataAndEnabledThenGranted() { this.csrfFilter.setCsrfTokenRepository(this.repository); ServerCsrfTokenRequestAttributeHandler requestHandler = new ServerCsrfTokenRequestAttributeHandler(); requestHandler.setTokenFromMultipartDataEnabled(true); this.csrfFilter.setRequestHandler(requestHandler); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); client.post().uri("/").contentType(MediaType.MULTIPART_FORM_DATA) .body(BodyInserters.fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange() .expectStatus().is2xxSuccessful(); } @Test public void filterWhenPostAndMultipartFormDataEnabledAndNoBodyProvided() { this.csrfFilter.setCsrfTokenRepository(this.repository); ServerCsrfTokenRequestAttributeHandler requestHandler = new ServerCsrfTokenRequestAttributeHandler(); requestHandler.setTokenFromMultipartDataEnabled(true); this.csrfFilter.setRequestHandler(requestHandler); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); client.post().uri("/").header(this.token.getHeaderName(), this.token.getToken()).exchange().expectStatus() .is2xxSuccessful(); } @Test public void filterWhenFormDataAndEnabledThenGranted() { this.csrfFilter.setCsrfTokenRepository(this.repository); ServerCsrfTokenRequestAttributeHandler requestHandler = new ServerCsrfTokenRequestAttributeHandler(); requestHandler.setTokenFromMultipartDataEnabled(true); this.csrfFilter.setRequestHandler(requestHandler); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); client.post().uri("/").contentType(MediaType.APPLICATION_FORM_URLENCODED) .bodyValue(this.token.getParameterName() + "=" + this.token.getToken()).exchange().expectStatus() .is2xxSuccessful(); } @Test public void filterWhenMultipartMixedAndEnabledThenNotRead() { this.csrfFilter.setCsrfTokenRepository(this.repository); ServerCsrfTokenRequestAttributeHandler requestHandler = new ServerCsrfTokenRequestAttributeHandler(); requestHandler.setTokenFromMultipartDataEnabled(true); this.csrfFilter.setRequestHandler(requestHandler); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); client.post().uri("/").contentType(MediaType.MULTIPART_MIXED) .bodyValue(this.token.getParameterName() + "=" + this.token.getToken()).exchange().expectStatus() .isForbidden(); } // gh-9561 @Test public void doFilterWhenTokenIsNullThenNoNullPointer() { this.csrfFilter.setCsrfTokenRepository(this.repository); CsrfToken token = mock(CsrfToken.class); given(token.getToken()).willReturn(null); given(token.getHeaderName()).willReturn(this.token.getHeaderName()); given(token.getParameterName()).willReturn(this.token.getParameterName()); given(this.repository.loadToken(any())).willReturn(Mono.just(token)); WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); client.post().uri("/").contentType(MediaType.APPLICATION_FORM_URLENCODED) .bodyValue(this.token.getParameterName() + "=" + this.token.getToken()).exchange().expectStatus() .isForbidden(); } // gh-9113 @Test public void filterWhenSubscribingCsrfTokenMultipleTimesThenGenerateOnlyOnce() { PublisherProbe<CsrfToken> chainResult = PublisherProbe.empty(); this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.empty()); given(this.repository.generateToken(any())).willReturn(chainResult.mono()); given(this.chain.filter(any())).willReturn(Mono.empty()); this.csrfFilter.filter(this.get, this.chain).block(); Mono<CsrfToken> result = this.get.getAttribute(CsrfToken.class.getName()); result.block(); result.block(); assertThat(chainResult.subscribeCount()).isEqualTo(1); } private CsrfToken createXorCsrfToken() { ServerCsrfTokenRequestHandler handler = new XorServerCsrfTokenRequestAttributeHandler(); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); handler.handle(exchange, Mono.just(this.token)); Mono<CsrfToken> csrfToken = exchange.getAttribute(CsrfToken.class.getName()); return csrfToken.block(); } @RestController static class OkController { @RequestMapping("/**") String ok() { return "ok"; } } }
16,647
46.430199
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/csrf/XorServerCsrfTokenRequestAttributeHandlerTests.java
/* * Copyright 2002-2022 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 java.security.SecureRandom; import java.util.Arrays; import java.util.Base64; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link XorServerCsrfTokenRequestAttributeHandler}. * * @author Steve Riesenberg * @since 5.8 */ public class XorServerCsrfTokenRequestAttributeHandlerTests { private static final byte[] XOR_CSRF_TOKEN_BYTES = new byte[] { 1, 1, 1, 96, 99, 98 }; private static final String XOR_CSRF_TOKEN_VALUE = Base64.getEncoder().encodeToString(XOR_CSRF_TOKEN_BYTES); private XorServerCsrfTokenRequestAttributeHandler handler; private MockServerWebExchange exchange; private CsrfToken token; private SecureRandom secureRandom; @BeforeEach public void setUp() { this.handler = new XorServerCsrfTokenRequestAttributeHandler(); this.exchange = MockServerWebExchange.builder(MockServerHttpRequest.get("/")).build(); this.token = new DefaultCsrfToken("headerName", "paramName", "abc"); this.secureRandom = mock(SecureRandom.class); } @Test public void setSecureRandomWhenNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.setSecureRandom(null)) .withMessage("secureRandom cannot be null"); // @formatter:on } @Test public void handleWhenExchangeIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.handle(null, Mono.just(this.token))) .withMessage("exchange cannot be null"); // @formatter:on } @Test public void handleWhenCsrfTokenIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.handle(this.exchange, null)) .withMessage("csrfToken cannot be null"); // @formatter:on } @Test public void handleWhenSecureRandomSetThenUsed() { this.handler.setSecureRandom(this.secureRandom); this.handler.handle(this.exchange, Mono.just(this.token)); Mono<CsrfToken> csrfTokenAttribute = this.exchange.getAttribute(CsrfToken.class.getName()); assertThat(csrfTokenAttribute).isNotNull(); StepVerifier.create(csrfTokenAttribute).expectNextCount(1).verifyComplete(); verify(this.secureRandom).nextBytes(anyByteArray()); } @Test public void handleWhenValidParametersThenExchangeAttributeSet() { willAnswer(fillByteArray()).given(this.secureRandom).nextBytes(anyByteArray()); this.handler.setSecureRandom(this.secureRandom); this.handler.handle(this.exchange, Mono.just(this.token)); Mono<CsrfToken> csrfTokenAttribute = this.exchange.getAttribute(CsrfToken.class.getName()); assertThat(csrfTokenAttribute).isNotNull(); // @formatter:off StepVerifier.create(csrfTokenAttribute) .assertNext((csrfToken) -> assertThat(csrfToken.getToken()).isEqualTo(XOR_CSRF_TOKEN_VALUE)) .verifyComplete(); // @formatter:on verify(this.secureRandom).nextBytes(anyByteArray()); } @Test public void handleWhenCsrfTokenRequestedTwiceThenCached() { this.handler.handle(this.exchange, Mono.just(this.token)); Mono<CsrfToken> csrfTokenAttribute = this.exchange.getAttribute(CsrfToken.class.getName()); assertThat(csrfTokenAttribute).isNotNull(); CsrfToken csrfToken1 = csrfTokenAttribute.block(); CsrfToken csrfToken2 = csrfTokenAttribute.block(); assertThat(csrfToken1.getToken()).isNotEqualTo(this.token.getToken()); assertThat(csrfToken1.getToken()).isEqualTo(csrfToken2.getToken()); } @Test public void resolveCsrfTokenValueWhenExchangeIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.resolveCsrfTokenValue(null, this.token)) .withMessage("exchange cannot be null"); // @formatter:on } @Test public void resolveCsrfTokenValueWhenCsrfTokenIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.resolveCsrfTokenValue(this.exchange, null)) .withMessage("csrfToken cannot be null"); // @formatter:on } @Test public void resolveCsrfTokenValueWhenTokenNotSetThenReturnsEmptyMono() { Mono<String> csrfToken = this.handler.resolveCsrfTokenValue(this.exchange, this.token); StepVerifier.create(csrfToken).verifyComplete(); } @Test public void resolveCsrfTokenValueWhenFormDataSetThenReturnsTokenValue() { this.exchange = MockServerWebExchange.builder(MockServerHttpRequest.post("/") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .body(this.token.getParameterName() + "=" + XOR_CSRF_TOKEN_VALUE)).build(); Mono<String> csrfToken = this.handler.resolveCsrfTokenValue(this.exchange, this.token); StepVerifier.create(csrfToken).expectNext(this.token.getToken()).verifyComplete(); } @Test public void resolveCsrfTokenValueWhenHeaderSetThenReturnsTokenValue() { this.exchange = MockServerWebExchange.builder(MockServerHttpRequest.post("/") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .header(this.token.getHeaderName(), XOR_CSRF_TOKEN_VALUE)).build(); Mono<String> csrfToken = this.handler.resolveCsrfTokenValue(this.exchange, this.token); StepVerifier.create(csrfToken).expectNext(this.token.getToken()).verifyComplete(); } @Test public void resolveCsrfTokenValueWhenHeaderAndFormDataSetThenFormDataIsPreferred() { this.exchange = MockServerWebExchange.builder(MockServerHttpRequest.post("/") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .header(this.token.getHeaderName(), "header") .body(this.token.getParameterName() + "=" + XOR_CSRF_TOKEN_VALUE)).build(); Mono<String> csrfToken = this.handler.resolveCsrfTokenValue(this.exchange, this.token); StepVerifier.create(csrfToken).expectNext(this.token.getToken()).verifyComplete(); } private static Answer<Void> fillByteArray() { return (invocation) -> { byte[] bytes = invocation.getArgument(0); Arrays.fill(bytes, (byte) 1); return null; }; } private static byte[] anyByteArray() { return any(byte[].class); } }
7,474
36.752525
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/csrf/WebSessionServerCsrfTokenRepositoryTests.java
/* * Copyright 2002-2017 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 java.util.Map; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.WebSession; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @since 5.0 */ public class WebSessionServerCsrfTokenRepositoryTests { private WebSessionServerCsrfTokenRepository repository = new WebSessionServerCsrfTokenRepository(); private MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); @Test public void generateTokenThenNoSession() { Mono<CsrfToken> result = this.repository.generateToken(this.exchange); Mono<Boolean> isSessionStarted = this.exchange.getSession().map(WebSession::isStarted); StepVerifier.create(isSessionStarted).expectNext(false).verifyComplete(); } @Test public void generateTokenWhenSubscriptionThenNoSession() { Mono<CsrfToken> result = this.repository.generateToken(this.exchange); Mono<Boolean> isSessionStarted = this.exchange.getSession().map(WebSession::isStarted); StepVerifier.create(isSessionStarted).expectNext(false).verifyComplete(); } @Test public void saveTokenWhenDefaultThenAddsToSession() { Mono<CsrfToken> result = this.repository.generateToken(this.exchange) .delayUntil((t) -> this.repository.saveToken(this.exchange, t)); result.block(); WebSession session = this.exchange.getSession().block(); Map<String, Object> attributes = session.getAttributes(); assertThat(session.isStarted()).isTrue(); assertThat(attributes).hasSize(1); assertThat(attributes.values().iterator().next()).isInstanceOf(CsrfToken.class); } @Test public void saveTokenWhenNullThenDeletes() { CsrfToken token = this.repository.generateToken(this.exchange).block(); Mono<Void> result = this.repository.saveToken(this.exchange, null); StepVerifier.create(result).verifyComplete(); WebSession session = this.exchange.getSession().block(); assertThat(session.getAttributes()).isEmpty(); } @Test public void saveTokenChangeSessionId() { String originalSessionId = this.exchange.getSession().block().getId(); this.repository.saveToken(this.exchange, null).block(); WebSession session = this.exchange.getSession().block(); assertThat(session.getId()).isNotEqualTo(originalSessionId); } }
3,141
35.964706
101
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/csrf/ServerCsrfTokenRequestAttributeHandlerTests.java
/* * Copyright 2002-2022 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.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ServerCsrfTokenRequestAttributeHandler}. * * @author Steve Riesenberg * @since 5.8 */ public class ServerCsrfTokenRequestAttributeHandlerTests { private ServerCsrfTokenRequestAttributeHandler handler; private MockServerWebExchange exchange; private CsrfToken token; @BeforeEach public void setUp() { this.handler = new ServerCsrfTokenRequestAttributeHandler(); this.exchange = MockServerWebExchange.builder(MockServerHttpRequest.get("/")).build(); this.token = new DefaultCsrfToken("headerName", "paramName", "csrfTokenValue"); } @Test public void handleWhenExchangeIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.handle(null, Mono.just(this.token))) .withMessage("exchange cannot be null"); // @formatter:on } @Test public void handleWhenCsrfTokenIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.handle(this.exchange, null)) .withMessage("csrfToken cannot be null"); // @formatter:on } @Test public void handleWhenValidParametersThenExchangeAttributeSet() { Mono<CsrfToken> csrfToken = Mono.just(this.token); this.handler.handle(this.exchange, csrfToken); Mono<CsrfToken> csrfTokenAttribute = this.exchange.getAttribute(CsrfToken.class.getName()); assertThat(csrfTokenAttribute).isNotNull(); assertThat(csrfTokenAttribute).isEqualTo(csrfToken); } @Test public void resolveCsrfTokenValueWhenExchangeIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.resolveCsrfTokenValue(null, this.token)) .withMessage("exchange cannot be null"); // @formatter:on } @Test public void resolveCsrfTokenValueWhenCsrfTokenIsNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.handler.resolveCsrfTokenValue(this.exchange, null)) .withMessage("csrfToken cannot be null"); // @formatter:on } @Test public void resolveCsrfTokenValueWhenTokenNotSetThenReturnsEmptyMono() { Mono<String> csrfToken = this.handler.resolveCsrfTokenValue(this.exchange, this.token); StepVerifier.create(csrfToken).verifyComplete(); } @Test public void resolveCsrfTokenValueWhenFormDataSetThenReturnsTokenValue() { this.exchange = MockServerWebExchange.builder(MockServerHttpRequest.post("/") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .body(this.token.getParameterName() + "=" + this.token.getToken())).build(); Mono<String> csrfToken = this.handler.resolveCsrfTokenValue(this.exchange, this.token); StepVerifier.create(csrfToken).expectNext(this.token.getToken()).verifyComplete(); } @Test public void resolveCsrfTokenValueWhenHeaderSetThenReturnsTokenValue() { this.exchange = MockServerWebExchange.builder(MockServerHttpRequest.post("/") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .header(this.token.getHeaderName(), this.token.getToken())).build(); Mono<String> csrfToken = this.handler.resolveCsrfTokenValue(this.exchange, this.token); StepVerifier.create(csrfToken).expectNext(this.token.getToken()).verifyComplete(); } @Test public void resolveCsrfTokenValueWhenHeaderAndFormDataSetThenFormDataIsPreferred() { this.exchange = MockServerWebExchange.builder(MockServerHttpRequest.post("/") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .header(this.token.getHeaderName(), "header") .body(this.token.getParameterName() + "=" + this.token.getToken())).build(); Mono<String> csrfToken = this.handler.resolveCsrfTokenValue(this.exchange, this.token); StepVerifier.create(csrfToken).expectNext(this.token.getToken()).verifyComplete(); } }
5,106
37.398496
93
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/csrf/CsrfServerLogoutHandlerTests.java
/* * Copyright 2002-2018 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.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; /** * @author Eric Deandrea * @since 5.1 */ @ExtendWith(MockitoExtension.class) public class CsrfServerLogoutHandlerTests { @Mock private ServerCsrfTokenRepository csrfTokenRepository; @Mock private WebFilterChain filterChain; private MockServerWebExchange exchange; private WebFilterExchange filterExchange; private CsrfServerLogoutHandler handler; @BeforeEach public void setup() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.filterExchange = new WebFilterExchange(this.exchange, this.filterChain); this.handler = new CsrfServerLogoutHandler(this.csrfTokenRepository); } @Test public void constructorNullCsrfTokenRepository() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new CsrfServerLogoutHandler(null)) .withMessage("csrfTokenRepository cannot be null").withNoCause(); } @Test public void logoutRemovesCsrfToken() { given(this.csrfTokenRepository.saveToken(this.exchange, null)).willReturn(Mono.empty()); this.handler.logout(this.filterExchange, new TestingAuthenticationToken("user", "password", "ROLE_USER")) .block(); verify(this.csrfTokenRepository).saveToken(this.exchange, null); } }
2,642
33.324675
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/context/NoOpServerSecurityContextRepositoryTests.java
/* * Copyright 2002-2017 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.context; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.web.server.ServerWebExchange; /** * @author Rob Winch * @since 5.0 */ public class NoOpServerSecurityContextRepositoryTests { NoOpServerSecurityContextRepository repository = NoOpServerSecurityContextRepository.getInstance(); ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); @Test public void saveAndLoad() { SecurityContext context = new SecurityContextImpl(); Mono<SecurityContext> result = this.repository.save(this.exchange, context) .then(this.repository.load(this.exchange)); StepVerifier.create(result).verifyComplete(); } }
1,695
34.333333
100
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/context/ReactorContextWebFilterTests.java
/* * Copyright 2002-2017 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.context; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.test.publisher.TestPublisher; import reactor.util.context.Context; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.test.web.reactive.server.WebTestHandler; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.handler.DefaultWebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class ReactorContextWebFilterTests { @Mock private Authentication principal; @Mock private ServerSecurityContextRepository repository; private MockServerHttpRequest.BaseBuilder<?> exchange = MockServerHttpRequest.get("/"); private TestPublisher<SecurityContext> securityContext = TestPublisher.create(); private ReactorContextWebFilter filter; private WebTestHandler handler; @BeforeEach public void setup() { this.filter = new ReactorContextWebFilter(this.repository); this.handler = WebTestHandler.bindToWebFilters(this.filter); } @Test public void constructorNullSecurityContextRepository() { assertThatIllegalArgumentException().isThrownBy(() -> new ReactorContextWebFilter(null)); } @Test public void filterWhenNoPrincipalAccessThenNoInteractions() { given(this.repository.load(any())).willReturn(this.securityContext.mono()); this.handler.exchange(this.exchange); this.securityContext.assertWasNotSubscribed(); } @Test public void filterWhenGetPrincipalMonoThenNoInteractions() { given(this.repository.load(any())).willReturn(this.securityContext.mono()); this.handler = WebTestHandler.bindToWebFilters(this.filter, (e, c) -> { ReactiveSecurityContextHolder.getContext(); return c.filter(e); }); this.handler.exchange(this.exchange); this.securityContext.assertWasNotSubscribed(); } @Test public void filterWhenPrincipalAndGetPrincipalThenInteractAndUseOriginalPrincipal() { SecurityContextImpl context = new SecurityContextImpl(this.principal); given(this.repository.load(any())).willReturn(Mono.just(context)); this.handler = WebTestHandler.bindToWebFilters(this.filter, (e, c) -> ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication) .doOnSuccess((p) -> assertThat(p).isSameAs(this.principal)).flatMap((p) -> c.filter(e))); WebTestHandler.WebHandlerResult result = this.handler.exchange(this.exchange); this.securityContext.assertWasNotSubscribed(); } @Test // gh-4962 public void filterWhenMainContextThenDoesNotOverride() { given(this.repository.load(any())).willReturn(this.securityContext.mono()); String contextKey = "main"; WebFilter mainContextWebFilter = (e, c) -> c.filter(e).contextWrite(Context.of(contextKey, true)); WebFilterChain chain = new DefaultWebFilterChain((e) -> Mono.empty(), List.of(mainContextWebFilter, this.filter)); Mono<Void> filter = chain.filter(MockServerWebExchange.from(this.exchange.build())); StepVerifier.create(filter).expectAccessibleContext().hasKey(contextKey).then().verifyComplete(); } }
4,618
37.173554
100
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/context/WebSessionServerSecurityContextRepositoryTests.java
/* * Copyright 2002-2017 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.context; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.publisher.PublisherProbe; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Rob Winch * @since 5.0 */ public class WebSessionServerSecurityContextRepositoryTests { private MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); private WebSessionServerSecurityContextRepository repository = new WebSessionServerSecurityContextRepository(); @Test public void saveAndLoadWhenDefaultsThenFound() { SecurityContext expected = new SecurityContextImpl(); this.repository.save(this.exchange, expected).block(); SecurityContext actual = this.repository.load(this.exchange).block(); assertThat(actual).isEqualTo(expected); } @Test public void saveAndLoadWhenCustomAttributeThenFound() { String attrName = "attr"; this.repository.setSpringSecurityContextAttrName(attrName); SecurityContext expected = new SecurityContextImpl(); this.repository.save(this.exchange, expected).block(); WebSession session = this.exchange.getSession().block(); assertThat(session.<SecurityContext>getAttribute(attrName)).isEqualTo(expected); SecurityContext actual = this.repository.load(this.exchange).block(); assertThat(actual).isEqualTo(expected); } @Test public void saveAndLoadWhenNullThenDeletes() { SecurityContext context = new SecurityContextImpl(); this.repository.save(this.exchange, context).block(); this.repository.save(this.exchange, null).block(); SecurityContext actual = this.repository.load(this.exchange).block(); assertThat(actual).isNull(); } @Test public void saveWhenNewContextThenChangeSessionId() { String originalSessionId = this.exchange.getSession().block().getId(); this.repository.save(this.exchange, new SecurityContextImpl()).block(); WebSession session = this.exchange.getSession().block(); assertThat(session.getId()).isNotEqualTo(originalSessionId); } @Test public void loadWhenNullThenNull() { SecurityContext context = this.repository.load(this.exchange).block(); assertThat(context).isNull(); } @Test public void loadWhenCacheSecurityContextThenSubscribeOnce() { PublisherProbe<WebSession> webSession = PublisherProbe.empty(); ServerWebExchange exchange = mock(ServerWebExchange.class); given(exchange.getSession()).willReturn(webSession.mono()); this.repository.setCacheSecurityContext(true); Mono<SecurityContext> context = this.repository.load(exchange); assertThat(context.block()).isSameAs(context.block()); assertThat(webSession.subscribeCount()).isEqualTo(1); } @Test public void loadWhenNotCacheSecurityContextThenSubscribeMultiple() { PublisherProbe<WebSession> webSession = PublisherProbe.empty(); ServerWebExchange exchange = mock(ServerWebExchange.class); given(exchange.getSession()).willReturn(webSession.mono()); Mono<SecurityContext> context = this.repository.load(exchange); assertThat(context.block()).isSameAs(context.block()); assertThat(webSession.subscribeCount()).isEqualTo(2); } }
4,225
37.770642
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/context/SecurityContextServerWebExchangeWebFilterTests.java
/* * Copyright 2002-2017 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.context; import java.util.Collections; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.handler.DefaultWebFilterChain; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @since 5.0 */ public class SecurityContextServerWebExchangeWebFilterTests { SecurityContextServerWebExchangeWebFilter filter = new SecurityContextServerWebExchangeWebFilter(); Authentication principal = new TestingAuthenticationToken("user", "password", "ROLE_USER"); ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); @Test public void filterWhenExistingContextAndPrincipalNotNullThenContextPopulated() { Mono<Void> result = this.filter .filter(this.exchange, new DefaultWebFilterChain((e) -> e.getPrincipal() .doOnSuccess((contextPrincipal) -> assertThat(contextPrincipal).isEqualTo(this.principal)) .flatMap((contextPrincipal) -> Mono.deferContextual(Mono::just)) .doOnSuccess((context) -> assertThat(context.<String>get("foo")).isEqualTo("bar")).then(), Collections.emptyList())) .contextWrite((context) -> context.put("foo", "bar")) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.principal)); StepVerifier.create(result).verifyComplete(); } @Test public void filterWhenPrincipalNotNullThenContextPopulated() { Mono<Void> result = this.filter .filter(this.exchange, new DefaultWebFilterChain((e) -> e.getPrincipal() .doOnSuccess( (contextPrincipal) -> assertThat(contextPrincipal).isEqualTo(this.principal)) .then(), Collections.emptyList())) .contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.principal)); StepVerifier.create(result).verifyComplete(); } @Test public void filterWhenPrincipalNullThenContextEmpty() { Authentication defaultAuthentication = new TestingAuthenticationToken("anonymouse", "anonymous", "TEST"); Mono<Void> result = this.filter.filter(this.exchange, new DefaultWebFilterChain((e) -> e.getPrincipal().defaultIfEmpty(defaultAuthentication) .doOnSuccess( (contextPrincipal) -> assertThat(contextPrincipal).isEqualTo(defaultAuthentication)) .then(), Collections.emptyList())); StepVerifier.create(result).verifyComplete(); } }
3,462
40.22619
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/jackson2/DefaultCsrfServerTokenMixinTests.java
/* * Copyright 2015-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 * * 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.jackson2; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import org.json.JSONException; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.web.jackson2.AbstractMixinTests; import org.springframework.security.web.server.csrf.DefaultCsrfToken; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Boris Finkelshteyn * @since 5.1 */ public class DefaultCsrfServerTokenMixinTests extends AbstractMixinTests { // @formatter:off private static final String CSRF_JSON = "{" + "\"@class\": \"org.springframework.security.web.server.csrf.DefaultCsrfToken\", " + "\"headerName\": \"csrf-header\", " + "\"parameterName\": \"_csrf\", " + "\"token\": \"1\"" + "}"; // @formatter:on @Test public void defaultCsrfTokenSerializedTest() throws JsonProcessingException, JSONException { DefaultCsrfToken token = new DefaultCsrfToken("csrf-header", "_csrf", "1"); String serializedJson = this.mapper.writeValueAsString(token); JSONAssert.assertEquals(CSRF_JSON, serializedJson, true); } @Test public void defaultCsrfTokenDeserializeTest() throws IOException { DefaultCsrfToken token = this.mapper.readValue(CSRF_JSON, DefaultCsrfToken.class); assertThat(token).isNotNull(); assertThat(token.getHeaderName()).isEqualTo("csrf-header"); assertThat(token.getParameterName()).isEqualTo("_csrf"); assertThat(token.getToken()).isEqualTo("1"); } @Test public void defaultCsrfTokenDeserializeWithoutClassTest() throws IOException { String tokenJson = "{\"headerName\": \"csrf-header\", \"parameterName\": \"_csrf\", \"token\": \"1\"}"; assertThatExceptionOfType(JsonMappingException.class) .isThrownBy(() -> this.mapper.readValue(tokenJson, DefaultCsrfToken.class)); } @Test public void defaultCsrfTokenDeserializeNullValuesTest() throws IOException { String tokenJson = "{\"@class\": \"org.springframework.security.web.server.csrf.DefaultCsrfToken\", \"headerName\": \"\", \"parameterName\": null, \"token\": \"1\"}"; assertThatExceptionOfType(JsonMappingException.class) .isThrownBy(() -> this.mapper.readValue(tokenJson, DefaultCsrfToken.class)); } }
3,029
37.846154
168
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/CrossOriginEmbedderPolicyServerHttpHeadersWriterTests.java
/* * Copyright 2002-2021 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.header; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; class CrossOriginEmbedderPolicyServerHttpHeadersWriterTests { private ServerWebExchange exchange; private CrossOriginEmbedderPolicyServerHttpHeadersWriter writer; @BeforeEach void setup() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); this.writer = new CrossOriginEmbedderPolicyServerHttpHeadersWriter(); } @Test void setEmbedderPolicyWhenNullEmbedderPolicyThenThrowsIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) .withMessage("embedderPolicy cannot be null"); } @Test void writeHeadersWhenNoValuesThenDoesNotWriteHeaders() { this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).isEmpty(); } @Test void writeHeadersWhenResponseHeaderExistsThenDontOverride() { this.exchange.getResponse().getHeaders().add(CrossOriginEmbedderPolicyServerHttpHeadersWriter.EMBEDDER_POLICY, "require-corp"); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(CrossOriginEmbedderPolicyServerHttpHeadersWriter.EMBEDDER_POLICY)) .containsOnly("require-corp"); } @Test void writeHeadersWhenSetHeaderValuesThenWrites() { this.writer.setPolicy(CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(CrossOriginEmbedderPolicyServerHttpHeadersWriter.EMBEDDER_POLICY)) .containsOnly("require-corp"); } }
2,866
36.233766
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/CrossOriginOpenerPolicyServerHttpHeadersWriterTests.java
/* * Copyright 2002-2021 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.header; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; class CrossOriginOpenerPolicyServerHttpHeadersWriterTests { private ServerWebExchange exchange; private CrossOriginOpenerPolicyServerHttpHeadersWriter writer; @BeforeEach void setup() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); this.writer = new CrossOriginOpenerPolicyServerHttpHeadersWriter(); } @Test void setOpenerPolicyWhenNullOpenerPolicyThenThrowsIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) .withMessage("openerPolicy cannot be null"); } @Test void writeHeadersWhenNoValuesThenDoesNotWriteHeaders() { this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).isEmpty(); } @Test void writeHeadersWhenResponseHeaderExistsThenDontOverride() { this.exchange.getResponse().getHeaders().add(CrossOriginOpenerPolicyServerHttpHeadersWriter.OPENER_POLICY, "same-origin"); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(CrossOriginOpenerPolicyServerHttpHeadersWriter.OPENER_POLICY)) .containsOnly("same-origin"); } @Test void writeHeadersWhenSetHeaderValuesThenWrites() { this.writer.setPolicy( CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(CrossOriginOpenerPolicyServerHttpHeadersWriter.OPENER_POLICY)) .containsOnly("same-origin-allow-popups"); } }
2,865
35.74359
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/XFrameOptionsServerHttpHeadersWriterTests.java
/* * Copyright 2002-2017 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.header; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @since 5.0 */ public class XFrameOptionsServerHttpHeadersWriterTests { ServerWebExchange exchange = exchange(MockServerHttpRequest.get("/")); XFrameOptionsServerHttpHeadersWriter writer; @BeforeEach public void setup() { this.writer = new XFrameOptionsServerHttpHeadersWriter(); } @Test public void writeHeadersWhenUsingDefaultsThenWritesDeny() { this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("DENY"); } @Test public void writeHeadersWhenUsingExplicitDenyThenWritesDeny() { this.writer.setMode(XFrameOptionsServerHttpHeadersWriter.Mode.DENY); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("DENY"); } @Test public void writeHeadersWhenUsingSameOriginThenWritesSameOrigin() { this.writer.setMode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("SAMEORIGIN"); } @Test public void writeHeadersWhenAlreadyWrittenThenWritesHeader() { String headerValue = "other"; this.exchange.getResponse().getHeaders().set(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, headerValue); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly(headerValue); } private static MockServerWebExchange exchange(MockServerHttpRequest.BaseBuilder<?> request) { return MockServerWebExchange.from(request.build()); } }
3,142
35.976471
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/FeaturePolicyServerHttpHeadersWriterTests.java
/* * Copyright 2002-2018 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.header; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link FeaturePolicyServerHttpHeadersWriter}. * * @author Vedran Pavic */ public class FeaturePolicyServerHttpHeadersWriterTests { private static final String DEFAULT_POLICY_DIRECTIVES = "geolocation 'self'"; private ServerWebExchange exchange; private FeaturePolicyServerHttpHeadersWriter writer; @BeforeEach public void setup() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); this.writer = new FeaturePolicyServerHttpHeadersWriter(); } @Test public void writeHeadersWhenUsingDefaultsThenDoesNotWrite() { this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).isEmpty(); } @Test public void writeHeadersWhenUsingPolicyThenWritesPolicy() { this.writer.setPolicyDirectives(DEFAULT_POLICY_DIRECTIVES); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(FeaturePolicyServerHttpHeadersWriter.FEATURE_POLICY)) .containsOnly(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersWhenAlreadyWrittenThenWritesHeader() { this.writer.setPolicyDirectives(DEFAULT_POLICY_DIRECTIVES); String headerValue = "camera: 'self'"; this.exchange.getResponse().getHeaders().set(FeaturePolicyServerHttpHeadersWriter.FEATURE_POLICY, headerValue); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(FeaturePolicyServerHttpHeadersWriter.FEATURE_POLICY)).containsOnly(headerValue); } }
2,737
34.558442
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/PermissionsPolicyServerHttpHeadersWriterTests.java
/* * 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.header; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PermissionsPolicyServerHttpHeadersWriter}. * * @author Christophe Gilles */ public class PermissionsPolicyServerHttpHeadersWriterTests { private static final String DEFAULT_POLICY_DIRECTIVES = "geolocation=(self)"; private ServerWebExchange exchange; private PermissionsPolicyServerHttpHeadersWriter writer; @BeforeEach public void setup() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); this.writer = new PermissionsPolicyServerHttpHeadersWriter(); } @Test public void writeHeadersWhenUsingDefaultsThenDoesNotWrite() { this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).isEmpty(); } @Test public void writeHeadersWhenUsingPolicyThenWritesPolicy() { this.writer.setPolicy(DEFAULT_POLICY_DIRECTIVES); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(PermissionsPolicyServerHttpHeadersWriter.PERMISSIONS_POLICY)) .containsOnly(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersWhenAlreadyWrittenThenWritesHeader() { this.writer.setPolicy(DEFAULT_POLICY_DIRECTIVES); String headerValue = "camera=(self)"; this.exchange.getResponse().getHeaders().set(PermissionsPolicyServerHttpHeadersWriter.PERMISSIONS_POLICY, headerValue); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(PermissionsPolicyServerHttpHeadersWriter.PERMISSIONS_POLICY)).containsOnly(headerValue); } }
2,765
34.461538
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/CacheControlServerHttpHeadersWriterTests.java
/* * Copyright 2002-2017 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.header; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @since 5.0 * */ public class CacheControlServerHttpHeadersWriterTests { CacheControlServerHttpHeadersWriter writer = new CacheControlServerHttpHeadersWriter(); ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); HttpHeaders headers = this.exchange.getResponse().getHeaders(); @Test public void writeHeadersWhenCacheHeadersThenWritesAllCacheControl() { this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(3); assertThat(this.headers.get(HttpHeaders.CACHE_CONTROL)) .containsOnly(CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE); assertThat(this.headers.get(HttpHeaders.EXPIRES)) .containsOnly(CacheControlServerHttpHeadersWriter.EXPIRES_VALUE); assertThat(this.headers.get(HttpHeaders.PRAGMA)).containsOnly(CacheControlServerHttpHeadersWriter.PRAGMA_VALUE); } @Test public void writeHeadersWhenCacheControlThenNoCacheControlHeaders() { String cacheControl = "max-age=1234"; this.headers.set(HttpHeaders.CACHE_CONTROL, cacheControl); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(cacheControl); } @Test public void writeHeadersWhenPragmaThenNoCacheControlHeaders() { String pragma = "1"; this.headers.set(HttpHeaders.PRAGMA, pragma); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(HttpHeaders.PRAGMA)).containsOnly(pragma); } @Test public void writeHeadersWhenExpiresThenNoCacheControlHeaders() { String expires = "1"; this.headers.set(HttpHeaders.EXPIRES, expires); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(HttpHeaders.EXPIRES)).containsOnly(expires); } @Test // gh-5534 public void writeHeadersWhenNotModifiedThenNoCacheControlHeaders() { this.exchange.getResponse().setStatusCode(HttpStatus.NOT_MODIFIED); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).isEmpty(); } }
3,146
34.761364
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/HttpHeaderWriterWebFilterTests.java
/* * Copyright 2002-2017 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.header; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.security.test.web.reactive.server.WebTestClientBuilder; import org.springframework.security.test.web.reactive.server.WebTestHandler; import org.springframework.security.test.web.reactive.server.WebTestHandler.WebHandlerResult; import org.springframework.test.web.reactive.server.WebTestClient; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class HttpHeaderWriterWebFilterTests { @Mock ServerHttpHeadersWriter writer; HttpHeaderWriterWebFilter filter; @BeforeEach public void setup() { given(this.writer.writeHttpHeaders(any())).willReturn(Mono.empty()); this.filter = new HttpHeaderWriterWebFilter(this.writer); } @Test public void filterWhenCompleteThenWritten() { WebTestClient rest = WebTestClientBuilder.bindToWebFilters(this.filter).build(); rest.get().uri("/foo").exchange(); verify(this.writer).writeHttpHeaders(any()); } @Test public void filterWhenNotCompleteThenNotWritten() { WebTestHandler handler = WebTestHandler.bindToWebFilters(this.filter); WebHandlerResult result = handler.exchange(MockServerHttpRequest.get("/foo")); verify(this.writer, never()).writeHttpHeaders(any()); result.getExchange().getResponse().setComplete().block(); verify(this.writer).writeHttpHeaders(any()); } }
2,476
33.402778
93
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/ContentTypeOptionsServerHttpHeadersWriterTests.java
/* * Copyright 2002-2023 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.header; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ContentTypeOptionsServerHttpHeadersWriter} * * @author Marcus da Coregio */ class ContentTypeOptionsServerHttpHeadersWriterTests { ContentTypeOptionsServerHttpHeadersWriter writer = new ContentTypeOptionsServerHttpHeadersWriter(); ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); HttpHeaders headers = this.exchange.getResponse().getHeaders(); @Test void writeHeadersWhenNoHeadersThenWriteHeaders() { this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)) .containsOnly(ContentTypeOptionsServerHttpHeadersWriter.NOSNIFF); } @Test void writeHeadersWhenHeaderWrittenThenDoesNotOverride() { String headerValue = "value"; this.headers.set(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)) .containsOnly(headerValue); } @Test void constantsMatchExpectedHeaderAndValue() { assertThat(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS).isEqualTo("X-Content-Type-Options"); assertThat(ContentTypeOptionsServerHttpHeadersWriter.NOSNIFF).isEqualTo("nosniff"); } }
2,420
35.681818
110
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/XXssProtectionServerHttpHeadersWriterTests.java
/* * Copyright 2002-2022 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.header; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * @since 5.0 */ public class XXssProtectionServerHttpHeadersWriterTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); HttpHeaders headers = this.exchange.getResponse().getHeaders(); XXssProtectionServerHttpHeadersWriter writer = new XXssProtectionServerHttpHeadersWriter(); @Test void setHeaderValueNullThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setHeaderValue(null)) .withMessage("headerValue cannot be null"); } @Test public void writeHeadersWhenNoHeadersThenWriteHeaders() { this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("0"); } @Test public void writeHeadersWhenHeaderWrittenThenDoesNotOverrride() { String headerValue = "value"; this.headers.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, headerValue); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly(headerValue); } @Test void writeHeadersWhenDisabledThenWriteHeaders() { this.writer.setHeaderValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.DISABLED); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("0"); } @Test void writeHeadersWhenEnabledThenWriteHeaders() { this.writer.setHeaderValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.ENABLED); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("1"); } @Test void writeHeadersWhenEnabledModeBlockThenWriteHeaders() { this.writer.setHeaderValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.ENABLED_MODE_BLOCK); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)) .containsOnly("1 ; mode=block"); } }
3,404
37.258427
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/StaticServerHttpHeadersWriterTests.java
/* * Copyright 2002-2021 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.header; import java.util.Locale; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @since 5.0 */ public class StaticServerHttpHeadersWriterTests { StaticServerHttpHeadersWriter writer = StaticServerHttpHeadersWriter.builder() .header(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, ContentTypeOptionsServerHttpHeadersWriter.NOSNIFF) .build(); ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); HttpHeaders headers = this.exchange.getResponse().getHeaders(); @Test public void writeHeadersWhenSingleHeaderThenWritesHeader() { this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)) .containsOnly(ContentTypeOptionsServerHttpHeadersWriter.NOSNIFF); } @Test public void writeHeadersWhenSingleHeaderAndHeaderWrittenThenSuccess() { String headerValue = "other"; this.headers.set(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)) .containsOnly(headerValue); } // gh-10557 @Test public void writeHeadersWhenHeaderWrittenWithDifferentCaseThenDoesNotWriteHeaders() { String headerName = HttpHeaders.CACHE_CONTROL.toLowerCase(Locale.ROOT); String headerValue = "max-age=120"; this.headers.set(headerName, headerValue); // Note: This test inverts which collection uses case sensitive headers, // due to the fact that gh-10557 reports NettyHeadersAdapter as the // response headers implementation, which is not accessible here. HttpHeaders caseSensitiveHeaders = new HttpHeaders(new LinkedMultiValueMap<>()); caseSensitiveHeaders.set(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE); caseSensitiveHeaders.set(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE); caseSensitiveHeaders.set(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE); this.writer = new StaticServerHttpHeadersWriter(caseSensitiveHeaders); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers.get(headerName)).containsOnly(headerValue); } @Test public void writeHeadersWhenMultiHeaderThenWritesAllHeaders() { this.writer = StaticServerHttpHeadersWriter.builder() .header(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE) .header(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE) .header(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE).build(); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers.get(HttpHeaders.CACHE_CONTROL)) .containsOnly(CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE); assertThat(this.headers.get(HttpHeaders.PRAGMA)).containsOnly(CacheControlServerHttpHeadersWriter.PRAGMA_VALUE); assertThat(this.headers.get(HttpHeaders.EXPIRES)) .containsOnly(CacheControlServerHttpHeadersWriter.EXPIRES_VALUE); } @Test public void writeHeadersWhenMultiHeaderAndSingleWrittenThenNoHeadersOverridden() { String headerValue = "other"; this.headers.set(HttpHeaders.CACHE_CONTROL, headerValue); this.writer = StaticServerHttpHeadersWriter.builder() .header(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE) .header(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE) .header(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE).build(); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(headerValue); } }
4,819
43.62963
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/ClearSiteDataServerHttpHeadersWriterTests.java
/* * Copyright 2002-2019 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.header; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.assertj.core.api.AbstractAssert; import org.junit.jupiter.api.Test; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.web.server.header.ClearSiteDataServerHttpHeadersWriter.Directive; import org.springframework.util.CollectionUtils; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author MD Sayem Ahmed * @since 5.2 */ public class ClearSiteDataServerHttpHeadersWriterTests { @Test public void constructorWhenMissingDirectivesThenThrowsException() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(ClearSiteDataServerHttpHeadersWriter::new); } @Test public void writeHttpHeadersWhenSecureConnectionThenHeaderWritten() { ClearSiteDataServerHttpHeadersWriter writer = new ClearSiteDataServerHttpHeadersWriter(Directive.ALL); ServerWebExchange secureExchange = MockServerWebExchange .from(MockServerHttpRequest.get("https://localhost").build()); writer.writeHttpHeaders(secureExchange); assertThat(secureExchange.getResponse()).hasClearSiteDataHeaderDirectives(Directive.ALL); } @Test public void writeHttpHeadersWhenInsecureConnectionThenHeaderNotWritten() { ClearSiteDataServerHttpHeadersWriter writer = new ClearSiteDataServerHttpHeadersWriter(Directive.ALL); ServerWebExchange insecureExchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); writer.writeHttpHeaders(insecureExchange); assertThat(insecureExchange.getResponse()).doesNotHaveClearSiteDataHeaderSet(); } @Test public void writeHttpHeadersWhenMultipleDirectivesSpecifiedThenHeaderContainsAll() { ClearSiteDataServerHttpHeadersWriter writer = new ClearSiteDataServerHttpHeadersWriter(Directive.CACHE, Directive.COOKIES); ServerWebExchange secureExchange = MockServerWebExchange .from(MockServerHttpRequest.get("https://localhost").build()); writer.writeHttpHeaders(secureExchange); assertThat(secureExchange.getResponse()).hasClearSiteDataHeaderDirectives(Directive.CACHE, Directive.COOKIES); } private static ClearSiteDataAssert assertThat(ServerHttpResponse response) { return new ClearSiteDataAssert(response); } private static class ClearSiteDataAssert extends AbstractAssert<ClearSiteDataAssert, ServerHttpResponse> { ClearSiteDataAssert(ServerHttpResponse response) { super(response, ClearSiteDataAssert.class); } void hasClearSiteDataHeaderDirectives(Directive... directives) { isNotNull(); List<String> header = getHeader(); String actualHeaderValue = String.join("", header); String expectedHeaderVale = Stream.of(directives).map(Directive::getHeaderValue) .collect(Collectors.joining(", ")); if (!actualHeaderValue.equals(expectedHeaderVale)) { failWithMessage("Expected to have %s as Clear-Site-Data header value but found %s", expectedHeaderVale, actualHeaderValue); } } void doesNotHaveClearSiteDataHeaderSet() { isNotNull(); List<String> header = getHeader(); if (!CollectionUtils.isEmpty(header)) { failWithMessage("Expected not to have Clear-Site-Data header set but found %s", String.join("", header)); } } List<String> getHeader() { return this.actual.getHeaders().get(ClearSiteDataServerHttpHeadersWriter.CLEAR_SITE_DATA_HEADER); } } }
4,279
37.558559
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/CompositeServerHttpHeadersWriterTests.java
/* * Copyright 2002-2017 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.header; import java.time.Duration; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class CompositeServerHttpHeadersWriterTests { @Mock ServerHttpHeadersWriter writer1; @Mock ServerHttpHeadersWriter writer2; CompositeServerHttpHeadersWriter writer; ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); @BeforeEach public void setup() { this.writer = new CompositeServerHttpHeadersWriter(Arrays.asList(this.writer1, this.writer2)); } @Test public void writeHttpHeadersWhenErrorNoErrorThenError() { given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException())); Mono<Void> result = this.writer.writeHttpHeaders(this.exchange); StepVerifier.create(result).expectError().verify(); verify(this.writer1).writeHttpHeaders(this.exchange); } @Test public void writeHttpHeadersWhenErrorErrorThenError() { given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException())); Mono<Void> result = this.writer.writeHttpHeaders(this.exchange); StepVerifier.create(result).expectError().verify(); verify(this.writer1).writeHttpHeaders(this.exchange); } @Test public void writeHttpHeadersWhenNoErrorThenNoError() { given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.empty()); given(this.writer2.writeHttpHeaders(this.exchange)).willReturn(Mono.empty()); Mono<Void> result = this.writer.writeHttpHeaders(this.exchange); StepVerifier.create(result).expectComplete().verify(); verify(this.writer1).writeHttpHeaders(this.exchange); verify(this.writer2).writeHttpHeaders(this.exchange); } @Test public void writeHttpHeadersSequential() throws Exception { AtomicBoolean slowDone = new AtomicBoolean(); CountDownLatch latch = new CountDownLatch(1); ServerHttpHeadersWriter slow = (exchange) -> Mono.delay(Duration.ofMillis(100)) .doOnSuccess((__) -> slowDone.set(true)).then(); ServerHttpHeadersWriter second = (exchange) -> Mono.fromRunnable(() -> { latch.countDown(); assertThat(slowDone.get()).describedAs("ServerLogoutHandler should be executed sequentially").isTrue(); }); CompositeServerHttpHeadersWriter writer = new CompositeServerHttpHeadersWriter(slow, second); writer.writeHttpHeaders(this.exchange).block(); assertThat(latch.await(3, TimeUnit.SECONDS)).isTrue(); } }
3,857
35.742857
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/ContentSecurityPolicyServerHttpHeadersWriterTests.java
/* * Copyright 2002-2018 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.header; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ContentSecurityPolicyServerHttpHeadersWriter}. * * @author Vedran Pavic */ public class ContentSecurityPolicyServerHttpHeadersWriterTests { private static final String DEFAULT_POLICY_DIRECTIVES = "default-src 'self'"; private ServerWebExchange exchange; private ContentSecurityPolicyServerHttpHeadersWriter writer; @BeforeEach public void setup() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); this.writer = new ContentSecurityPolicyServerHttpHeadersWriter(); } @Test public void writeHeadersWhenUsingDefaultsThenDoesNotWrite() { this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).isEmpty(); } @Test public void writeHeadersWhenUsingPolicyThenWritesPolicy() { this.writer.setPolicyDirectives(DEFAULT_POLICY_DIRECTIVES); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY)) .containsOnly(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersWhenReportPolicyThenWritesReportPolicy() { this.writer.setPolicyDirectives(DEFAULT_POLICY_DIRECTIVES); this.writer.setReportOnly(true); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY_REPORT_ONLY)) .containsOnly(DEFAULT_POLICY_DIRECTIVES); } @Test public void writeHeadersWhenOnlyReportOnlySetThenDoesNotWrite() { this.writer.setReportOnly(true); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).isEmpty(); } @Test public void writeHeadersWhenAlreadyWrittenThenWritesHeader() { String headerValue = "default-src https: 'self'"; this.exchange.getResponse().getHeaders() .set(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, headerValue); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY)) .containsOnly(headerValue); } }
3,515
35.247423
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/StrictTransportSecurityServerHttpHeadersWriterTests.java
/* * Copyright 2002-2017 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.header; import java.time.Duration; import java.util.Arrays; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch * @since 5.0 */ public class StrictTransportSecurityServerHttpHeadersWriterTests { StrictTransportSecurityServerHttpHeadersWriter hsts = new StrictTransportSecurityServerHttpHeadersWriter(); ServerWebExchange exchange; @Test public void writeHttpHeadersWhenHttpsThenWrites() { this.exchange = exchange(MockServerHttpRequest.get("https://example.com/")); this.hsts.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers).containsEntry(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY, Arrays.asList("max-age=31536000 ; includeSubDomains")); } @Test public void writeHttpHeadersWhenCustomMaxAgeThenWrites() { Duration maxAge = Duration.ofDays(1); this.hsts.setMaxAge(maxAge); this.exchange = exchange(MockServerHttpRequest.get("https://example.com/")); this.hsts.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers).containsEntry(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY, Arrays.asList("max-age=" + maxAge.getSeconds() + " ; includeSubDomains")); } @Test public void writeHttpHeadersWhenCustomIncludeSubDomainsThenWrites() { this.hsts.setIncludeSubDomains(false); this.exchange = exchange(MockServerHttpRequest.get("https://example.com/")); this.hsts.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers).containsEntry(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY, Arrays.asList("max-age=31536000")); } @Test public void writeHttpHeadersWhenNullSchemeThenNoHeaders() { this.exchange = exchange(MockServerHttpRequest.get("/")); this.hsts.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).isEmpty(); } @Test public void writeHttpHeadersWhenHttpThenNoHeaders() { this.exchange = exchange(MockServerHttpRequest.get("http://localhost/")); this.hsts.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).isEmpty(); } private static MockServerWebExchange exchange(MockServerHttpRequest.BaseBuilder<?> request) { return MockServerWebExchange.from(request.build()); } }
3,551
36.389474
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/XContentTypeOptionsServerHttpHeadersWriterTests.java
/* * Copyright 2002-2023 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.header; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link XContentTypeOptionsServerHttpHeadersWriter} * * @author Rob Winch * @since 5.0 */ public class XContentTypeOptionsServerHttpHeadersWriterTests { XContentTypeOptionsServerHttpHeadersWriter writer = new XContentTypeOptionsServerHttpHeadersWriter(); ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); HttpHeaders headers = this.exchange.getResponse().getHeaders(); @Test public void writeHeadersWhenNoHeadersThenWriteHeadersForXContentTypeOptionsServerHttpHeadersWriter() { this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)) .containsOnly(XContentTypeOptionsServerHttpHeadersWriter.NOSNIFF); } @Test public void writeHeadersWhenHeaderWrittenThenDoesNotOverrideForXContentTypeOptionsServerHttpHeadersWriter() { String headerValue = "value"; this.headers.set(XContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)) .containsOnly(headerValue); } @Test public void constantsMatchExpectedHeaderAndValueForXContentTypeOptionsServerHttpHeadersWriter() { assertThat(XContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS).isEqualTo("X-Content-Type-Options"); assertThat(XContentTypeOptionsServerHttpHeadersWriter.NOSNIFF).isEqualTo("nosniff"); } }
2,599
37.80597
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/ServerWebExchangeDelegatingServerHttpHeadersWriterTests.java
/* * Copyright 2002-2022 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.header; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; 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.ServerWebExchangeMatcherEntry; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * @author David Herberth */ @ExtendWith(MockitoExtension.class) public class ServerWebExchangeDelegatingServerHttpHeadersWriterTests { @Mock private ServerWebExchangeMatcher matcher; @Mock private ServerHttpHeadersWriter delegate; private ServerWebExchange exchange; private ServerWebExchangeDelegatingServerHttpHeadersWriter headerWriter; @BeforeEach public void setup() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); this.headerWriter = new ServerWebExchangeDelegatingServerHttpHeadersWriter(this.matcher, this.delegate); } @Test public void constructorWhenNullWebExchangeMatcherThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ServerWebExchangeDelegatingServerHttpHeadersWriter(null, this.delegate)) .withMessage("webExchangeMatcher cannot be null"); } @Test public void constructorWhenNullWebExchangeMatcherEntryThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ServerWebExchangeDelegatingServerHttpHeadersWriter(null)) .withMessage("headersWriter cannot be null"); } @Test public void constructorWhenNullDelegateHeadersWriterThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ServerWebExchangeDelegatingServerHttpHeadersWriter(this.matcher, null)) .withMessage("delegateHeadersWriter cannot be null"); } @Test public void constructorWhenEntryWithNullMatcherThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ServerWebExchangeDelegatingServerHttpHeadersWriter( new ServerWebExchangeMatcherEntry<>(null, this.delegate))) .withMessage("webExchangeMatcher cannot be null"); } @Test public void constructorWhenEntryWithNullEntryThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> new ServerWebExchangeDelegatingServerHttpHeadersWriter( new ServerWebExchangeMatcherEntry<>(this.matcher, null))) .withMessage("delegateHeadersWriter cannot be null"); } @Test public void writeHeadersWhenMatchThenDelegateWriteHttpHeaders() { given(this.matcher.matches(this.exchange)) .willReturn(ServerWebExchangeMatcher.MatchResult.match(Collections.emptyMap())); given(this.delegate.writeHttpHeaders(this.exchange)).willReturn(Mono.empty()); this.headerWriter.writeHttpHeaders(this.exchange).block(); verify(this.delegate).writeHttpHeaders(this.exchange); } @Test public void writeHeadersWhenNoMatchThenDelegateNotCalled() { given(this.matcher.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); this.headerWriter.writeHttpHeaders(this.exchange).block(); verify(this.matcher).matches(this.exchange); verify(this.delegate, times(0)).writeHttpHeaders(this.exchange); } }
4,317
36.224138
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/CrossOriginResourcePolicyServerHttpHeadersWriterTests.java
/* * Copyright 2002-2021 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.header; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; class CrossOriginResourcePolicyServerHttpHeadersWriterTests { private ServerWebExchange exchange; private CrossOriginResourcePolicyServerHttpHeadersWriter writer; @BeforeEach void setup() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); this.writer = new CrossOriginResourcePolicyServerHttpHeadersWriter(); } @Test void setResourcePolicyWhenNullThenThrowsIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null)) .withMessage("resourcePolicy cannot be null"); } @Test void writeHeadersWhenNoValuesThenDoesNotWriteHeaders() { this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).isEmpty(); } @Test void writeHeadersWhenResponseHeaderExistsThenDontOverride() { this.exchange.getResponse().getHeaders().add(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY, "same-origin"); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY)) .containsOnly("same-origin"); } @Test void writeHeadersWhenSetHeaderValuesThenWrites() { this.writer.setPolicy(CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY)) .containsOnly("same-origin"); } }
2,848
36
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/header/ReferrerPolicyServerHttpHeadersWriterTests.java
/* * Copyright 2002-2018 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.header; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ReferrerPolicyServerHttpHeadersWriter}. * * @author Vedran Pavic */ public class ReferrerPolicyServerHttpHeadersWriterTests { private ServerWebExchange exchange; private ReferrerPolicyServerHttpHeadersWriter writer; @BeforeEach public void setup() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); this.writer = new ReferrerPolicyServerHttpHeadersWriter(); } @Test public void writeHeadersWhenUsingDefaultsThenDoesNotWrite() { this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY)) .containsOnly(ReferrerPolicy.NO_REFERRER.getPolicy()); } @Test public void writeHeadersWhenUsingPolicyThenWritesPolicy() { this.writer.setPolicy(ReferrerPolicy.SAME_ORIGIN); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY)) .containsOnly(ReferrerPolicy.SAME_ORIGIN.getPolicy()); } @Test public void writeHeadersWhenAlreadyWrittenThenWritesHeader() { String headerValue = ReferrerPolicy.SAME_ORIGIN.getPolicy(); this.exchange.getResponse().getHeaders().set(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY, headerValue); this.writer.writeHttpHeaders(this.exchange); HttpHeaders headers = this.exchange.getResponse().getHeaders(); assertThat(headers).hasSize(1); assertThat(headers.get(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY)).containsOnly(headerValue); } }
2,884
35.987179
107
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationSuccessHandlerTests.java
/* * Copyright 2002-2017 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.authentication; import java.net.URI; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.test.publisher.PublisherProbe; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.ServerRedirectStrategy; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class RedirectServerAuthenticationSuccessHandlerTests { @Mock private ServerWebExchange exchange; @Mock private WebFilterChain chain; @Mock private ServerRedirectStrategy redirectStrategy; @Mock private Authentication authentication; private URI location = URI.create("/"); private RedirectServerAuthenticationSuccessHandler handler = new RedirectServerAuthenticationSuccessHandler(); @Test public void constructorStringWhenNullLocationThenException() { assertThatIllegalArgumentException().isThrownBy(() -> new RedirectServerAuthenticationEntryPoint(null)); } @Test public void successWhenNoSubscribersThenNoActions() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.handler.onAuthenticationSuccess(new WebFilterExchange(this.exchange, this.chain), this.authentication); assertThat(this.exchange.getResponse().getHeaders().getLocation()).isNull(); assertThat(this.exchange.getSession().block().isStarted()).isFalse(); } @Test public void successWhenSubscribeThenStatusAndLocationSet() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.handler.onAuthenticationSuccess(new WebFilterExchange(this.exchange, this.chain), this.authentication) .block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND); assertThat(this.exchange.getResponse().getHeaders().getLocation()).isEqualTo(this.location); } @Test public void successWhenCustomLocationThenCustomLocationUsed() { PublisherProbe<Void> redirectResult = PublisherProbe.empty(); given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono()); this.handler.setRedirectStrategy(this.redirectStrategy); this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.handler.onAuthenticationSuccess(new WebFilterExchange(this.exchange, this.chain), this.authentication) .block(); redirectResult.assertWasSubscribed(); verify(this.redirectStrategy).sendRedirect(any(), eq(this.location)); } @Test public void setRedirectStrategyWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setRedirectStrategy(null)); } @Test public void setLocationWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setLocation(null)); } }
4,214
36.972973
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/ServerWebExchangeDelegatingReactiveAuthenticationManagerResolverTests.java
/* * Copyright 2002-2022 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.authentication; import org.junit.jupiter.api.Test; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.util.matcher.PathPatternParserServerWebExchangeMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; /** * Tests for {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver} * * @author Josh Cummings */ public class ServerWebExchangeDelegatingReactiveAuthenticationManagerResolverTests { private ReactiveAuthenticationManager one = mock(ReactiveAuthenticationManager.class); private ReactiveAuthenticationManager two = mock(ReactiveAuthenticationManager.class); @Test public void resolveWhenMatchesThenReturnsReactiveAuthenticationManager() { ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver resolver = ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver .builder().add(new PathPatternParserServerWebExchangeMatcher("/one/**"), this.one) .add(new PathPatternParserServerWebExchangeMatcher("/two/**"), this.two).build(); MockServerHttpRequest request = MockServerHttpRequest.get("/one/location").build(); assertThat(resolver.resolve(MockServerWebExchange.from(request)).block()).isEqualTo(this.one); } @Test public void resolveWhenDoesNotMatchThenReturnsDefaultReactiveAuthenticationManager() { ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver resolver = ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver .builder().add(new PathPatternParserServerWebExchangeMatcher("/one/**"), this.one) .add(new PathPatternParserServerWebExchangeMatcher("/two/**"), this.two).build(); MockServerHttpRequest request = MockServerHttpRequest.get("/wrong/location").build(); ReactiveAuthenticationManager authenticationManager = resolver.resolve(MockServerWebExchange.from(request)) .block(); Authentication authentication = new TestingAuthenticationToken("principal", "creds"); assertThatExceptionOfType(AuthenticationServiceException.class) .isThrownBy(() -> authenticationManager.authenticate(authentication).block()); } }
3,284
45.928571
142
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationFailureHandlerTests.java
/* * Copyright 2002-2017 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.authentication; import java.util.Collections; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.publisher.PublisherProbe; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.ServerRedirectStrategy; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.web.server.handler.DefaultWebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class RedirectServerAuthenticationFailureHandlerTests { private WebFilterExchange exchange; @Mock private ServerRedirectStrategy redirectStrategy; private String location = "/login"; private RedirectServerAuthenticationFailureHandler handler = new RedirectServerAuthenticationFailureHandler( this.location); private AuthenticationException exception = new AuthenticationCredentialsNotFoundException( "Authentication Required"); @Test public void constructorStringWhenNullLocationThenException() { assertThatIllegalArgumentException().isThrownBy(() -> new RedirectServerAuthenticationEntryPoint(null)); } @Test public void commenceWhenNoSubscribersThenNoActions() { this.exchange = createExchange(); this.handler.onAuthenticationFailure(this.exchange, this.exception); assertThat(this.exchange.getExchange().getResponse().getHeaders().getLocation()).isNull(); assertThat(this.exchange.getExchange().getSession().block().isStarted()).isFalse(); } @Test public void commenceWhenSubscribeThenStatusAndLocationSet() { this.exchange = createExchange(); this.handler.onAuthenticationFailure(this.exchange, this.exception).block(); assertThat(this.exchange.getExchange().getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND); assertThat(this.exchange.getExchange().getResponse().getHeaders().getLocation()).hasPath(this.location); } @Test public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() { PublisherProbe<Void> redirectResult = PublisherProbe.empty(); given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono()); this.handler.setRedirectStrategy(this.redirectStrategy); this.exchange = createExchange(); this.handler.onAuthenticationFailure(this.exchange, this.exception).block(); redirectResult.assertWasSubscribed(); } @Test public void setRedirectStrategyWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setRedirectStrategy(null)); } private WebFilterExchange createExchange() { return new WebFilterExchange(MockServerWebExchange.from(MockServerHttpRequest.get("/").build()), new DefaultWebFilterChain((e) -> Mono.empty(), Collections.emptyList())); } }
4,086
38.298077
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java
/* * Copyright 2002-2022 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.authentication; import java.security.Principal; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.util.context.Context; import org.springframework.http.HttpMethod; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authentication.AccountStatusUserDetailsChecker; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.userdetails.ReactiveUserDetailsService; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.context.ServerSecurityContextRepository; import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * @author Artur Otrzonsek */ @ExtendWith(MockitoExtension.class) public class SwitchUserWebFilterTests { private SwitchUserWebFilter switchUserWebFilter; @Mock private ReactiveUserDetailsService userDetailsService; @Mock ServerAuthenticationSuccessHandler successHandler; @Mock private ServerAuthenticationFailureHandler failureHandler; @Mock private ServerSecurityContextRepository serverSecurityContextRepository; @BeforeEach public void setUp() { this.switchUserWebFilter = new SwitchUserWebFilter(this.userDetailsService, this.successHandler, this.failureHandler); this.switchUserWebFilter.setSecurityContextRepository(this.serverSecurityContextRepository); } @Test public void switchUserWhenRequestNotMatchThenDoesNothing() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/not/existing")); WebFilterChain chain = mock(WebFilterChain.class); given(chain.filter(exchange)).willReturn(Mono.empty()); this.switchUserWebFilter.filter(exchange, chain).block(); verifyNoInteractions(this.userDetailsService); verifyNoInteractions(this.successHandler); verifyNoInteractions(this.failureHandler); verifyNoInteractions(this.serverSecurityContextRepository); verify(chain).filter(exchange); } @Test public void switchUser() { final String targetUsername = "TEST_USERNAME"; final UserDetails switchUserDetails = switchUserDetails(targetUsername, true); final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername)); final WebFilterChain chain = mock(WebFilterChain.class); final Authentication originalAuthentication = UsernamePasswordAuthenticationToken.unauthenticated("principal", "credentials"); final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication); given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails)); given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))) .willReturn(Mono.empty()); given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))) .willReturn(Mono.empty()); this.switchUserWebFilter.filter(exchange, chain) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block(); verifyNoInteractions(chain); verify(this.userDetailsService).findByUsername(targetUsername); final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class); verify(this.serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture()); final SecurityContext savedSecurityContext = securityContextCaptor.getValue(); final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class); verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture()); final Authentication switchUserAuthentication = authenticationCaptor.getValue(); assertThat(switchUserAuthentication).isSameAs(savedSecurityContext.getAuthentication()); assertThat(switchUserAuthentication.getName()).isEqualTo(targetUsername); assertThat(switchUserAuthentication.getAuthorities()).anyMatch(SwitchUserGrantedAuthority.class::isInstance); assertThat(switchUserAuthentication.getAuthorities()) .anyMatch((a) -> a.getAuthority().contains(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR)); assertThat(switchUserAuthentication.getAuthorities().stream() .filter((a) -> a instanceof SwitchUserGrantedAuthority) .map((a) -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName)) .contains(originalAuthentication.getName()); } @Test public void switchUserWhenUserAlreadySwitchedThenExitSwitchAndSwitchAgain() { final Authentication originalAuthentication = UsernamePasswordAuthenticationToken .unauthenticated("origPrincipal", "origCredentials"); final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority( SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication); final Authentication switchUserAuthentication = UsernamePasswordAuthenticationToken .authenticated("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority)); final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication); final String targetUsername = "newSwitchPrincipal"; final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername)); final WebFilterChain chain = mock(WebFilterChain.class); given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))) .willReturn(Mono.empty()); given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))) .willReturn(Mono.empty()); given(this.userDetailsService.findByUsername(targetUsername)) .willReturn(Mono.just(switchUserDetails(targetUsername, true))); this.switchUserWebFilter.filter(exchange, chain) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block(); final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class); verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture()); final Authentication secondSwitchUserAuthentication = authenticationCaptor.getValue(); assertThat(secondSwitchUserAuthentication.getName()).isEqualTo(targetUsername); assertThat(secondSwitchUserAuthentication.getAuthorities().stream() .filter((a) -> a instanceof SwitchUserGrantedAuthority) .map((a) -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName).findFirst() .orElse(null)).isEqualTo(originalAuthentication.getName()); } @Test public void switchUserWhenUsernameIsMissingThenThrowException() { final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/login/impersonate")); final WebFilterChain chain = mock(WebFilterChain.class); final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class)); assertThatIllegalArgumentException().isThrownBy(() -> { Context securityContextHolder = ReactiveSecurityContextHolder .withSecurityContext(Mono.just(securityContext)); this.switchUserWebFilter.filter(exchange, chain).contextWrite(securityContextHolder).block(); }).withMessage("The userName can not be null."); verifyNoInteractions(chain); } @Test public void switchUserWhenExceptionThenCallFailureHandler() { final String targetUsername = "TEST_USERNAME"; final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername)); final WebFilterChain chain = mock(WebFilterChain.class); final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class)); final UserDetails switchUserDetails = switchUserDetails(targetUsername, false); given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails)); given(this.failureHandler.onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class))) .willReturn(Mono.empty()); this.switchUserWebFilter.filter(exchange, chain) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block(); verify(this.failureHandler).onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class)); verifyNoInteractions(chain); } @Test public void switchUserWhenFailureHandlerNotDefinedThenReturnError() { this.switchUserWebFilter = new SwitchUserWebFilter(this.userDetailsService, this.successHandler, null); final String targetUsername = "TEST_USERNAME"; final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername)); final WebFilterChain chain = mock(WebFilterChain.class); final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class)); final UserDetails switchUserDetails = switchUserDetails(targetUsername, false); given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails)); assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> { Context securityContextHolder = ReactiveSecurityContextHolder .withSecurityContext(Mono.just(securityContext)); this.switchUserWebFilter.filter(exchange, chain).contextWrite(securityContextHolder).block(); }); verifyNoInteractions(chain); } @Test public void exitSwitchThenReturnToOriginalAuthentication() { final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/logout/impersonate")); final Authentication originalAuthentication = UsernamePasswordAuthenticationToken .unauthenticated("origPrincipal", "origCredentials"); final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority( SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication); final Authentication switchUserAuthentication = UsernamePasswordAuthenticationToken .authenticated("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority)); final WebFilterChain chain = mock(WebFilterChain.class); final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication); given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))) .willReturn(Mono.empty()); given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))) .willReturn(Mono.empty()); this.switchUserWebFilter.filter(exchange, chain) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block(); final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class); verify(this.serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture()); final SecurityContext savedSecurityContext = securityContextCaptor.getValue(); final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class); verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture()); final Authentication originalAuthenticationValue = authenticationCaptor.getValue(); assertThat(savedSecurityContext.getAuthentication()).isSameAs(originalAuthentication); assertThat(originalAuthenticationValue).isSameAs(originalAuthentication); verifyNoInteractions(chain); } @Test public void exitSwitchWhenUserNotSwitchedThenThrowError() { final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/logout/impersonate")); final Authentication originalAuthentication = UsernamePasswordAuthenticationToken .unauthenticated("origPrincipal", "origCredentials"); final WebFilterChain chain = mock(WebFilterChain.class); final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> { Context securityContextHolder = ReactiveSecurityContextHolder .withSecurityContext(Mono.just(securityContext)); this.switchUserWebFilter.filter(exchange, chain).contextWrite(securityContextHolder).block(); }).withMessage("Could not find original Authentication object"); verifyNoInteractions(chain); } @Test public void exitSwitchWhenNoCurrentUserThenThrowError() { final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/logout/impersonate")); final WebFilterChain chain = mock(WebFilterChain.class); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) .isThrownBy(() -> this.switchUserWebFilter.filter(exchange, chain).block()) .withMessage("No current user associated with this request"); verifyNoInteractions(chain); } @Test public void constructorUserDetailsServiceRequired() { assertThatIllegalArgumentException() .isThrownBy(() -> this.switchUserWebFilter = new SwitchUserWebFilter(null, mock(ServerAuthenticationSuccessHandler.class), mock(ServerAuthenticationFailureHandler.class))) .withMessage("userDetailsService must be specified"); } @Test public void constructorServerAuthenticationSuccessHandlerRequired() { assertThatIllegalArgumentException() .isThrownBy( () -> this.switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class), null, mock(ServerAuthenticationFailureHandler.class))) .withMessage("successHandler must be specified"); } @Test public void constructorSuccessTargetUrlRequired() { assertThatIllegalArgumentException().isThrownBy( () -> this.switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class), null, "failure/target/url")) .withMessage("successTargetUrl must be specified"); } @Test public void constructorFirstDefaultValues() { this.switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class), mock(ServerAuthenticationSuccessHandler.class), mock(ServerAuthenticationFailureHandler.class)); final Object securityContextRepository = ReflectionTestUtils.getField(this.switchUserWebFilter, "securityContextRepository"); assertThat(securityContextRepository).isInstanceOf(WebSessionServerSecurityContextRepository.class); final Object userDetailsChecker = ReflectionTestUtils.getField(this.switchUserWebFilter, "userDetailsChecker"); assertThat(userDetailsChecker).isInstanceOf(AccountStatusUserDetailsChecker.class); } @Test public void constructorSecondDefaultValues() { this.switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class), "success/target/url", "failure/target/url"); final Object successHandler = ReflectionTestUtils.getField(this.switchUserWebFilter, "successHandler"); assertThat(successHandler).isInstanceOf(RedirectServerAuthenticationSuccessHandler.class); final Object failureHandler = ReflectionTestUtils.getField(this.switchUserWebFilter, "failureHandler"); assertThat(failureHandler).isInstanceOf(RedirectServerAuthenticationFailureHandler.class); final Object securityContextRepository = ReflectionTestUtils.getField(this.switchUserWebFilter, "securityContextRepository"); assertThat(securityContextRepository).isInstanceOf(WebSessionServerSecurityContextRepository.class); final Object userDetailsChecker = ReflectionTestUtils.getField(this.switchUserWebFilter, "userDetailsChecker"); assertThat(userDetailsChecker instanceof AccountStatusUserDetailsChecker).isTrue(); } @Test public void setSecurityContextRepositoryWhenNullThenThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.switchUserWebFilter.setSecurityContextRepository(null)) .withMessage("securityContextRepository cannot be null"); } @Test public void setSecurityContextRepositoryWhenDefinedThenChangeDefaultValue() { final Object oldSecurityContextRepository = ReflectionTestUtils.getField(this.switchUserWebFilter, "securityContextRepository"); assertThat(oldSecurityContextRepository).isSameAs(this.serverSecurityContextRepository); final ServerSecurityContextRepository newSecurityContextRepository = mock( ServerSecurityContextRepository.class); this.switchUserWebFilter.setSecurityContextRepository(newSecurityContextRepository); final Object currentSecurityContextRepository = ReflectionTestUtils.getField(this.switchUserWebFilter, "securityContextRepository"); assertThat(currentSecurityContextRepository).isSameAs(newSecurityContextRepository); } @Test public void setExitUserUrlWhenNullThenThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.switchUserWebFilter.setExitUserUrl(null)) .withMessage("exitUserUrl cannot be empty and must be a valid redirect URL"); } @Test public void setExitUserUrlWhenInvalidUrlThenThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.switchUserWebFilter.setExitUserUrl("wrongUrl")) .withMessage("exitUserUrl cannot be empty and must be a valid redirect URL"); } @Test public void setExitUserUrlWhenDefinedThenChangeDefaultValue() { final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/logout/impersonate")); final ServerWebExchangeMatcher oldExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils .getField(this.switchUserWebFilter, "exitUserMatcher"); assertThat(oldExitUserMatcher.matches(exchange).block().isMatch()).isTrue(); this.switchUserWebFilter.setExitUserUrl("/exit-url"); final MockServerWebExchange newExchange = MockServerWebExchange.from(MockServerHttpRequest.post("/exit-url")); final ServerWebExchangeMatcher newExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils .getField(this.switchUserWebFilter, "exitUserMatcher"); assertThat(newExitUserMatcher.matches(newExchange).block().isMatch()).isTrue(); } @Test public void setExitUserMatcherWhenNullThenThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.switchUserWebFilter.setExitUserMatcher(null)) .withMessage("exitUserMatcher cannot be null"); } @Test public void setExitUserMatcherWhenDefinedThenChangeDefaultValue() { final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/logout/impersonate")); final ServerWebExchangeMatcher oldExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils .getField(this.switchUserWebFilter, "exitUserMatcher"); assertThat(oldExitUserMatcher.matches(exchange).block().isMatch()).isTrue(); final ServerWebExchangeMatcher newExitUserMatcher = ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/exit-url"); this.switchUserWebFilter.setExitUserMatcher(newExitUserMatcher); final ServerWebExchangeMatcher currentExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils .getField(this.switchUserWebFilter, "exitUserMatcher"); assertThat(currentExitUserMatcher).isSameAs(newExitUserMatcher); } @Test public void setSwitchUserUrlWhenNullThenThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.switchUserWebFilter.setSwitchUserUrl(null)) .withMessage("switchUserUrl cannot be empty and must be a valid redirect URL"); } @Test public void setSwitchUserUrlWhenInvalidThenThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.switchUserWebFilter.setSwitchUserUrl("wrongUrl")) .withMessage("switchUserUrl cannot be empty and must be a valid redirect URL"); } @Test public void setSwitchUserUrlWhenDefinedThenChangeDefaultValue() { final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/login/impersonate")); final ServerWebExchangeMatcher oldSwitchUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils .getField(this.switchUserWebFilter, "switchUserMatcher"); assertThat(oldSwitchUserMatcher.matches(exchange).block().isMatch()).isTrue(); this.switchUserWebFilter.setSwitchUserUrl("/switch-url"); final MockServerWebExchange newExchange = MockServerWebExchange.from(MockServerHttpRequest.post("/switch-url")); final ServerWebExchangeMatcher newSwitchUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils .getField(this.switchUserWebFilter, "switchUserMatcher"); assertThat(newSwitchUserMatcher.matches(newExchange).block().isMatch()).isTrue(); } @Test public void setSwitchUserMatcherWhenNullThenThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.switchUserWebFilter.setSwitchUserMatcher(null)) .withMessage("switchUserMatcher cannot be null"); } @Test public void setSwitchUserMatcherWhenDefinedThenChangeDefaultValue() { final MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.post("/login/impersonate")); final ServerWebExchangeMatcher oldSwitchUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils .getField(this.switchUserWebFilter, "switchUserMatcher"); assertThat(oldSwitchUserMatcher.matches(exchange).block().isMatch()).isTrue(); final ServerWebExchangeMatcher newSwitchUserMatcher = ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/switch-url"); this.switchUserWebFilter.setSwitchUserMatcher(newSwitchUserMatcher); final ServerWebExchangeMatcher currentExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils .getField(this.switchUserWebFilter, "switchUserMatcher"); assertThat(currentExitUserMatcher).isSameAs(newSwitchUserMatcher); } private UserDetails switchUserDetails(String username, boolean enabled) { final SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_SWITCH_TEST"); return new User(username, "NA", enabled, true, true, true, Collections.singleton(authority)); } }
24,712
53.674779
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/ServerX509AuthenticationConverterTests.java
/* * Copyright 2002-2018 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.authentication; import java.security.cert.X509Certificate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.server.reactive.SslInfo; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor; import org.springframework.security.web.authentication.preauth.x509.X509TestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @ExtendWith(MockitoExtension.class) public class ServerX509AuthenticationConverterTests { @Mock private X509PrincipalExtractor principalExtractor; @InjectMocks private ServerX509AuthenticationConverter converter; private X509Certificate certificate; private MockServerHttpRequest.BaseBuilder<?> request; @BeforeEach public void setUp() throws Exception { this.request = MockServerHttpRequest.get("/"); this.certificate = X509TestUtils.buildTestCertificate(); } private void givenExtractPrincipalWillReturn() { given(this.principalExtractor.extractPrincipal(any())).willReturn("Luke Taylor"); } @Test public void shouldReturnNullForInvalidCertificate() { Authentication authentication = this.converter.convert(MockServerWebExchange.from(this.request.build())) .block(); assertThat(authentication).isNull(); } @Test public void shouldReturnAuthenticationForValidCertificate() { givenExtractPrincipalWillReturn(); this.request.sslInfo(new MockSslInfo(this.certificate)); Authentication authentication = this.converter.convert(MockServerWebExchange.from(this.request.build())) .block(); assertThat(authentication.getName()).isEqualTo("Luke Taylor"); assertThat(authentication.getCredentials()).isEqualTo(this.certificate); } class MockSslInfo implements SslInfo { private final X509Certificate[] peerCertificates; MockSslInfo(X509Certificate... peerCertificates) { this.peerCertificates = peerCertificates; } @Override public String getSessionId() { return "mock-session-id"; } @Override public X509Certificate[] getPeerCertificates() { return this.peerCertificates; } } }
3,209
31.1
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/ReactivePreAuthenticatedAuthenticationManagerTests.java
/* * Copyright 2002-2019 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.authentication; import java.util.Collections; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import org.springframework.security.authentication.AccountExpiredException; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.LockedException; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.ReactiveUserDetailsService; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Alexey Nesterov * @since 5.2 */ public class ReactivePreAuthenticatedAuthenticationManagerTests { private ReactiveUserDetailsService mockUserDetailsService = mock(ReactiveUserDetailsService.class); private ReactivePreAuthenticatedAuthenticationManager manager = new ReactivePreAuthenticatedAuthenticationManager( this.mockUserDetailsService); private final User validAccount = new User("valid", "", Collections.emptySet()); private final User nonExistingAccount = new User("non existing", "", Collections.emptySet()); private final User disabledAccount = new User("disabled", "", false, true, true, true, Collections.emptySet()); private final User expiredAccount = new User("expired", "", true, false, true, true, Collections.emptySet()); private final User accountWithExpiredCredentials = new User("credentials expired", "", true, true, false, true, Collections.emptySet()); private final User lockedAccount = new User("locked", "", true, true, true, false, Collections.emptySet()); @Test public void returnsAuthenticatedTokenForValidAccount() { given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.validAccount)); Authentication authentication = this.manager.authenticate(tokenForUser(this.validAccount.getUsername())) .block(); assertThat(authentication.isAuthenticated()).isEqualTo(true); } @Test public void returnsNullForNonExistingAccount() { given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.empty()); assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy( () -> this.manager.authenticate(tokenForUser(this.nonExistingAccount.getUsername())).block()); } @Test public void throwsExceptionForLockedAccount() { given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.lockedAccount)); assertThatExceptionOfType(LockedException.class) .isThrownBy(() -> this.manager.authenticate(tokenForUser(this.lockedAccount.getUsername())).block()); } @Test public void throwsExceptionForDisabledAccount() { given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.disabledAccount)); assertThatExceptionOfType(DisabledException.class) .isThrownBy(() -> this.manager.authenticate(tokenForUser(this.disabledAccount.getUsername())).block()); } @Test public void throwsExceptionForExpiredAccount() { given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.expiredAccount)); assertThatExceptionOfType(AccountExpiredException.class) .isThrownBy(() -> this.manager.authenticate(tokenForUser(this.expiredAccount.getUsername())).block()); } @Test public void throwsExceptionForAccountWithExpiredCredentials() { given(this.mockUserDetailsService.findByUsername(anyString())) .willReturn(Mono.just(this.accountWithExpiredCredentials)); assertThatExceptionOfType(CredentialsExpiredException.class).isThrownBy(() -> this.manager .authenticate(tokenForUser(this.accountWithExpiredCredentials.getUsername())).block()); } private Authentication tokenForUser(String username) { return new PreAuthenticatedAuthenticationToken(username, null); } }
4,955
42.858407
115
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationEntryPointTests.java
/* * Copyright 2002-2017 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.authentication; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.test.publisher.PublisherProbe; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.server.ServerRedirectStrategy; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class RedirectServerAuthenticationEntryPointTests { @Mock private ServerWebExchange exchange; @Mock private ServerRedirectStrategy redirectStrategy; private String location = "/login"; private RedirectServerAuthenticationEntryPoint entryPoint = new RedirectServerAuthenticationEntryPoint( this.location); private AuthenticationException exception = new AuthenticationCredentialsNotFoundException( "Authentication Required"); @Test public void constructorStringWhenNullLocationThenException() { assertThatIllegalArgumentException().isThrownBy(() -> new RedirectServerAuthenticationEntryPoint(null)); } @Test public void commenceWhenNoSubscribersThenNoActions() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.entryPoint.commence(this.exchange, this.exception); assertThat(this.exchange.getResponse().getHeaders().getLocation()).isNull(); assertThat(this.exchange.getSession().block().isStarted()).isFalse(); } @Test public void commenceWhenSubscribeThenStatusAndLocationSet() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.entryPoint.commence(this.exchange, this.exception).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND); assertThat(this.exchange.getResponse().getHeaders().getLocation()).hasPath(this.location); } @Test public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() { PublisherProbe<Void> redirectResult = PublisherProbe.empty(); given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono()); this.entryPoint.setRedirectStrategy(this.redirectStrategy); this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.entryPoint.commence(this.exchange, this.exception).block(); redirectResult.assertWasSubscribed(); } @Test public void setRedirectStrategyWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.entryPoint.setRedirectStrategy(null)); } }
3,776
38.34375
106
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/ServerHttpBasicAuthenticationConverterTests.java
/* * Copyright 2002-2022 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.authentication; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * @since 5.0 */ public class ServerHttpBasicAuthenticationConverterTests { ServerHttpBasicAuthenticationConverter converter = new ServerHttpBasicAuthenticationConverter(); MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/"); @Test public void setCredentialsCharsetWhenNullThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setCredentialsCharset(null)) .withMessage("credentialsCharset cannot be null"); } @Test public void applyWhenNoAuthorizationHeaderThenEmpty() { Mono<Authentication> result = apply(this.request); assertThat(result.block()).isNull(); } @Test public void applyWhenEmptyAuthorizationHeaderThenEmpty() { Mono<Authentication> result = apply(this.request.header(HttpHeaders.AUTHORIZATION, "")); assertThat(result.block()).isNull(); } @Test public void applyWhenOnlyBasicAuthorizationHeaderThenEmpty() { Mono<Authentication> result = apply(this.request.header(HttpHeaders.AUTHORIZATION, "Basic ")); assertThat(result.block()).isNull(); } @Test public void applyWhenNotBase64ThenEmpty() { Mono<Authentication> result = apply(this.request.header(HttpHeaders.AUTHORIZATION, "Basic z")); assertThat(result.block()).isNull(); } @Test public void applyWhenNoColonThenEmpty() { Mono<Authentication> result = apply(this.request.header(HttpHeaders.AUTHORIZATION, "Basic dXNlcg==")); assertThat(result.block()).isNull(); } @Test public void applyWhenUserPasswordThenAuthentication() { Mono<Authentication> result = apply( this.request.header(HttpHeaders.AUTHORIZATION, "Basic dXNlcjpwYXNzd29yZA==")); UsernamePasswordAuthenticationToken authentication = result.cast(UsernamePasswordAuthenticationToken.class) .block(); assertThat(authentication.getPrincipal()).isEqualTo("user"); assertThat(authentication.getCredentials()).isEqualTo("password"); } @Test public void applyWhenUserPasswordHasColonThenAuthentication() { Mono<Authentication> result = apply( this.request.header(HttpHeaders.AUTHORIZATION, "Basic dXNlcjpwYXNzOndvcmQ=")); UsernamePasswordAuthenticationToken authentication = result.cast(UsernamePasswordAuthenticationToken.class) .block(); assertThat(authentication.getPrincipal()).isEqualTo("user"); assertThat(authentication.getCredentials()).isEqualTo("pass:word"); } @Test public void applyWhenLowercaseSchemeThenAuthentication() { Mono<Authentication> result = apply( this.request.header(HttpHeaders.AUTHORIZATION, "basic dXNlcjpwYXNzd29yZA==")); UsernamePasswordAuthenticationToken authentication = result.cast(UsernamePasswordAuthenticationToken.class) .block(); assertThat(authentication.getPrincipal()).isEqualTo("user"); assertThat(authentication.getCredentials()).isEqualTo("password"); } @Test public void applyWhenWrongSchemeThenEmpty() { Mono<Authentication> result = apply( this.request.header(HttpHeaders.AUTHORIZATION, "token dXNlcjpwYXNzd29yZA==")); assertThat(result.block()).isNull(); } @Test public void applyWhenNonAsciiThenAuthentication() { Mono<Authentication> result = apply( this.request.header(HttpHeaders.AUTHORIZATION, "Basic w7xzZXI6cGFzc3fDtnJk")); UsernamePasswordAuthenticationToken authentication = result.cast(UsernamePasswordAuthenticationToken.class) .block(); assertThat(authentication.getPrincipal()).isEqualTo("üser"); assertThat(authentication.getCredentials()).isEqualTo("passwörd"); } @Test public void applyWhenIsoOnlyAsciiThenAuthentication() { this.converter.setCredentialsCharset(StandardCharsets.ISO_8859_1); Mono<Authentication> result = apply( this.request.header(HttpHeaders.AUTHORIZATION, "Basic dXNlcjpwYXNzd29yZA==")); UsernamePasswordAuthenticationToken authentication = result.cast(UsernamePasswordAuthenticationToken.class) .block(); assertThat(authentication.getPrincipal()).isEqualTo("user"); assertThat(authentication.getCredentials()).isEqualTo("password"); } @Test public void applyWhenIsoNonAsciiThenAuthentication() { this.converter.setCredentialsCharset(StandardCharsets.ISO_8859_1); Mono<Authentication> result = apply( this.request.header(HttpHeaders.AUTHORIZATION, "Basic /HNlcjpwYXNzd/ZyZA==")); UsernamePasswordAuthenticationToken authentication = result.cast(UsernamePasswordAuthenticationToken.class) .block(); assertThat(authentication.getPrincipal()).isEqualTo("üser"); assertThat(authentication.getCredentials()).isEqualTo("passwörd"); } private Mono<Authentication> apply(MockServerHttpRequest.BaseBuilder<?> request) { return this.converter.convert(MockServerWebExchange.from(this.request.build())); } }
5,983
38.111111
109
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/AnonymousAuthenticationWebFilterTests.java
/* * Copyright 2002-2018 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.authentication; import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.test.web.reactive.server.WebTestClientBuilder; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ServerWebExchange; /** * @author Ankur Pathak * @since 5.2.0 */ @ExtendWith(MockitoExtension.class) public class AnonymousAuthenticationWebFilterTests { @Test public void anonymousAuthenticationFilterWorking() { WebTestClient client = WebTestClientBuilder.bindToControllerAndWebFilters(HttpMeController.class, new AnonymousAuthenticationWebFilter(UUID.randomUUID().toString())).build(); client.get().uri("/me").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("anonymousUser"); } @RestController @RequestMapping("/me") public static class HttpMeController { @GetMapping public Mono<String> me(ServerWebExchange exchange) { return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication) .map(Authentication::getPrincipal).ofType(String.class); } } }
2,295
35.444444
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/ServerFormLoginAuthenticationConverterTests.java
/* * Copyright 2002-2018 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.authentication; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class ServerFormLoginAuthenticationConverterTests { @Mock private ServerWebExchange exchange; private MultiValueMap<String, String> data = new LinkedMultiValueMap<>(); private ServerFormLoginAuthenticationConverter converter = new ServerFormLoginAuthenticationConverter(); public void setupMocks() { given(this.exchange.getFormData()).willReturn(Mono.just(this.data)); } @Test public void applyWhenUsernameAndPasswordThenCreatesTokenSuccess() { setupMocks(); String username = "username"; String password = "password"; this.data.add("username", username); this.data.add("password", password); Authentication authentication = this.converter.convert(this.exchange).block(); assertThat(authentication.getName()).isEqualTo(username); assertThat(authentication.getCredentials()).isEqualTo(password); assertThat(authentication.getAuthorities()).isEmpty(); } @Test public void applyWhenCustomParametersAndUsernameAndPasswordThenCreatesTokenSuccess() { setupMocks(); String usernameParameter = "j_username"; String passwordParameter = "j_password"; String username = "username"; String password = "password"; this.converter.setUsernameParameter(usernameParameter); this.converter.setPasswordParameter(passwordParameter); this.data.add(usernameParameter, username); this.data.add(passwordParameter, password); Authentication authentication = this.converter.convert(this.exchange).block(); assertThat(authentication.getName()).isEqualTo(username); assertThat(authentication.getCredentials()).isEqualTo(password); assertThat(authentication.getAuthorities()).isEmpty(); } @Test public void applyWhenNoDataThenCreatesTokenSuccess() { setupMocks(); Authentication authentication = this.converter.convert(this.exchange).block(); assertThat(authentication.getName()).isNullOrEmpty(); assertThat(authentication.getCredentials()).isNull(); assertThat(authentication.getAuthorities()).isEmpty(); } @Test public void setUsernameParameterWhenNullThenIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setUsernameParameter(null)); } @Test public void setPasswordParameterWhenNullThenIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setPasswordParameter(null)); } }
3,703
35.313725
105
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcherTests.java
/* * 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.authentication; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; /** * @author David Kovac * @since 5.4 */ @ExtendWith(MockitoExtension.class) public class AuthenticationConverterServerWebExchangeMatcherTests { private MockServerWebExchange exchange; private AuthenticationConverterServerWebExchangeMatcher matcher; private Authentication authentication = new TestingAuthenticationToken("user", "password"); @Mock private ServerAuthenticationConverter converter; @BeforeEach public void setup() { MockServerHttpRequest request = MockServerHttpRequest.get("/path").build(); this.exchange = MockServerWebExchange.from(request); this.matcher = new AuthenticationConverterServerWebExchangeMatcher(this.converter); } @Test public void constructorConverterWhenConverterNullThenThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> new AuthenticationConverterServerWebExchangeMatcher(null)); } @Test public void matchesWhenNotEmptyThenReturnTrue() { given(this.converter.convert(any())).willReturn(Mono.just(this.authentication)); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue(); } @Test public void matchesWhenEmptyThenReturnFalse() { given(this.converter.convert(any())).willReturn(Mono.empty()); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse(); } @Test public void matchesWhenErrorThenReturnFalse() { given(this.converter.convert(any())).willReturn(Mono.error(new RuntimeException())); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse(); } @Test public void matchesWhenNullThenThrowsException() { given(this.converter.convert(any())).willReturn(null); assertThatNullPointerException().isThrownBy(() -> this.matcher.matches(this.exchange).block()); } @Test public void matchesWhenExceptionThenPropagates() { given(this.converter.convert(any())).willThrow(RuntimeException.class); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.matcher.matches(this.exchange).block()); } }
3,592
35.663265
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationWebFilterTests.java
/* * Copyright 2002-2019 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.authentication; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.test.web.reactive.server.WebTestClientBuilder; import org.springframework.security.web.server.context.ServerSecurityContextRepository; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @author Rafiullah Hamedy * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class AuthenticationWebFilterTests { @Mock private ServerAuthenticationSuccessHandler successHandler; @Mock private ServerAuthenticationConverter authenticationConverter; @Mock private ReactiveAuthenticationManager authenticationManager; @Mock private ServerAuthenticationFailureHandler failureHandler; @Mock private ServerSecurityContextRepository securityContextRepository; @Mock private ReactiveAuthenticationManagerResolver<ServerWebExchange> authenticationManagerResolver; private AuthenticationWebFilter filter; @BeforeEach public void setup() { this.filter = new AuthenticationWebFilter(this.authenticationManager); this.filter.setAuthenticationSuccessHandler(this.successHandler); this.filter.setServerAuthenticationConverter(this.authenticationConverter); this.filter.setSecurityContextRepository(this.securityContextRepository); this.filter.setAuthenticationFailureHandler(this.failureHandler); } @Test public void filterWhenDefaultsAndNoAuthenticationThenContinues() { this.filter = new AuthenticationWebFilter(this.authenticationManager); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); EntityExchangeResult<String> result = client.get().uri("/").exchange().expectStatus().isOk() .expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")) .returnResult(); verifyNoMoreInteractions(this.authenticationManager); assertThat(result.getResponseCookies()).isEmpty(); } @Test public void filterWhenAuthenticationManagerResolverDefaultsAndNoAuthenticationThenContinues() { this.filter = new AuthenticationWebFilter(this.authenticationManagerResolver); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); EntityExchangeResult<String> result = client.get().uri("/").exchange().expectStatus().isOk() .expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")) .returnResult(); verifyNoMoreInteractions(this.authenticationManagerResolver); assertThat(result.getResponseCookies()).isEmpty(); } @Test public void filterWhenDefaultsAndAuthenticationSuccessThenContinues() { given(this.authenticationManager.authenticate(any())) .willReturn(Mono.just(new TestingAuthenticationToken("test", "this", "ROLE"))); this.filter = new AuthenticationWebFilter(this.authenticationManager); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); EntityExchangeResult<String> result = client.get().uri("/") .headers((headers) -> headers.setBasicAuth("test", "this")).exchange().expectStatus().isOk() .expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")) .returnResult(); assertThat(result.getResponseCookies()).isEmpty(); } @Test public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationSuccessThenContinues() { given(this.authenticationManager.authenticate(any())) .willReturn(Mono.just(new TestingAuthenticationToken("test", "this", "ROLE"))); given(this.authenticationManagerResolver.resolve(any())).willReturn(Mono.just(this.authenticationManager)); this.filter = new AuthenticationWebFilter(this.authenticationManagerResolver); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); EntityExchangeResult<String> result = client.get().uri("/") .headers((headers) -> headers.setBasicAuth("test", "this")).exchange().expectStatus().isOk() .expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")) .returnResult(); assertThat(result.getResponseCookies()).isEmpty(); } @Test public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() { given(this.authenticationManager.authenticate(any())) .willReturn(Mono.error(new BadCredentialsException("failed"))); this.filter = new AuthenticationWebFilter(this.authenticationManager); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); EntityExchangeResult<Void> result = client.get().uri("/") .headers((headers) -> headers.setBasicAuth("test", "this")).exchange().expectStatus().isUnauthorized() .expectHeader().valueMatches("WWW-Authenticate", "Basic realm=\"Realm\"").expectBody().isEmpty(); assertThat(result.getResponseCookies()).isEmpty(); } @Test public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized() { given(this.authenticationManager.authenticate(any())) .willReturn(Mono.error(new BadCredentialsException("failed"))); given(this.authenticationManagerResolver.resolve(any())).willReturn(Mono.just(this.authenticationManager)); this.filter = new AuthenticationWebFilter(this.authenticationManagerResolver); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); EntityExchangeResult<Void> result = client.get().uri("/") .headers((headers) -> headers.setBasicAuth("test", "this")).exchange().expectStatus().isUnauthorized() .expectHeader().valueMatches("WWW-Authenticate", "Basic realm=\"Realm\"").expectBody().isEmpty(); assertThat(result.getResponseCookies()).isEmpty(); } @Test public void filterWhenConvertEmptyThenOk() { given(this.authenticationConverter.convert(any())).willReturn(Mono.empty()); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class) .consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult(); verify(this.securityContextRepository, never()).save(any(), any()); verifyNoMoreInteractions(this.authenticationManager, this.successHandler, this.failureHandler); } @Test public void filterWhenConvertErrorThenServerError() { given(this.authenticationConverter.convert(any())).willReturn(Mono.error(new RuntimeException("Unexpected"))); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); client.get().uri("/").exchange().expectStatus().is5xxServerError().expectBody().isEmpty(); verify(this.securityContextRepository, never()).save(any(), any()); verifyNoMoreInteractions(this.authenticationManager, this.successHandler, this.failureHandler); } @Test public void filterWhenConvertAndAuthenticationSuccessThenSuccess() { Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER")); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(authentication); given(this.successHandler.onAuthenticationSuccess(any(), any())).willReturn(Mono.empty()); given(this.securityContextRepository.save(any(), any())).willAnswer((a) -> Mono.just(a.getArguments()[0])); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); client.get().uri("/").exchange().expectStatus().isOk().expectBody().isEmpty(); verify(this.successHandler).onAuthenticationSuccess(any(), eq(authentication.block())); verify(this.securityContextRepository).save(any(), any()); verifyNoMoreInteractions(this.failureHandler); } @Test public void filterWhenConvertAndAuthenticationEmptyThenServerError() { Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER")); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(Mono.empty()); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); client.get().uri("/").exchange().expectStatus().is5xxServerError().expectBody().isEmpty(); verify(this.securityContextRepository, never()).save(any(), any()); verifyNoMoreInteractions(this.successHandler, this.failureHandler); } @Test public void filterWhenNotMatchAndConvertAndAuthenticationSuccessThenContinues() { this.filter.setRequiresAuthenticationMatcher((e) -> ServerWebExchangeMatcher.MatchResult.notMatch()); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); EntityExchangeResult<String> result = client.get().uri("/") .headers((headers) -> headers.setBasicAuth("test", "this")).exchange().expectStatus().isOk() .expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")) .returnResult(); assertThat(result.getResponseCookies()).isEmpty(); verifyNoMoreInteractions(this.authenticationConverter, this.authenticationManager, this.successHandler); } @Test public void filterWhenConvertAndAuthenticationFailThenEntryPoint() { Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER")); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())) .willReturn(Mono.error(new BadCredentialsException("Failed"))); given(this.failureHandler.onAuthenticationFailure(any(), any())).willReturn(Mono.empty()); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); client.get().uri("/").exchange().expectStatus().isOk().expectBody().isEmpty(); verify(this.failureHandler).onAuthenticationFailure(any(), any()); verify(this.securityContextRepository, never()).save(any(), any()); verifyNoMoreInteractions(this.successHandler); } @Test public void filterWhenConvertAndAuthenticationExceptionThenServerError() { Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER")); given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new RuntimeException("Failed"))); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); client.get().uri("/").exchange().expectStatus().is5xxServerError().expectBody().isEmpty(); verify(this.securityContextRepository, never()).save(any(), any()); verifyNoMoreInteractions(this.successHandler, this.failureHandler); } @Test public void setRequiresAuthenticationMatcherWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequiresAuthenticationMatcher(null)); } }
12,665
50.697959
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/ServerAuthenticationEntryPointFailureHandlerTests.java
/* * Copyright 2002-2017 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.authentication; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.web.server.ServerAuthenticationEntryPoint; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class ServerAuthenticationEntryPointFailureHandlerTests { @Mock private ServerAuthenticationEntryPoint authenticationEntryPoint; @Mock private ServerWebExchange exchange; @Mock private WebFilterChain chain; @InjectMocks private WebFilterExchange filterExchange; @InjectMocks private ServerAuthenticationEntryPointFailureHandler handler; @Test public void constructorWhenNullEntryPointThenException() { assertThatIllegalArgumentException().isThrownBy(() -> new ServerAuthenticationEntryPointFailureHandler(null)); } @Test public void onAuthenticationFailureWhenInvokedThenDelegatesToEntryPoint() { Mono<Void> result = Mono.empty(); BadCredentialsException e = new BadCredentialsException("Failed"); given(this.authenticationEntryPoint.commence(this.exchange, e)).willReturn(result); assertThat(this.handler.onAuthenticationFailure(this.filterExchange, e)).isEqualTo(result); } @Test void onAuthenticationFailureWhenRethrownFalseThenAuthenticationServiceExceptionSwallowed() { AuthenticationServiceException e = new AuthenticationServiceException("fail"); this.handler.setRethrowAuthenticationServiceException(false); given(this.authenticationEntryPoint.commence(this.exchange, e)).willReturn(Mono.empty()); this.handler.onAuthenticationFailure(this.filterExchange, e).block(); } @Test void handleWhenDefaultsThenAuthenticationServiceExceptionRethrown() { AuthenticationServiceException e = new AuthenticationServiceException("fail"); assertThatExceptionOfType(AuthenticationServiceException.class) .isThrownBy(() -> this.handler.onAuthenticationFailure(this.filterExchange, e).block()); } }
3,327
36.393258
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/HttpBasicServerAuthenticationEntryPointTests.java
/* * Copyright 2002-2017 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.authentication; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.AuthenticationException; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class HttpBasicServerAuthenticationEntryPointTests { @Mock private ServerWebExchange exchange; private HttpBasicServerAuthenticationEntryPoint entryPoint = new HttpBasicServerAuthenticationEntryPoint(); private AuthenticationException exception = new AuthenticationCredentialsNotFoundException("Authenticate"); @Test public void commenceWhenNoSubscribersThenNoActions() { this.entryPoint.commence(this.exchange, this.exception); verifyNoMoreInteractions(this.exchange); } @Test public void commenceWhenSubscribeThenStatusAndHeaderSet() { this.exchange = exchange(MockServerHttpRequest.get("/")); this.entryPoint.commence(this.exchange, this.exception).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(this.exchange.getResponse().getHeaders().get("WWW-Authenticate")) .containsOnly("Basic realm=\"Realm\""); } @Test public void commenceWhenCustomRealmThenStatusAndHeaderSet() { this.entryPoint.setRealm("Custom"); this.exchange = exchange(MockServerHttpRequest.get("/")); this.entryPoint.commence(this.exchange, this.exception).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(this.exchange.getResponse().getHeaders().get("WWW-Authenticate")) .containsOnly("Basic realm=\"Custom\""); } @Test public void setRealmWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.entryPoint.setRealm(null)); } private static MockServerWebExchange exchange(MockServerHttpRequest.BaseBuilder<?> request) { return MockServerWebExchange.from(request.build()); } }
3,206
37.178571
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandlerTests.java
/* * Copyright 2002-2019 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.authentication; import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.publisher.PublisherProbe; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @since 5.1 */ @ExtendWith(MockitoExtension.class) public class DelegatingServerAuthenticationSuccessHandlerTests { @Mock private ServerAuthenticationSuccessHandler delegate1; @Mock private ServerAuthenticationSuccessHandler delegate2; private PublisherProbe<Void> delegate1Result = PublisherProbe.empty(); private PublisherProbe<Void> delegate2Result = PublisherProbe.empty(); @Mock private WebFilterExchange exchange; @Mock private Authentication authentication; private void givenDelegate1WillReturnMock() { given(this.delegate1.onAuthenticationSuccess(any(), any())).willReturn(this.delegate1Result.mono()); } private void givenDelegate2WillReturnMock() { given(this.delegate2.onAuthenticationSuccess(any(), any())).willReturn(this.delegate2Result.mono()); } @Test public void constructorWhenNullThenIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy( () -> new DelegatingServerAuthenticationSuccessHandler((ServerAuthenticationSuccessHandler[]) null)); } @Test public void constructorWhenEmptyThenIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy( () -> new DelegatingServerAuthenticationSuccessHandler(new ServerAuthenticationSuccessHandler[0])); } @Test public void onAuthenticationSuccessWhenSingleThenExecuted() { givenDelegate1WillReturnMock(); DelegatingServerAuthenticationSuccessHandler handler = new DelegatingServerAuthenticationSuccessHandler( this.delegate1); handler.onAuthenticationSuccess(this.exchange, this.authentication).block(); this.delegate1Result.assertWasSubscribed(); } @Test public void onAuthenticationSuccessWhenMultipleThenExecuted() { givenDelegate1WillReturnMock(); givenDelegate2WillReturnMock(); DelegatingServerAuthenticationSuccessHandler handler = new DelegatingServerAuthenticationSuccessHandler( this.delegate1, this.delegate2); handler.onAuthenticationSuccess(this.exchange, this.authentication).block(); this.delegate1Result.assertWasSubscribed(); this.delegate2Result.assertWasSubscribed(); } @Test public void onAuthenticationSuccessSequential() throws Exception { AtomicBoolean slowDone = new AtomicBoolean(); CountDownLatch latch = new CountDownLatch(1); ServerAuthenticationSuccessHandler slow = (exchange, authentication) -> Mono.delay(Duration.ofMillis(100)) .doOnSuccess((__) -> slowDone.set(true)).then(); ServerAuthenticationSuccessHandler second = (exchange, authentication) -> Mono.fromRunnable(() -> { latch.countDown(); assertThat(slowDone.get()).describedAs("ServerAuthenticationSuccessHandler should be executed sequentially") .isTrue(); }); DelegatingServerAuthenticationSuccessHandler handler = new DelegatingServerAuthenticationSuccessHandler(slow, second); handler.onAuthenticationSuccess(this.exchange, this.authentication).block(); assertThat(latch.await(3, TimeUnit.SECONDS)).isTrue(); } }
4,411
35.766667
111
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/HttpStatusServerEntryPointTests.java
/* * Copyright 2002-2018 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.authentication; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.core.AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Eric Deandrea * @since 5.1 */ public class HttpStatusServerEntryPointTests { private MockServerHttpRequest request; private MockServerWebExchange exchange; private AuthenticationException authException; private HttpStatusServerEntryPoint entryPoint; @BeforeEach public void setup() { this.request = MockServerHttpRequest.get("/").build(); this.exchange = MockServerWebExchange.from(this.request); this.authException = new AuthenticationException("") { }; this.entryPoint = new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED); } @Test public void constructorNullStatus() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new HttpStatusServerEntryPoint(null)) .withMessage("httpStatus cannot be null"); } @Test public void unauthorized() { this.entryPoint.commence(this.exchange, this.authException).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } }
2,142
31.469697
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/logout/HttpStatusReturningServerLogoutSuccessHandlerTests.java
/* * Copyright 2002-2018 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.authentication.logout; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; /** * @author Eric Deandrea * @since 5.1 */ public class HttpStatusReturningServerLogoutSuccessHandlerTests { @Test public void defaultHttpStatusBeingReturned() { WebFilterExchange filterExchange = buildFilterExchange(); new HttpStatusReturningServerLogoutSuccessHandler().onLogoutSuccess(filterExchange, mock(Authentication.class)) .block(); assertThat(filterExchange.getExchange().getResponse().getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void customHttpStatusBeingReturned() { WebFilterExchange filterExchange = buildFilterExchange(); new HttpStatusReturningServerLogoutSuccessHandler(HttpStatus.NO_CONTENT) .onLogoutSuccess(filterExchange, mock(Authentication.class)).block(); assertThat(filterExchange.getExchange().getResponse().getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); } @Test public void nullHttpStatusThrowsException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new HttpStatusReturningServerLogoutSuccessHandler(null)) .withMessage("The provided HttpStatus must not be null."); } private static WebFilterExchange buildFilterExchange() { MockServerHttpRequest request = MockServerHttpRequest.get("/").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); return new WebFilterExchange(exchange, mock(WebFilterChain.class)); } }
2,641
37.852941
113
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/logout/HeaderWriterServerLogoutHandlerTests.java
/* * Copyright 2002-2019 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.authentication.logout; import org.junit.jupiter.api.Test; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.header.ServerHttpHeadersWriter; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author MD Sayem Ahmed * @since 5.2 */ public class HeaderWriterServerLogoutHandlerTests { @Test public void constructorWhenHeadersWriterIsNullThenExceptionThrown() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new HeaderWriterServerLogoutHandler(null)); } @Test public void logoutWhenInvokedThenWritesResponseHeaders() { ServerHttpHeadersWriter headersWriter = mock(ServerHttpHeadersWriter.class); HeaderWriterServerLogoutHandler handler = new HeaderWriterServerLogoutHandler(headersWriter); ServerWebExchange serverWebExchange = mock(ServerWebExchange.class); WebFilterExchange filterExchange = mock(WebFilterExchange.class); given(filterExchange.getExchange()).willReturn(serverWebExchange); Authentication authentication = mock(Authentication.class); handler.logout(filterExchange, authentication); verify(headersWriter).writeHttpHeaders(serverWebExchange); } }
2,129
37.035714
95
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/logout/LogoutWebFilterTests.java
/* * Copyright 2002-2018 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.authentication.logout; import java.util.Arrays; import java.util.Collection; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Eric Deandrea * @since 5.1 */ @ExtendWith(MockitoExtension.class) public class LogoutWebFilterTests { @Mock private ServerLogoutHandler handler1; @Mock private ServerLogoutHandler handler2; @Mock private ServerLogoutHandler handler3; private LogoutWebFilter logoutWebFilter = new LogoutWebFilter(); @Test public void defaultLogoutHandler() { assertThat(getLogoutHandler()).isNotNull().isExactlyInstanceOf(SecurityContextServerLogoutHandler.class); } @Test public void singleLogoutHandler() { this.logoutWebFilter.setLogoutHandler(this.handler1); this.logoutWebFilter.setLogoutHandler(this.handler2); assertThat(getLogoutHandler()).isNotNull().isInstanceOf(ServerLogoutHandler.class) .isNotInstanceOf(SecurityContextServerLogoutHandler.class).extracting(ServerLogoutHandler::getClass) .isEqualTo(this.handler2.getClass()); } @Test public void multipleLogoutHandlers() { this.logoutWebFilter .setLogoutHandler(new DelegatingServerLogoutHandler(this.handler1, this.handler2, this.handler3)); assertThat(getLogoutHandler()).isNotNull().isExactlyInstanceOf(DelegatingServerLogoutHandler.class) .extracting((delegatingLogoutHandler) -> ((Collection<ServerLogoutHandler>) ReflectionTestUtils .getField(delegatingLogoutHandler, DelegatingServerLogoutHandler.class, "delegates")).stream() .map(ServerLogoutHandler::getClass).collect(Collectors.toList())) .isEqualTo(Arrays.asList(this.handler1.getClass(), this.handler2.getClass(), this.handler3.getClass())); } private ServerLogoutHandler getLogoutHandler() { return (ServerLogoutHandler) ReflectionTestUtils.getField(this.logoutWebFilter, LogoutWebFilter.class, "logoutHandler"); } }
2,790
33.45679
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandlerTests.java
/* * Copyright 2002-2018 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.authentication.logout; import java.time.Duration; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.publisher.PublisherProbe; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; /** * @author Eric Deandrea * @since 5.1 */ @ExtendWith(MockitoExtension.class) public class DelegatingServerLogoutHandlerTests { @Mock private ServerLogoutHandler delegate1; @Mock private ServerLogoutHandler delegate2; private PublisherProbe<Void> delegate1Result = PublisherProbe.empty(); private PublisherProbe<Void> delegate2Result = PublisherProbe.empty(); @Mock private WebFilterExchange exchange; @Mock private Authentication authentication; private void givenDelegate1WillReturn() { given(this.delegate1.logout(any(WebFilterExchange.class), any(Authentication.class))) .willReturn(this.delegate1Result.mono()); } private void givenDelegate2WillReturn() { given(this.delegate2.logout(any(WebFilterExchange.class), any(Authentication.class))) .willReturn(this.delegate2Result.mono()); } @Test public void constructorWhenNullVargsThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelegatingServerLogoutHandler((ServerLogoutHandler[]) null)) .withMessage("delegates cannot be null or empty").withNoCause(); } @Test public void constructorWhenNullListThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelegatingServerLogoutHandler((List<ServerLogoutHandler>) null)) .withMessage("delegates cannot be null or empty").withNoCause(); } @Test public void constructorWhenEmptyThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelegatingServerLogoutHandler(new ServerLogoutHandler[0])) .withMessage("delegates cannot be null or empty").withNoCause(); } @Test public void logoutWhenSingleThenExecuted() { givenDelegate1WillReturn(); DelegatingServerLogoutHandler handler = new DelegatingServerLogoutHandler(this.delegate1); handler.logout(this.exchange, this.authentication).block(); this.delegate1Result.assertWasSubscribed(); } @Test public void logoutWhenMultipleThenExecuted() { givenDelegate1WillReturn(); givenDelegate2WillReturn(); DelegatingServerLogoutHandler handler = new DelegatingServerLogoutHandler(this.delegate1, this.delegate2); handler.logout(this.exchange, this.authentication).block(); this.delegate1Result.assertWasSubscribed(); this.delegate2Result.assertWasSubscribed(); } @Test public void logoutSequential() throws Exception { AtomicBoolean slowDone = new AtomicBoolean(); CountDownLatch latch = new CountDownLatch(1); ServerLogoutHandler slow = (exchange, authentication) -> Mono.delay(Duration.ofMillis(100)) .doOnSuccess((__) -> slowDone.set(true)).then(); ServerLogoutHandler second = (exchange, authentication) -> Mono.fromRunnable(() -> { latch.countDown(); assertThat(slowDone.get()).describedAs("ServerLogoutHandler should be executed sequentially").isTrue(); }); DelegatingServerLogoutHandler handler = new DelegatingServerLogoutHandler(slow, second); handler.logout(this.exchange, this.authentication).block(); assertThat(latch.await(3, TimeUnit.SECONDS)).isTrue(); } }
4,545
34.515625
108
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authentication/logout/WebSessionServerLogoutHandlerTests.java
/* * Copyright 2002-2021 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.authentication.logout; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) public class WebSessionServerLogoutHandlerTests { @Mock ServerWebExchange webExchange; @Mock WebFilterExchange filterExchange; @Mock WebSession webSession; @Test public void shouldInvalidateWebSession() { doReturn(this.webExchange).when(this.filterExchange).getExchange(); doReturn(Mono.just(this.webSession)).when(this.webExchange).getSession(); doReturn(Mono.empty()).when(this.webSession).invalidate(); WebSessionServerLogoutHandler handler = new WebSessionServerLogoutHandler(); handler.logout(this.filterExchange, mock(Authentication.class)).block(); verify(this.webSession).invalidate(); } }
1,914
31.457627
78
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authorization/HttpStatusServerAccessDeniedHandlerTests.java
/* * Copyright 2002-2017 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.authorization; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class HttpStatusServerAccessDeniedHandlerTests { @Mock private ServerWebExchange exchange; private HttpStatus httpStatus = HttpStatus.FORBIDDEN; private HttpStatusServerAccessDeniedHandler handler = new HttpStatusServerAccessDeniedHandler(this.httpStatus); private AccessDeniedException exception = new AccessDeniedException("Forbidden"); @Test public void constructorHttpStatusWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusServerAccessDeniedHandler(null)); } @Test public void commenceWhenNoSubscribersThenNoActions() { this.handler.handle(this.exchange, this.exception); verifyNoMoreInteractions(this.exchange); } @Test public void commenceWhenSubscribeThenStatusSet() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.handler.handle(this.exchange, this.exception).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(this.httpStatus); } @Test public void commenceWhenCustomStatusSubscribeThenStatusSet() { this.httpStatus = HttpStatus.NOT_FOUND; this.handler = new HttpStatusServerAccessDeniedHandler(this.httpStatus); this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.handler.handle(this.exchange, this.exception).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(this.httpStatus); } }
2,860
35.679487
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authorization/IpAddressReactiveAuthorizationManagerTests.java
/* * Copyright 2002-2021 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.authorization; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import org.junit.jupiter.api.Test; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link IpAddressReactiveAuthorizationManager} * * @author Guirong Hu */ public class IpAddressReactiveAuthorizationManagerTests { @Test public void checkWhenHasIpv6AddressThenReturnTrue() throws UnknownHostException { IpAddressReactiveAuthorizationManager v6manager = IpAddressReactiveAuthorizationManager .hasIpAddress("fe80::21f:5bff:fe33:bd68"); boolean granted = v6manager.check(null, context("fe80::21f:5bff:fe33:bd68")).block().isGranted(); assertThat(granted).isTrue(); } @Test public void checkWhenHasIpv6AddressThenReturnFalse() throws UnknownHostException { IpAddressReactiveAuthorizationManager v6manager = IpAddressReactiveAuthorizationManager .hasIpAddress("fe80::21f:5bff:fe33:bd68"); boolean granted = v6manager.check(null, context("fe80::1c9a:7cfd:29a8:a91e")).block().isGranted(); assertThat(granted).isFalse(); } @Test public void checkWhenHasIpv4AddressThenReturnTrue() throws UnknownHostException { IpAddressReactiveAuthorizationManager v4manager = IpAddressReactiveAuthorizationManager .hasIpAddress("192.168.1.104"); boolean granted = v4manager.check(null, context("192.168.1.104")).block().isGranted(); assertThat(granted).isTrue(); } @Test public void checkWhenHasIpv4AddressThenReturnFalse() throws UnknownHostException { IpAddressReactiveAuthorizationManager v4manager = IpAddressReactiveAuthorizationManager .hasIpAddress("192.168.1.104"); boolean granted = v4manager.check(null, context("192.168.100.15")).block().isGranted(); assertThat(granted).isFalse(); } private static AuthorizationContext context(String ipAddress) throws UnknownHostException { MockServerWebExchange exchange = MockServerWebExchange.builder(MockServerHttpRequest.get("/") .remoteAddress(new InetSocketAddress(InetAddress.getByName(ipAddress), 8080))).build(); return new AuthorizationContext(exchange); } }
2,925
37.5
100
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authorization/DelegatingReactiveAuthorizationManagerTests.java
/* * Copyright 2002-2017 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.authorization; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import reactor.core.publisher.Mono; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.authorization.AuthorityReactiveAuthorizationManager; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcherEntry; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Rob Winch * @since 5.0 */ public class DelegatingReactiveAuthorizationManagerTests { @Mock ServerWebExchangeMatcher match1; @Mock ServerWebExchangeMatcher match2; @Mock AuthorityReactiveAuthorizationManager<AuthorizationContext> delegate1; @Mock AuthorityReactiveAuthorizationManager<AuthorizationContext> delegate2; ServerWebExchange exchange; @Mock Mono<Authentication> authentication; @Mock AuthorizationDecision decision; DelegatingReactiveAuthorizationManager manager; @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); this.manager = DelegatingReactiveAuthorizationManager.builder() .add(new ServerWebExchangeMatcherEntry<>(this.match1, this.delegate1)) .add(new ServerWebExchangeMatcherEntry<>(this.match2, this.delegate2)).build(); MockServerHttpRequest request = MockServerHttpRequest.get("/test").build(); this.exchange = MockServerWebExchange.from(request); } @Test public void checkWhenFirstMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() { given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match()); given(this.delegate1.check(eq(this.authentication), any(AuthorizationContext.class))) .willReturn(Mono.just(this.decision)); assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision); verifyNoMoreInteractions(this.match2, this.delegate2); } @Test public void checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() { given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); given(this.match2.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match()); given(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class))) .willReturn(Mono.just(this.decision)); assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision); verifyNoMoreInteractions(this.delegate1); } }
3,711
36.877551
102
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authorization/ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java
/* * Copyright 2002-2018 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.authorization; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import org.springframework.security.web.server.authorization.ServerWebExchangeDelegatingServerAccessDeniedHandler.DelegateEntry; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult; import org.springframework.web.server.ServerWebExchange; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests { private ServerWebExchangeDelegatingServerAccessDeniedHandler delegator; private List<ServerWebExchangeDelegatingServerAccessDeniedHandler.DelegateEntry> entries; private ServerAccessDeniedHandler accessDeniedHandler; private ServerWebExchange exchange; @BeforeEach public void setup() { this.accessDeniedHandler = mock(ServerAccessDeniedHandler.class); this.entries = new ArrayList<>(); this.exchange = mock(ServerWebExchange.class); } @Test public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() { ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class); given(matcher.matches(this.exchange)).willReturn(MatchResult.notMatch()); given(handler.handle(this.exchange, null)).willReturn(Mono.empty()); given(this.accessDeniedHandler.handle(this.exchange, null)).willReturn(Mono.empty()); this.entries.add(new DelegateEntry(matcher, handler)); this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries); this.delegator.setDefaultAccessDeniedHandler(this.accessDeniedHandler); this.delegator.handle(this.exchange, null).block(); verify(this.accessDeniedHandler).handle(this.exchange, null); verify(handler, never()).handle(this.exchange, null); } @Test public void handleWhenFirstMatchesThenOnlyFirstInvoked() { ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class); ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class); given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.match()); given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty()); given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty()); this.entries.add(new DelegateEntry(firstMatcher, firstHandler)); this.entries.add(new DelegateEntry(secondMatcher, secondHandler)); this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries); this.delegator.setDefaultAccessDeniedHandler(this.accessDeniedHandler); this.delegator.handle(this.exchange, null).block(); verify(firstHandler).handle(this.exchange, null); verify(secondHandler, never()).handle(this.exchange, null); verify(this.accessDeniedHandler, never()).handle(this.exchange, null); verify(secondMatcher, never()).matches(this.exchange); } @Test public void handleWhenSecondMatchesThenOnlySecondInvoked() { ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class); ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class); given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.notMatch()); given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match()); given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty()); given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty()); this.entries.add(new DelegateEntry(firstMatcher, firstHandler)); this.entries.add(new DelegateEntry(secondMatcher, secondHandler)); this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries); this.delegator.handle(this.exchange, null).block(); verify(secondHandler).handle(this.exchange, null); verify(firstHandler, never()).handle(this.exchange, null); verify(this.accessDeniedHandler, never()).handle(this.exchange, null); } }
5,193
47.092593
128
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authorization/ExceptionTranslationWebFilterTests.java
/* * Copyright 2002-2022 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.authorization; import java.security.Principal; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.test.publisher.PublisherProbe; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.web.server.ServerAuthenticationEntryPoint; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @author César Revert * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class ExceptionTranslationWebFilterTests { @Mock private Principal principal; @Mock private AnonymousAuthenticationToken anonymousPrincipal; @Mock private ServerWebExchange exchange; @Mock private WebFilterChain chain; @Mock private ServerAccessDeniedHandler deniedHandler; @Mock private ServerAuthenticationEntryPoint entryPoint; private PublisherProbe<Void> deniedPublisher = PublisherProbe.empty(); private PublisherProbe<Void> entryPointPublisher = PublisherProbe.empty(); private ExceptionTranslationWebFilter filter = new ExceptionTranslationWebFilter(); @BeforeEach public void setup() { this.filter.setAuthenticationEntryPoint(this.entryPoint); this.filter.setAccessDeniedHandler(this.deniedHandler); } @Test public void filterWhenNoExceptionThenNotHandled() { given(this.chain.filter(this.exchange)).willReturn(Mono.empty()); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify(); this.deniedPublisher.assertWasNotSubscribed(); this.entryPointPublisher.assertWasNotSubscribed(); } @Test public void filterWhenNotAccessDeniedExceptionThenNotHandled() { given(this.chain.filter(this.exchange)).willReturn(Mono.error(new IllegalArgumentException("oops"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectError(IllegalArgumentException.class) .verify(); this.deniedPublisher.assertWasNotSubscribed(); this.entryPointPublisher.assertWasNotSubscribed(); } @Test public void filterWhenAccessDeniedExceptionAndNotAuthenticatedThenHandled() { given(this.entryPoint.commence(any(), any())).willReturn(this.entryPointPublisher.mono()); given(this.exchange.getPrincipal()).willReturn(Mono.empty()); given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).verifyComplete(); this.deniedPublisher.assertWasNotSubscribed(); this.entryPointPublisher.assertWasSubscribed(); } @Test public void filterWhenDefaultsAndAccessDeniedExceptionAndAuthenticatedThenForbidden() { given(this.exchange.getResponse()).willReturn(new MockServerHttpResponse()); this.filter = new ExceptionTranslationWebFilter(); given(this.exchange.getPrincipal()).willReturn(Mono.just(this.principal)); given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test public void filterWhenDefaultsAndAccessDeniedExceptionAndNotAuthenticatedThenUnauthorized() { given(this.exchange.getResponse()).willReturn(new MockServerHttpResponse()); this.filter = new ExceptionTranslationWebFilter(); given(this.exchange.getPrincipal()).willReturn(Mono.empty()); given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void filterWhenAccessDeniedExceptionAndAuthenticatedThenHandled() { given(this.deniedHandler.handle(any(), any())).willReturn(this.deniedPublisher.mono()); given(this.entryPoint.commence(any(), any())).willReturn(this.entryPointPublisher.mono()); given(this.exchange.getPrincipal()).willReturn(Mono.just(this.principal)); given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify(); this.deniedPublisher.assertWasSubscribed(); this.entryPointPublisher.assertWasNotSubscribed(); } @Test public void filterWhenAccessDeniedExceptionAndAnonymousAuthenticatedThenHandled() { given(this.entryPoint.commence(any(), any())).willReturn(this.entryPointPublisher.mono()); given(this.exchange.getPrincipal()).willReturn(Mono.just(this.anonymousPrincipal)); given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify(); this.deniedPublisher.assertWasNotSubscribed(); this.entryPointPublisher.assertWasSubscribed(); } @Test public void setAccessDeniedHandlerWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAccessDeniedHandler(null)); } @Test public void setAuthenticationEntryPointWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthenticationEntryPoint(null)); } @Test public void setAuthenticationTrustResolver() { assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthenticationTrustResolver(null)); } }
6,835
40.430303
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/authorization/AuthorizationWebFilterTests.java
/* * Copyright 2002-2017 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.authorization; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.test.publisher.PublisherProbe; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @since 5.0 */ @ExtendWith(MockitoExtension.class) public class AuthorizationWebFilterTests { @Mock private ServerWebExchange exchange; @Mock private WebFilterChain chain; PublisherProbe<Void> chainResult = PublisherProbe.empty(); @Test public void filterWhenNoSecurityContextThenThrowsAccessDenied() { given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter( (a, e) -> Mono.error(new AccessDeniedException("Denied"))); Mono<Void> result = filter.filter(this.exchange, this.chain); StepVerifier.create(result).expectError(AccessDeniedException.class).verify(); this.chainResult.assertWasNotSubscribed(); } @Test public void filterWhenNoAuthenticationThenThrowsAccessDenied() { given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter( (a, e) -> a.flatMap((auth) -> Mono.error(new AccessDeniedException("Denied")))); Mono<Void> result = filter.filter(this.exchange, this.chain) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(new SecurityContextImpl()))); StepVerifier.create(result).expectError(AccessDeniedException.class).verify(); this.chainResult.assertWasNotSubscribed(); } @Test public void filterWhenAuthenticationThenThrowsAccessDenied() { given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter( (a, e) -> Mono.error(new AccessDeniedException("Denied"))); Mono<Void> result = filter.filter(this.exchange, this.chain).contextWrite( ReactiveSecurityContextHolder.withAuthentication(new TestingAuthenticationToken("a", "b", "R"))); StepVerifier.create(result).expectError(AccessDeniedException.class).verify(); this.chainResult.assertWasNotSubscribed(); } @Test public void filterWhenDoesNotAccessAuthenticationThenSecurityContextNotSubscribed() { PublisherProbe<SecurityContext> context = PublisherProbe.empty(); given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter( (a, e) -> Mono.error(new AccessDeniedException("Denied"))); Mono<Void> result = filter.filter(this.exchange, this.chain) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(context.mono())); StepVerifier.create(result).expectError(AccessDeniedException.class).verify(); this.chainResult.assertWasNotSubscribed(); context.assertWasNotSubscribed(); } @Test public void filterWhenGrantedAndDoesNotAccessAuthenticationThenChainSubscribedAndSecurityContextNotSubscribed() { PublisherProbe<SecurityContext> context = PublisherProbe.empty(); given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter( (a, e) -> Mono.just(new AuthorizationDecision(true))); Mono<Void> result = filter.filter(this.exchange, this.chain) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(context.mono())); StepVerifier.create(result).verifyComplete(); this.chainResult.assertWasSubscribed(); context.assertWasNotSubscribed(); } @Test public void filterWhenGrantedAndDoeAccessAuthenticationThenChainSubscribedAndSecurityContextSubscribed() { PublisherProbe<SecurityContext> context = PublisherProbe.empty(); given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter((a, e) -> a .map((auth) -> new AuthorizationDecision(true)).defaultIfEmpty(new AuthorizationDecision(true))); Mono<Void> result = filter.filter(this.exchange, this.chain) .contextWrite(ReactiveSecurityContextHolder.withSecurityContext(context.mono())); StepVerifier.create(result).verifyComplete(); this.chainResult.assertWasSubscribed(); context.assertWasSubscribed(); } }
5,549
43.4
114
java
null
spring-security-main/web/src/test/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilterTests.java
/* * Copyright 2002-2018 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.transport; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.security.web.PortMapper; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link HttpsRedirectWebFilter} * * @author Josh Cummings */ @ExtendWith(MockitoExtension.class) public class HttpsRedirectWebFilterTests { HttpsRedirectWebFilter filter; @Mock WebFilterChain chain; @BeforeEach public void configureFilter() { this.filter = new HttpsRedirectWebFilter(); } @Test public void filterWhenExchangeIsInsecureThenRedirects() { given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty()); ServerWebExchange exchange = get("http://localhost"); this.filter.filter(exchange, this.chain).block(); assertThat(statusCode(exchange)).isEqualTo(302); assertThat(redirectedUrl(exchange)).isEqualTo("https://localhost"); } @Test public void filterWhenExchangeIsSecureThenNoRedirect() { given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty()); ServerWebExchange exchange = get("https://localhost"); this.filter.filter(exchange, this.chain).block(); assertThat(exchange.getResponse().getStatusCode()).isNull(); } @Test public void filterWhenExchangeMismatchesThenNoRedirect() { given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty()); ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class); given(matcher.matches(any(ServerWebExchange.class))) .willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); this.filter.setRequiresHttpsRedirectMatcher(matcher); ServerWebExchange exchange = get("http://localhost:8080"); this.filter.filter(exchange, this.chain).block(); assertThat(exchange.getResponse().getStatusCode()).isNull(); } @Test public void filterWhenExchangeMatchesAndRequestIsInsecureThenRedirects() { given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty()); ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class); given(matcher.matches(any(ServerWebExchange.class))).willReturn(ServerWebExchangeMatcher.MatchResult.match()); this.filter.setRequiresHttpsRedirectMatcher(matcher); ServerWebExchange exchange = get("http://localhost:8080"); this.filter.filter(exchange, this.chain).block(); assertThat(statusCode(exchange)).isEqualTo(302); assertThat(redirectedUrl(exchange)).isEqualTo("https://localhost:8443"); verify(matcher).matches(any(ServerWebExchange.class)); } @Test public void filterWhenRequestIsInsecureThenPortMapperRemapsPort() { given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty()); PortMapper portMapper = mock(PortMapper.class); given(portMapper.lookupHttpsPort(314)).willReturn(159); this.filter.setPortMapper(portMapper); ServerWebExchange exchange = get("http://localhost:314"); this.filter.filter(exchange, this.chain).block(); assertThat(statusCode(exchange)).isEqualTo(302); assertThat(redirectedUrl(exchange)).isEqualTo("https://localhost:159"); verify(portMapper).lookupHttpsPort(314); } @Test public void filterWhenRequestIsInsecureAndNoPortMappingThenThrowsIllegalState() { given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty()); ServerWebExchange exchange = get("http://localhost:1234"); assertThatIllegalStateException().isThrownBy(() -> this.filter.filter(exchange, this.chain).block()); } @Test public void filterWhenInsecureRequestHasAPathThenRedirects() { given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty()); ServerWebExchange exchange = get("http://localhost:8080/path/page.html?query=string"); this.filter.filter(exchange, this.chain).block(); assertThat(statusCode(exchange)).isEqualTo(302); assertThat(redirectedUrl(exchange)).isEqualTo("https://localhost:8443/path/page.html?query=string"); } @Test public void setRequiresTransportSecurityMatcherWhenSetWithNullValueThenThrowsIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequiresHttpsRedirectMatcher(null)); } @Test public void setPortMapperWhenSetWithNullValueThenThrowsIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setPortMapper(null)); } private String redirectedUrl(ServerWebExchange exchange) { return exchange.getResponse().getHeaders().get(HttpHeaders.LOCATION).iterator().next(); } private int statusCode(ServerWebExchange exchange) { return exchange.getResponse().getStatusCode().value(); } private ServerWebExchange get(String uri) { return MockServerWebExchange.from(MockServerHttpRequest.get(uri).build()); } }
6,250
39.590909
112
java
null
spring-security-main/web/src/test/java/org/springframework/security/test/web/CodecTestUtils.java
/* * Copyright 2002-2022 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.test.web; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import org.springframework.security.crypto.codec.Hex; import org.springframework.util.DigestUtils; public final class CodecTestUtils { private CodecTestUtils() { } public static String encodeBase64(String unencoded) { return Base64.getEncoder().encodeToString(unencoded.getBytes()); } public static String encodeBase64(byte[] unencoded) { return Base64.getEncoder().encodeToString(unencoded); } public static String decodeBase64(String encoded) { return new String(Base64.getDecoder().decode(encoded)); } public static boolean isBase64(byte[] arrayOctet) { try { Base64.getMimeDecoder().decode(arrayOctet); return true; } catch (Exception ex) { return false; } } public static String md5Hex(String data) { return DigestUtils.md5DigestAsHex(data.getBytes()); } public static String algorithmHex(String algorithmName, String data) { try { MessageDigest digest = MessageDigest.getInstance(algorithmName); return new String(Hex.encode(digest.digest(data.getBytes()))); } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException("No " + algorithmName + " algorithm available!"); } } }
1,939
27.115942
84
java
null
spring-security-main/web/src/test/java/org/springframework/security/test/web/reactive/server/WebTestHandler.java
/* * Copyright 2002-2017 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.test.web.reactive.server; import java.util.Arrays; import reactor.core.publisher.Mono; import org.springframework.mock.http.server.reactive.MockServerHttpRequest.BaseBuilder; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebHandler; import org.springframework.web.server.handler.FilteringWebHandler; /** * @author Rob Winch * @since 5.0 */ public final class WebTestHandler { private final MockWebHandler webHandler = new MockWebHandler(); private final WebHandler handler; private WebTestHandler(WebFilter... filters) { this.handler = new FilteringWebHandler(this.webHandler, Arrays.asList(filters)); } public WebHandlerResult exchange(BaseBuilder<?> baseBuilder) { ServerWebExchange exchange = MockServerWebExchange.from(baseBuilder.build()); return exchange(exchange); } public WebHandlerResult exchange(ServerWebExchange exchange) { this.handler.handle(exchange).block(); return new WebHandlerResult(this.webHandler.exchange); } public static WebTestHandler bindToWebFilters(WebFilter... filters) { return new WebTestHandler(filters); } public static final class WebHandlerResult { private final ServerWebExchange exchange; private WebHandlerResult(ServerWebExchange exchange) { this.exchange = exchange; } public ServerWebExchange getExchange() { return this.exchange; } } static class MockWebHandler implements WebHandler { private ServerWebExchange exchange; @Override public Mono<Void> handle(ServerWebExchange exchange) { this.exchange = exchange; return Mono.empty(); } } }
2,387
27.094118
87
java
null
spring-security-main/web/src/test/java/org/springframework/security/test/web/reactive/server/WebTestClientBuilder.java
/* * Copyright 2002-2017 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.test.web.reactive.server; import org.springframework.http.HttpStatus; import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.WebFilterChainProxy; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.Builder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.WebFilter; /** * Provides a convenient mechanism for running {@link WebTestClient} against * {@link WebFilter} * * @author Rob Winch * @since 5.0 * */ public final class WebTestClientBuilder { private WebTestClientBuilder() { } public static Builder bindToWebFilters(WebFilter... webFilters) { return WebTestClient.bindToController(new Http200RestController()).webFilter(webFilters).configureClient(); } public static Builder bindToWebFilters(SecurityWebFilterChain securityWebFilterChain) { return bindToWebFilters(new WebFilterChainProxy(securityWebFilterChain)); } public static Builder bindToControllerAndWebFilters(Class<?> controller, WebFilter... webFilters) { return WebTestClient.bindToController(controller).webFilter(webFilters).configureClient(); } public static Builder bindToControllerAndWebFilters(Class<?> controller, SecurityWebFilterChain securityWebFilterChain) { return bindToControllerAndWebFilters(controller, new WebFilterChainProxy(securityWebFilterChain)); } @RestController public static class Http200RestController { @RequestMapping("/**") @ResponseStatus(HttpStatus.OK) public String ok() { return "ok"; } } }
2,429
33.225352
109
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/SecurityFilterChain.java
/* * Copyright 2002-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 * * 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; import java.util.List; import jakarta.servlet.Filter; import jakarta.servlet.http.HttpServletRequest; /** * Defines a filter chain which is capable of being matched against an * {@code HttpServletRequest}. in order to decide whether it applies to that request. * <p> * Used to configure a {@code FilterChainProxy}. * * @author Luke Taylor * @since 3.1 */ public interface SecurityFilterChain { boolean matches(HttpServletRequest request); List<Filter> getFilters(); }
1,149
27.75
85
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/package-info.java
/* * Copyright 2002-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 * * 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. */ /** * Spring Security's web security module. Classes which have a dependency on the Servlet * API can be found here. */ package org.springframework.security.web;
788
34.863636
88
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/PortMapperImpl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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; import java.util.HashMap; import java.util.Map; import org.springframework.util.Assert; /** * Concrete implementation of {@link PortMapper} that obtains HTTP:HTTPS pairs from the * application context. * <p> * By default the implementation will assume 80:443 and 8080:8443 are HTTP:HTTPS pairs * respectively. If different pairs are required, use {@link #setPortMappings(Map)}. * * @author Ben Alex * @author colin sampaleanu */ public class PortMapperImpl implements PortMapper { private final Map<Integer, Integer> httpsPortMappings; public PortMapperImpl() { this.httpsPortMappings = new HashMap<>(); this.httpsPortMappings.put(80, 443); this.httpsPortMappings.put(8080, 8443); } /** * Returns the translated (Integer -&gt; Integer) version of the original port mapping * specified via setHttpsPortMapping() */ public Map<Integer, Integer> getTranslatedPortMappings() { return this.httpsPortMappings; } @Override public Integer lookupHttpPort(Integer httpsPort) { for (Integer httpPort : this.httpsPortMappings.keySet()) { if (this.httpsPortMappings.get(httpPort).equals(httpsPort)) { return httpPort; } } return null; } @Override public Integer lookupHttpsPort(Integer httpPort) { return this.httpsPortMappings.get(httpPort); } /** * Set to override the default HTTP port to HTTPS port mappings of 80:443, and * 8080:8443. In a Spring XML ApplicationContext, a definition would look something * like this: * * <pre> * &lt;property name="portMappings"&gt; * &lt;map&gt; * &lt;entry key="80"&gt;&lt;value&gt;443&lt;/value&gt;&lt;/entry&gt; * &lt;entry key="8080"&gt;&lt;value&gt;8443&lt;/value&gt;&lt;/entry&gt; * &lt;/map&gt; * &lt;/property&gt; * </pre> * @param newMappings A Map consisting of String keys and String values, where for * each entry the key is the string representation of an integer HTTP port number, and * the value is the string representation of the corresponding integer HTTPS port * number. * @throws IllegalArgumentException if input map does not consist of String keys and * values, each representing an integer port number in the range 1-65535 for that * mapping. */ public void setPortMappings(Map<String, String> newMappings) { Assert.notNull(newMappings, "A valid list of HTTPS port mappings must be provided"); this.httpsPortMappings.clear(); for (Map.Entry<String, String> entry : newMappings.entrySet()) { Integer httpPort = Integer.valueOf(entry.getKey()); Integer httpsPort = Integer.valueOf(entry.getValue()); Assert.isTrue(isInPortRange(httpPort) && isInPortRange(httpsPort), () -> "one or both ports out of legal range: " + httpPort + ", " + httpsPort); this.httpsPortMappings.put(httpPort, httpsPort); } Assert.isTrue(!this.httpsPortMappings.isEmpty(), "must map at least one port"); } private boolean isInPortRange(int port) { return port >= 1 && port <= 65535; } }
3,644
33.386792
87
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/FilterChainProxy.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.web.firewall.FirewalledRequest; import org.springframework.security.web.firewall.HttpFirewall; import org.springframework.security.web.firewall.HttpStatusRequestRejectedHandler; import org.springframework.security.web.firewall.RequestRejectedException; import org.springframework.security.web.firewall.RequestRejectedHandler; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.security.web.util.ThrowableAnalyzer; import org.springframework.security.web.util.UrlUtils; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.filter.GenericFilterBean; /** * Delegates {@code Filter} requests to a list of Spring-managed filter beans. As of * version 2.0, you shouldn't need to explicitly configure a {@code FilterChainProxy} bean * in your application context unless you need very fine control over the filter chain * contents. Most cases should be adequately covered by the default * {@code <security:http />} namespace configuration options. * <p> * The {@code FilterChainProxy} is linked into the servlet container filter chain by * adding a standard Spring {@link DelegatingFilterProxy} declaration in the application * {@code web.xml} file. * * <h2>Configuration</h2> * <p> * As of version 3.1, {@code FilterChainProxy} is configured using a list of * {@link SecurityFilterChain} instances, each of which contains a {@link RequestMatcher} * and a list of filters which should be applied to matching requests. Most applications * will only contain a single filter chain, and if you are using the namespace, you don't * have to set the chains explicitly. If you require finer-grained control, you can make * use of the {@code <filter-chain>} namespace element. This defines a URI pattern and the * list of filters (as comma-separated bean names) which should be applied to requests * which match the pattern. An example configuration might look like this: * * <pre> * &lt;bean id="myfilterChainProxy" class="org.springframework.security.web.FilterChainProxy"&gt; * &lt;constructor-arg&gt; * &lt;util:list&gt; * &lt;security:filter-chain pattern="/do/not/filter*" filters="none"/&gt; * &lt;security:filter-chain pattern="/**" filters="filter1,filter2,filter3"/&gt; * &lt;/util:list&gt; * &lt;/constructor-arg&gt; * &lt;/bean&gt; * </pre> * * The names "filter1", "filter2", "filter3" should be the bean names of {@code Filter} * instances defined in the application context. The order of the names defines the order * in which the filters will be applied. As shown above, use of the value "none" for the * "filters" can be used to exclude a request pattern from the security filter chain * entirely. Please consult the security namespace schema file for a full list of * available configuration options. * * <h2>Request Handling</h2> * <p> * Each possible pattern that the {@code FilterChainProxy} should service must be entered. * The first match for a given request will be used to define all of the {@code Filter}s * that apply to that request. This means you must put most specific matches at the top of * the list, and ensure all {@code Filter}s that should apply for a given matcher are * entered against the respective entry. The {@code FilterChainProxy} will not iterate * through the remainder of the map entries to locate additional {@code Filter}s. * <p> * {@code FilterChainProxy} respects normal handling of {@code Filter}s that elect not to * call * {@link jakarta.servlet.Filter#doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain)} * , in that the remainder of the original or {@code FilterChainProxy}-declared filter * chain will not be called. * * <h3>Request Firewalling</h3> * * An {@link HttpFirewall} instance is used to validate incoming requests and create a * wrapped request which provides consistent path values for matching against. See * {@link StrictHttpFirewall}, for more information on the type of attacks which the * default implementation protects against. A custom implementation can be injected to * provide stricter control over the request contents or if an application needs to * support certain types of request which are rejected by default. * <p> * Note that this means that you must use the Spring Security filters in combination with * a {@code FilterChainProxy} if you want this protection. Don't define them explicitly in * your {@code web.xml} file. * <p> * {@code FilterChainProxy} will use the firewall instance to obtain both request and * response objects which will be fed down the filter chain, so it is also possible to use * this functionality to control the functionality of the response. When the request has * passed through the security filter chain, the {@code reset} method will be called. With * the default implementation this means that the original values of {@code servletPath} * and {@code pathInfo} will be returned thereafter, instead of the modified ones used for * security pattern matching. * <p> * Since this additional wrapping functionality is performed by the * {@code FilterChainProxy}, we don't recommend that you use multiple instances in the * same filter chain. It shouldn't be considered purely as a utility for wrapping filter * beans in a single {@code Filter} instance. * * <h2>Filter Lifecycle</h2> * <p> * Note the {@code Filter} lifecycle mismatch between the servlet container and IoC * container. As described in the {@link DelegatingFilterProxy} Javadocs, we recommend you * allow the IoC container to manage the lifecycle instead of the servlet container. * {@code FilterChainProxy} does not invoke the standard filter lifecycle methods on any * filter beans that you add to the application context. * * @author Carlos Sanchez * @author Ben Alex * @author Luke Taylor * @author Rob Winch */ public class FilterChainProxy extends GenericFilterBean { private static final Log logger = LogFactory.getLog(FilterChainProxy.class); private static final String FILTER_APPLIED = FilterChainProxy.class.getName().concat(".APPLIED"); private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private List<SecurityFilterChain> filterChains; private FilterChainValidator filterChainValidator = new NullFilterChainValidator(); private HttpFirewall firewall = new StrictHttpFirewall(); private RequestRejectedHandler requestRejectedHandler = new HttpStatusRequestRejectedHandler(); private ThrowableAnalyzer throwableAnalyzer = new ThrowableAnalyzer(); private FilterChainDecorator filterChainDecorator = new VirtualFilterChainDecorator(); public FilterChainProxy() { } public FilterChainProxy(SecurityFilterChain chain) { this(Arrays.asList(chain)); } public FilterChainProxy(List<SecurityFilterChain> filterChains) { this.filterChains = filterChains; } @Override public void afterPropertiesSet() { this.filterChainValidator.validate(this); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean clearContext = request.getAttribute(FILTER_APPLIED) == null; if (!clearContext) { doFilterInternal(request, response, chain); return; } try { request.setAttribute(FILTER_APPLIED, Boolean.TRUE); doFilterInternal(request, response, chain); } catch (Exception ex) { Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex); Throwable requestRejectedException = this.throwableAnalyzer .getFirstThrowableOfType(RequestRejectedException.class, causeChain); if (!(requestRejectedException instanceof RequestRejectedException)) { throw ex; } this.requestRejectedHandler.handle((HttpServletRequest) request, (HttpServletResponse) response, (RequestRejectedException) requestRejectedException); } finally { this.securityContextHolderStrategy.clearContext(); request.removeAttribute(FILTER_APPLIED); } } private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { FirewalledRequest firewallRequest = this.firewall.getFirewalledRequest((HttpServletRequest) request); HttpServletResponse firewallResponse = this.firewall.getFirewalledResponse((HttpServletResponse) response); List<Filter> filters = getFilters(firewallRequest); if (filters == null || filters.size() == 0) { if (logger.isTraceEnabled()) { logger.trace(LogMessage.of(() -> "No security for " + requestLine(firewallRequest))); } firewallRequest.reset(); this.filterChainDecorator.decorate(chain).doFilter(firewallRequest, firewallResponse); return; } if (logger.isDebugEnabled()) { logger.debug(LogMessage.of(() -> "Securing " + requestLine(firewallRequest))); } FilterChain reset = (req, res) -> { if (logger.isDebugEnabled()) { logger.debug(LogMessage.of(() -> "Secured " + requestLine(firewallRequest))); } // Deactivate path stripping as we exit the security filter chain firewallRequest.reset(); chain.doFilter(req, res); }; this.filterChainDecorator.decorate(reset, filters).doFilter(firewallRequest, firewallResponse); } /** * Returns the first filter chain matching the supplied URL. * @param request the request to match * @return an ordered array of Filters defining the filter chain */ private List<Filter> getFilters(HttpServletRequest request) { int count = 0; for (SecurityFilterChain chain : this.filterChains) { if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Trying to match request against %s (%d/%d)", chain, ++count, this.filterChains.size())); } if (chain.matches(request)) { return chain.getFilters(); } } return null; } /** * Convenience method, mainly for testing. * @param url the URL * @return matching filter list */ public List<Filter> getFilters(String url) { return getFilters(this.firewall.getFirewalledRequest(new FilterInvocation(url, "GET").getRequest())); } /** * @return the list of {@code SecurityFilterChain}s which will be matched against and * applied to incoming requests. */ public List<SecurityFilterChain> getFilterChains() { return Collections.unmodifiableList(this.filterChains); } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * Used (internally) to specify a validation strategy for the filters in each * configured chain. * @param filterChainValidator the validator instance which will be invoked on during * initialization to check the {@code FilterChainProxy} instance. */ public void setFilterChainValidator(FilterChainValidator filterChainValidator) { this.filterChainValidator = filterChainValidator; } /** * Used to decorate the original {@link FilterChain} for each request * * <p> * By default, this decorates the filter chain with a {@link VirtualFilterChain} that * iterates through security filters and then delegates to the original chain * @param filterChainDecorator the strategy for constructing the filter chain * @since 6.0 */ public void setFilterChainDecorator(FilterChainDecorator filterChainDecorator) { Assert.notNull(filterChainDecorator, "filterChainDecorator cannot be null"); this.filterChainDecorator = filterChainDecorator; } /** * Sets the "firewall" implementation which will be used to validate and wrap (or * potentially reject) the incoming requests. The default implementation should be * satisfactory for most requirements. * @param firewall */ public void setFirewall(HttpFirewall firewall) { this.firewall = firewall; } /** * Sets the {@link RequestRejectedHandler} to be used for requests rejected by the * firewall. * @param requestRejectedHandler the {@link RequestRejectedHandler} * @since 5.2 */ public void setRequestRejectedHandler(RequestRejectedHandler requestRejectedHandler) { Assert.notNull(requestRejectedHandler, "requestRejectedHandler may not be null"); this.requestRejectedHandler = requestRejectedHandler; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("FilterChainProxy["); sb.append("Filter Chains: "); sb.append(this.filterChains); sb.append("]"); return sb.toString(); } private static String requestLine(HttpServletRequest request) { return request.getMethod() + " " + UrlUtils.buildRequestUrl(request); } /** * Internal {@code FilterChain} implementation that is used to pass a request through * the additional internal list of filters which match the request. */ private static final class VirtualFilterChain implements FilterChain { private final FilterChain originalChain; private final List<Filter> additionalFilters; private final int size; private int currentPosition = 0; private VirtualFilterChain(FilterChain chain, List<Filter> additionalFilters) { this.originalChain = chain; this.additionalFilters = additionalFilters; this.size = additionalFilters.size(); } @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (this.currentPosition == this.size) { this.originalChain.doFilter(request, response); return; } this.currentPosition++; Filter nextFilter = this.additionalFilters.get(this.currentPosition - 1); if (logger.isTraceEnabled()) { String name = nextFilter.getClass().getSimpleName(); logger.trace(LogMessage.format("Invoking %s (%d/%d)", name, this.currentPosition, this.size)); } nextFilter.doFilter(request, response, this); } } public interface FilterChainValidator { void validate(FilterChainProxy filterChainProxy); } private static class NullFilterChainValidator implements FilterChainValidator { @Override public void validate(FilterChainProxy filterChainProxy) { } } /** * A strategy for decorating the provided filter chain with one that accounts for the * {@link SecurityFilterChain} for a given request. * * @author Josh Cummings * @since 6.0 */ public interface FilterChainDecorator { /** * Provide a new {@link FilterChain} that accounts for needed security * considerations when there are no security filters. * @param original the original {@link FilterChain} * @return a security-enabled {@link FilterChain} */ default FilterChain decorate(FilterChain original) { return decorate(original, Collections.emptyList()); } /** * Provide a new {@link FilterChain} that accounts for the provided filters as * well as teh original filter chain. * @param original the original {@link FilterChain} * @param filters the security filters * @return a security-enabled {@link FilterChain} that includes the provided * filters */ FilterChain decorate(FilterChain original, List<Filter> filters); } /** * A {@link FilterChainDecorator} that uses the {@link VirtualFilterChain} * * @author Josh Cummings * @since 6.0 */ public static final class VirtualFilterChainDecorator implements FilterChainDecorator { /** * {@inheritDoc} */ @Override public FilterChain decorate(FilterChain original) { return original; } /** * {@inheritDoc} */ @Override public FilterChain decorate(FilterChain original, List<Filter> filters) { return new VirtualFilterChain(original, filters); } } }
17,487
37.776053
136
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/ObservationFilterChainDecorator.java
/* * Copyright 2002-2023 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; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import io.micrometer.common.KeyValue; import io.micrometer.common.KeyValues; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationConvention; import io.micrometer.observation.ObservationRegistry; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.util.StringUtils; /** * A {@link org.springframework.security.web.FilterChainProxy.FilterChainDecorator} that * wraps the chain in before and after observations * * @author Josh Cummings * @since 6.0 */ public final class ObservationFilterChainDecorator implements FilterChainProxy.FilterChainDecorator { private static final Log logger = LogFactory.getLog(FilterChainProxy.class); private static final String ATTRIBUTE = ObservationFilterChainDecorator.class + ".observation"; static final String UNSECURED_OBSERVATION_NAME = "spring.security.http.unsecured.requests"; static final String SECURED_OBSERVATION_NAME = "spring.security.http.secured.requests"; private final ObservationRegistry registry; public ObservationFilterChainDecorator(ObservationRegistry registry) { this.registry = registry; } @Override public FilterChain decorate(FilterChain original) { return wrapUnsecured(original); } @Override public FilterChain decorate(FilterChain original, List<Filter> filters) { return new VirtualFilterChain(wrapSecured(original), wrap(filters)); } private FilterChain wrapSecured(FilterChain original) { return (req, res) -> { AroundFilterObservation parent = observation((HttpServletRequest) req); Observation observation = Observation.createNotStarted(SECURED_OBSERVATION_NAME, this.registry) .contextualName("secured request"); parent.wrap(FilterObservation.create(observation).wrap(original)).doFilter(req, res); }; } private FilterChain wrapUnsecured(FilterChain original) { return (req, res) -> { Observation observation = Observation.createNotStarted(UNSECURED_OBSERVATION_NAME, this.registry) .contextualName("unsecured request"); FilterObservation.create(observation).wrap(original).doFilter(req, res); }; } private List<ObservationFilter> wrap(List<Filter> filters) { int size = filters.size(); List<ObservationFilter> observableFilters = new ArrayList<>(); int position = 1; for (Filter filter : filters) { observableFilters.add(new ObservationFilter(this.registry, filter, position, size)); position++; } return observableFilters; } static AroundFilterObservation observation(HttpServletRequest request) { return (AroundFilterObservation) request.getAttribute(ATTRIBUTE); } private static final class VirtualFilterChain implements FilterChain { private final FilterChain originalChain; private final List<ObservationFilter> additionalFilters; private final int size; private int currentPosition = 0; private VirtualFilterChain(FilterChain chain, List<ObservationFilter> additionalFilters) { this.originalChain = chain; this.additionalFilters = additionalFilters; this.size = additionalFilters.size(); } @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (this.currentPosition == this.size) { this.originalChain.doFilter(request, response); return; } this.currentPosition++; ObservationFilter nextFilter = this.additionalFilters.get(this.currentPosition - 1); if (logger.isTraceEnabled()) { String name = nextFilter.getName(); logger.trace(LogMessage.format("Invoking %s (%d/%d)", name, this.currentPosition, this.size)); } nextFilter.doFilter(request, response, this); } } static final class ObservationFilter implements Filter { private static final Map<String, String> OBSERVATION_NAMES = new HashMap<>(); static { OBSERVATION_NAMES.put("DisableEncodeUrlFilter", "session.url-encoding"); OBSERVATION_NAMES.put("ForceEagerSessionCreationFilter", "session.eager-create"); OBSERVATION_NAMES.put("ChannelProcessingFilter", "access.channel"); OBSERVATION_NAMES.put("WebAsyncManagerIntegrationFilter", "context.async"); OBSERVATION_NAMES.put("SecurityContextHolderFilter", "context.holder"); OBSERVATION_NAMES.put("SecurityContextPersistenceFilter", "context.management"); OBSERVATION_NAMES.put("HeaderWriterFilter", "header"); OBSERVATION_NAMES.put("CorsFilter", "cors"); OBSERVATION_NAMES.put("CsrfFilter", "csrf"); OBSERVATION_NAMES.put("LogoutFilter", "logout"); OBSERVATION_NAMES.put("OAuth2AuthorizationRequestRedirectFilter", "oauth2.authnrequest"); OBSERVATION_NAMES.put("Saml2WebSsoAuthenticationRequestFilter", "saml2.authnrequest"); OBSERVATION_NAMES.put("X509AuthenticationFilter", "authentication.x509"); OBSERVATION_NAMES.put("J2eePreAuthenticatedProcessingFilter", "preauthentication.j2ee"); OBSERVATION_NAMES.put("RequestHeaderAuthenticationFilter", "preauthentication.header"); OBSERVATION_NAMES.put("RequestAttributeAuthenticationFilter", "preauthentication.attribute"); OBSERVATION_NAMES.put("WebSpherePreAuthenticatedProcessingFilter", "preauthentication.websphere"); OBSERVATION_NAMES.put("CasAuthenticationFilter", "cas.authentication"); OBSERVATION_NAMES.put("OAuth2LoginAuthenticationFilter", "oauth2.authentication"); OBSERVATION_NAMES.put("Saml2WebSsoAuthenticationFilter", "saml2.authentication"); OBSERVATION_NAMES.put("UsernamePasswordAuthenticationFilter", "authentication.form"); OBSERVATION_NAMES.put("DefaultLoginPageGeneratingFilter", "page.login"); OBSERVATION_NAMES.put("DefaultLogoutPageGeneratingFilter", "page.logout"); OBSERVATION_NAMES.put("ConcurrentSessionFilter", "session.concurrent"); OBSERVATION_NAMES.put("DigestAuthenticationFilter", "authentication.digest"); OBSERVATION_NAMES.put("BearerTokenAuthenticationFilter", "authentication.bearer"); OBSERVATION_NAMES.put("BasicAuthenticationFilter", "authentication.basic"); OBSERVATION_NAMES.put("RequestCacheAwareFilter", "requestcache"); OBSERVATION_NAMES.put("SecurityContextHolderAwareRequestFilter", "context.servlet"); OBSERVATION_NAMES.put("JaasApiIntegrationFilter", "jaas"); OBSERVATION_NAMES.put("RememberMeAuthenticationFilter", "authentication.rememberme"); OBSERVATION_NAMES.put("AnonymousAuthenticationFilter", "authentication.anonymous"); OBSERVATION_NAMES.put("OAuth2AuthorizationCodeGrantFilter", "oauth2.client.code"); OBSERVATION_NAMES.put("SessionManagementFilter", "session.management"); OBSERVATION_NAMES.put("ExceptionTranslationFilter", "access.exceptions"); OBSERVATION_NAMES.put("FilterSecurityInterceptor", "access.request"); OBSERVATION_NAMES.put("AuthorizationFilter", "authorization"); OBSERVATION_NAMES.put("SwitchUserFilter", "authentication.switch"); } private final ObservationRegistry registry; private final FilterChainObservationConvention convention = new FilterChainObservationConvention(); private final Filter filter; private final String name; private final String eventName; private final int position; private final int size; ObservationFilter(ObservationRegistry registry, Filter filter, int position, int size) { this.registry = registry; this.filter = filter; this.name = filter.getClass().getSimpleName(); this.position = position; this.size = size; this.eventName = eventName(this.name); } private String eventName(String className) { String eventName = OBSERVATION_NAMES.get(className); return (eventName != null) ? eventName : className; } String getName() { return this.name; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (this.position == 1) { AroundFilterObservation parent = parent((HttpServletRequest) request); parent.wrap(this::wrapFilter).doFilter(request, response, chain); } else { wrapFilter(request, response, chain); } } private void wrapFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { AroundFilterObservation parent = observation((HttpServletRequest) request); if (parent.before().getContext() instanceof FilterChainObservationContext parentBefore) { parentBefore.setChainSize(this.size); parentBefore.setFilterName(this.name); parentBefore.setChainPosition(this.position); } parent.before().event(Observation.Event.of(this.eventName + ".before", "before " + this.name)); this.filter.doFilter(request, response, chain); parent.start(); if (parent.after().getContext() instanceof FilterChainObservationContext parentAfter) { parentAfter.setChainSize(this.size); parentAfter.setFilterName(this.name); parentAfter.setChainPosition(this.size - this.position + 1); } parent.after().event(Observation.Event.of(this.eventName + ".after", "after " + this.name)); } private AroundFilterObservation parent(HttpServletRequest request) { FilterChainObservationContext beforeContext = FilterChainObservationContext.before(); FilterChainObservationContext afterContext = FilterChainObservationContext.after(); Observation before = Observation.createNotStarted(this.convention, () -> beforeContext, this.registry); Observation after = Observation.createNotStarted(this.convention, () -> afterContext, this.registry); AroundFilterObservation parent = AroundFilterObservation.create(before, after); request.setAttribute(ATTRIBUTE, parent); return parent; } } interface AroundFilterObservation extends FilterObservation { AroundFilterObservation NOOP = new AroundFilterObservation() { }; static AroundFilterObservation create(Observation before, Observation after) { if (before.isNoop() || after.isNoop()) { return NOOP; } return new SimpleAroundFilterObservation(before, after); } default Observation before() { return Observation.NOOP; } default Observation after() { return Observation.NOOP; } class SimpleAroundFilterObservation implements AroundFilterObservation { private final ObservationReference before; private final ObservationReference after; private final AtomicReference<ObservationReference> reference = new AtomicReference<>( ObservationReference.NOOP); SimpleAroundFilterObservation(Observation before, Observation after) { this.before = new ObservationReference(before); this.after = new ObservationReference(after); } @Override public void start() { if (this.reference.compareAndSet(ObservationReference.NOOP, this.before)) { this.before.start(); return; } if (this.reference.compareAndSet(this.before, this.after)) { this.before.stop(); this.after.start(); } } @Override public void error(Throwable ex) { this.reference.get().error(ex); } @Override public void stop() { this.reference.get().stop(); } @Override public Filter wrap(Filter filter) { return (request, response, chain) -> { start(); try { filter.doFilter(request, response, chain); } catch (Throwable ex) { error(ex); throw ex; } finally { stop(); } }; } @Override public FilterChain wrap(FilterChain chain) { return (request, response) -> { stop(); try { chain.doFilter(request, response); } finally { start(); } }; } @Override public Observation before() { return this.before.observation; } @Override public Observation after() { return this.after.observation; } private static final class ObservationReference { private static final ObservationReference NOOP = new ObservationReference(Observation.NOOP); private final AtomicInteger state = new AtomicInteger(0); private final Observation observation; private volatile Observation.Scope scope; private ObservationReference(Observation observation) { this.observation = observation; this.scope = Observation.Scope.NOOP; } private void start() { if (this.state.compareAndSet(0, 1)) { this.observation.start(); this.scope = this.observation.openScope(); } } private void error(Throwable error) { if (this.state.get() == 1) { this.scope.getCurrentObservation().error(error); } } private void stop() { if (this.state.compareAndSet(1, 2)) { this.scope.close(); this.scope.getCurrentObservation().stop(); } } } } } interface FilterObservation { FilterObservation NOOP = new FilterObservation() { }; static FilterObservation create(Observation observation) { if (observation.isNoop()) { return NOOP; } return new SimpleFilterObservation(observation); } default void start() { } default void error(Throwable ex) { } default void stop() { } default Filter wrap(Filter filter) { return filter; } default FilterChain wrap(FilterChain chain) { return chain; } class SimpleFilterObservation implements FilterObservation { private final Observation observation; SimpleFilterObservation(Observation observation) { this.observation = observation; } @Override public void start() { this.observation.start(); } @Override public void error(Throwable ex) { this.observation.error(ex); } @Override public void stop() { this.observation.stop(); } @Override public Filter wrap(Filter filter) { if (this.observation.isNoop()) { return filter; } return (request, response, chain) -> { this.observation.start(); try (Observation.Scope scope = this.observation.openScope()) { filter.doFilter(request, response, chain); } catch (Throwable ex) { this.observation.error(ex); throw ex; } finally { this.observation.stop(); } }; } @Override public FilterChain wrap(FilterChain chain) { if (this.observation.isNoop()) { return chain; } return (request, response) -> { this.observation.start(); try (Observation.Scope scope = this.observation.openScope()) { chain.doFilter(request, response); } catch (Throwable ex) { this.observation.error(ex); throw ex; } finally { this.observation.stop(); } }; } } } static final class FilterChainObservationContext extends Observation.Context { private final String filterSection; private String filterName; private int chainPosition; private int chainSize; private FilterChainObservationContext(String filterSection) { this.filterSection = filterSection; setContextualName("security filterchain " + filterSection); } static FilterChainObservationContext before() { return new FilterChainObservationContext("before"); } static FilterChainObservationContext after() { return new FilterChainObservationContext("after"); } String getFilterSection() { return this.filterSection; } String getFilterName() { return this.filterName; } void setFilterName(String filterName) { this.filterName = filterName; } int getChainPosition() { return this.chainPosition; } void setChainPosition(int chainPosition) { this.chainPosition = chainPosition; } int getChainSize() { return this.chainSize; } void setChainSize(int chainSize) { this.chainSize = chainSize; } } static final class FilterChainObservationConvention implements ObservationConvention<FilterChainObservationContext> { static final String CHAIN_OBSERVATION_NAME = "spring.security.filterchains"; private static final String CHAIN_POSITION_NAME = "spring.security.filterchain.position"; private static final String CHAIN_SIZE_NAME = "spring.security.filterchain.size"; private static final String FILTER_SECTION_NAME = "security.security.reached.filter.section"; private static final String FILTER_NAME = "spring.security.reached.filter.name"; @Override public String getName() { return CHAIN_OBSERVATION_NAME; } @Override public String getContextualName(FilterChainObservationContext context) { return "security filterchain " + context.getFilterSection(); } @Override public KeyValues getLowCardinalityKeyValues(FilterChainObservationContext context) { return KeyValues.of(CHAIN_SIZE_NAME, String.valueOf(context.getChainSize())) .and(CHAIN_POSITION_NAME, String.valueOf(context.getChainPosition())) .and(FILTER_SECTION_NAME, context.getFilterSection()) .and(FILTER_NAME, (StringUtils.hasText(context.getFilterName())) ? context.getFilterName() : KeyValue.NONE_VALUE); } @Override public boolean supportsContext(Observation.Context context) { return context instanceof FilterChainObservationContext; } } }
18,123
29.823129
111
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/PortMapper.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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; /** * <code>PortMapper</code> implementations provide callers with information about which * HTTP ports are associated with which HTTPS ports on the system, and vice versa. * * @author Ben Alex */ public interface PortMapper { /** * Locates the HTTP port associated with the specified HTTPS port. * <P> * Returns <code>null</code> if unknown. * </p> * @param httpsPort * @return the HTTP port or <code>null</code> if unknown */ Integer lookupHttpPort(Integer httpsPort); /** * Locates the HTTPS port associated with the specified HTTP port. * <P> * Returns <code>null</code> if unknown. * </p> * @param httpPort * @return the HTTPS port or <code>null</code> if unknown */ Integer lookupHttpsPort(Integer httpPort); }
1,427
28.75
87
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/AuthenticationEntryPoint.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.access.ExceptionTranslationFilter; /** * Used by {@link ExceptionTranslationFilter} to commence an authentication scheme. * * @author Ben Alex */ public interface AuthenticationEntryPoint { /** * Commences an authentication scheme. * <p> * <code>ExceptionTranslationFilter</code> will populate the <code>HttpSession</code> * attribute named * <code>AbstractAuthenticationProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY</code> * with the requested target URL before calling this method. * <p> * Implementations should modify the headers on the <code>ServletResponse</code> as * necessary to commence the authentication process. * @param request that resulted in an <code>AuthenticationException</code> * @param response so that the user agent can begin authentication * @param authException that caused the invocation */ void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException; }
1,956
35.924528
111
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/RedirectStrategy.java
/* * Copyright 2002-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 * * 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; import java.io.IOException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Encapsulates the redirection logic for all classes in the framework which perform * redirects. * * @author Luke Taylor * @since 3.0 */ public interface RedirectStrategy { /** * Performs a redirect to the supplied URL * @param request the current request * @param response the response to redirect * @param url the target URL to redirect to, for example "/login" */ void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException; }
1,294
29.833333
108
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/WebAttributes.java
/* * Copyright 2002-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 * * 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; import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator; /** * Well-known keys which are used to store Spring Security information in request or * session scope. * * @author Luke Taylor * @author Rob Winch * @since 3.0.3 */ public final class WebAttributes { /** * Used to cache an {@code AccessDeniedException} in the request for rendering. * * @see org.springframework.security.web.access.AccessDeniedHandlerImpl */ public static final String ACCESS_DENIED_403 = "SPRING_SECURITY_403_EXCEPTION"; /** * Used to cache an authentication-failure exception in the session. * * @see org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler */ public static final String AUTHENTICATION_EXCEPTION = "SPRING_SECURITY_LAST_EXCEPTION"; /** * Set as a request attribute to override the default * {@link WebInvocationPrivilegeEvaluator} * * @since 3.1.3 * @see WebInvocationPrivilegeEvaluator */ public static final String WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE = WebAttributes.class.getName() + ".WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE"; private WebAttributes() { } }
1,840
30.20339
104
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/DefaultRedirectStrategy.java
/* * Copyright 2002-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 * * 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; import java.io.IOException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; /** * Simple implementation of <tt>RedirectStrategy</tt> which is the default used throughout * the framework. * * @author Luke Taylor * @since 3.0 */ public class DefaultRedirectStrategy implements RedirectStrategy { protected final Log logger = LogFactory.getLog(getClass()); private boolean contextRelative; /** * Redirects the response to the supplied URL. * <p> * If <tt>contextRelative</tt> is set, the redirect value will be the value after the * request context path. Note that this will result in the loss of protocol * information (HTTP or HTTPS), so will cause problems if a redirect is being * performed to change to HTTPS, for example. */ @Override public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { String redirectUrl = calculateRedirectUrl(request.getContextPath(), url); redirectUrl = response.encodeRedirectURL(redirectUrl); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Redirecting to %s", redirectUrl)); } response.sendRedirect(redirectUrl); } protected String calculateRedirectUrl(String contextPath, String url) { if (!UrlUtils.isAbsoluteUrl(url)) { if (isContextRelative()) { return url; } return contextPath + url; } // Full URL, including http(s):// if (!isContextRelative()) { return url; } Assert.isTrue(url.contains(contextPath), "The fully qualified URL does not include context path."); // Calculate the relative URL from the fully qualified URL, minus the last // occurrence of the scheme and base context. url = url.substring(url.lastIndexOf("://") + 3); url = url.substring(url.indexOf(contextPath) + contextPath.length()); if (url.length() > 1 && url.charAt(0) == '/') { url = url.substring(1); } return url; } /** * If <tt>true</tt>, causes any redirection URLs to be calculated minus the protocol * and context path (defaults to <tt>false</tt>). */ public void setContextRelative(boolean useRelativeContext) { this.contextRelative = useRelativeContext; } /** * Returns <tt>true</tt>, if the redirection URL should be calculated minus the * protocol and context path (defaults to <tt>false</tt>). */ protected boolean isContextRelative() { return this.contextRelative; } }
3,336
32.37
116
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/FilterInvocation.java
/* * Copyright 2002-2021 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; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequestWrapper; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * Holds objects associated with a HTTP filter. * <P> * Guarantees the request and response are instances of <code>HttpServletRequest</code> * and <code>HttpServletResponse</code>, and that there are no <code>null</code> objects. * <p> * Required so that security system classes can obtain access to the filter environment, * as well as the request and response. * * @author Ben Alex * @author colin sampaleanu * @author Luke Taylor * @author Rob Winch */ public class FilterInvocation { static final FilterChain DUMMY_CHAIN = (req, res) -> { throw new UnsupportedOperationException("Dummy filter chain"); }; private FilterChain chain; private HttpServletRequest request; private HttpServletResponse response; public FilterInvocation(ServletRequest request, ServletResponse response, FilterChain chain) { Assert.isTrue(request != null && response != null && chain != null, "Cannot pass null values to constructor"); this.request = (HttpServletRequest) request; this.response = (HttpServletResponse) response; this.chain = chain; } public FilterInvocation(String servletPath, String method) { this(null, servletPath, method); } public FilterInvocation(String contextPath, String servletPath, String method) { this(contextPath, servletPath, method, null); } public FilterInvocation(String contextPath, String servletPath, String method, ServletContext servletContext) { this(contextPath, servletPath, null, null, method, servletContext); } public FilterInvocation(String contextPath, String servletPath, String pathInfo, String query, String method) { this(contextPath, servletPath, pathInfo, query, method, null); } public FilterInvocation(String contextPath, String servletPath, String pathInfo, String query, String method, ServletContext servletContext) { DummyRequest request = new DummyRequest(); contextPath = (contextPath != null) ? contextPath : "/cp"; request.setContextPath(contextPath); request.setServletPath(servletPath); request.setRequestURI(contextPath + servletPath + ((pathInfo != null) ? pathInfo : "")); request.setPathInfo(pathInfo); request.setQueryString(query); request.setMethod(method); request.setServletContext(servletContext); this.request = request; } public FilterChain getChain() { return this.chain; } /** * Indicates the URL that the user agent used for this request. * <p> * The returned URL does <b>not</b> reflect the port number determined from a * {@link org.springframework.security.web.PortResolver}. * @return the full URL of this request */ public String getFullRequestUrl() { return UrlUtils.buildFullRequestUrl(this.request); } public HttpServletRequest getHttpRequest() { return this.request; } public HttpServletResponse getHttpResponse() { return this.response; } /** * Obtains the web application-specific fragment of the URL. * @return the URL, excluding any server name, context path or servlet path */ public String getRequestUrl() { return UrlUtils.buildRequestUrl(this.request); } public HttpServletRequest getRequest() { return getHttpRequest(); } public HttpServletResponse getResponse() { return getHttpResponse(); } @Override public String toString() { if (!StringUtils.hasLength(this.request.getMethod())) { return "filter invocation [" + getRequestUrl() + "]"; } else { return "filter invocation [" + this.request.getMethod() + " " + getRequestUrl() + "]"; } } static class DummyRequest extends HttpServletRequestWrapper { private static final HttpServletRequest UNSUPPORTED_REQUEST = (HttpServletRequest) Proxy.newProxyInstance( DummyRequest.class.getClassLoader(), new Class[] { HttpServletRequest.class }, new UnsupportedOperationExceptionInvocationHandler()); private String requestURI; private String contextPath = ""; private String servletPath; private String pathInfo; private String queryString; private String method; private ServletContext servletContext; private final HttpHeaders headers = new HttpHeaders(); private final Map<String, String[]> parameters = new LinkedHashMap<>(); DummyRequest() { super(UNSUPPORTED_REQUEST); } @Override public String getCharacterEncoding() { return "UTF-8"; } @Override public Object getAttribute(String attributeName) { return null; } void setRequestURI(String requestURI) { this.requestURI = requestURI; } void setPathInfo(String pathInfo) { this.pathInfo = pathInfo; } @Override public String getRequestURI() { return this.requestURI; } void setContextPath(String contextPath) { this.contextPath = contextPath; } @Override public String getContextPath() { return this.contextPath; } void setServletPath(String servletPath) { this.servletPath = servletPath; } @Override public String getServletPath() { return this.servletPath; } void setMethod(String method) { this.method = method; } @Override public String getMethod() { return this.method; } @Override public String getPathInfo() { return this.pathInfo; } @Override public String getQueryString() { return this.queryString; } void setQueryString(String queryString) { this.queryString = queryString; } @Override public String getServerName() { return null; } @Override public String getHeader(String name) { return this.headers.getFirst(name); } @Override public Enumeration<String> getHeaders(String name) { List<String> headerList = this.headers.get(name); if (headerList == null) { return Collections.emptyEnumeration(); } return Collections.enumeration(headerList); } @Override public Enumeration<String> getHeaderNames() { return Collections.enumeration(this.headers.keySet()); } @Override public int getIntHeader(String name) { String value = this.headers.getFirst(name); if (value == null) { return -1; } return Integer.parseInt(value); } void addHeader(String name, String value) { this.headers.add(name, value); } @Override public String getParameter(String name) { String[] array = this.parameters.get(name); return (array != null && array.length > 0) ? array[0] : null; } @Override public Map<String, String[]> getParameterMap() { return Collections.unmodifiableMap(this.parameters); } @Override public Enumeration<String> getParameterNames() { return Collections.enumeration(this.parameters.keySet()); } @Override public String[] getParameterValues(String name) { return this.parameters.get(name); } void setParameter(String name, String... values) { this.parameters.put(name, values); } @Override public ServletContext getServletContext() { return this.servletContext; } void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } } static final class UnsupportedOperationExceptionInvocationHandler implements InvocationHandler { private static final float JAVA_VERSION = Float.parseFloat(System.getProperty("java.class.version", "52")); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.isDefault()) { return invokeDefaultMethod(proxy, method, args); } throw new UnsupportedOperationException(method + " is not supported"); } private Object invokeDefaultMethod(Object proxy, Method method, Object[] args) throws Throwable { if (isJdk8OrEarlier()) { return invokeDefaultMethodForJdk8(proxy, method, args); } return MethodHandles.lookup() .findSpecial(method.getDeclaringClass(), method.getName(), MethodType.methodType(method.getReturnType(), new Class[0]), method.getDeclaringClass()) .bindTo(proxy).invokeWithArguments(args); } private Object invokeDefaultMethodForJdk8(Object proxy, Method method, Object[] args) throws Throwable { Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class); constructor.setAccessible(true); Class<?> clazz = method.getDeclaringClass(); return constructor.newInstance(clazz).in(clazz).unreflectSpecial(method, clazz).bindTo(proxy) .invokeWithArguments(args); } private boolean isJdk8OrEarlier() { return JAVA_VERSION <= 52; } } }
9,903
26.587744
112
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/DefaultSecurityFilterChain.java
/* * Copyright 2002-2021 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; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import jakarta.servlet.Filter; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.web.util.matcher.RequestMatcher; /** * Standard implementation of {@code SecurityFilterChain}. * * @author Luke Taylor * @since 3.1 */ public final class DefaultSecurityFilterChain implements SecurityFilterChain { private static final Log logger = LogFactory.getLog(DefaultSecurityFilterChain.class); private final RequestMatcher requestMatcher; private final List<Filter> filters; public DefaultSecurityFilterChain(RequestMatcher requestMatcher, Filter... filters) { this(requestMatcher, Arrays.asList(filters)); } public DefaultSecurityFilterChain(RequestMatcher requestMatcher, List<Filter> filters) { if (filters.isEmpty()) { logger.info(LogMessage.format("Will not secure %s", requestMatcher)); } else { logger.info(LogMessage.format("Will secure %s with %s", requestMatcher, filters)); } this.requestMatcher = requestMatcher; this.filters = new ArrayList<>(filters); } public RequestMatcher getRequestMatcher() { return this.requestMatcher; } @Override public List<Filter> getFilters() { return this.filters; } @Override public boolean matches(HttpServletRequest request) { return this.requestMatcher.matches(request); } @Override public String toString() { return this.getClass().getSimpleName() + " [RequestMatcher=" + this.requestMatcher + ", Filters=" + this.filters + "]"; } }
2,346
27.975309
114
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/RequestMatcherRedirectFilter.java
/* * Copyright 2002-2021 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; import java.io.IOException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; /** * Filter that redirects requests that match {@link RequestMatcher} to the specified URL. * * @author Evgeniy Cheban * @since 5.6 */ public final class RequestMatcherRedirectFilter extends OncePerRequestFilter { private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private final RequestMatcher requestMatcher; private final String redirectUrl; /** * Create and initialize an instance of the filter. * @param requestMatcher the request matcher * @param redirectUrl the redirect URL */ public RequestMatcherRedirectFilter(RequestMatcher requestMatcher, String redirectUrl) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); Assert.hasText(redirectUrl, "redirectUrl cannot be empty"); this.requestMatcher = requestMatcher; this.redirectUrl = redirectUrl; } /** * {@inheritDoc} */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (this.requestMatcher.matches(request)) { this.redirectStrategy.sendRedirect(request, response, this.redirectUrl); } else { filterChain.doFilter(request, response); } } }
2,260
30.402778
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/PortResolver.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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; import jakarta.servlet.ServletRequest; /** * A <code>PortResolver</code> determines the port a web request was received on. * * <P> * This interface is necessary because <code>ServletRequest.getServerPort()</code> may not * return the correct port in certain circumstances. For example, if the browser does not * construct the URL correctly after a redirect. * </p> * * @author Ben Alex */ public interface PortResolver { /** * Indicates the port the <code>ServletRequest</code> was received on. * @param request that the method should lookup the port for * @return the port the request was received on */ int getServerPort(ServletRequest request); }
1,344
31.02381
90
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/PortResolverImpl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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; import jakarta.servlet.ServletRequest; import org.springframework.util.Assert; /** * Concrete implementation of {@link PortResolver} that obtains the port from * <tt>ServletRequest.getServerPort()</tt>. * <p> * This class is capable of handling the IE bug which results in an incorrect URL being * presented in the header subsequent to a redirect to a different scheme and port where * the port is not a well-known number (ie 80 or 443). Handling involves detecting an * incorrect response from <code>ServletRequest.getServerPort()</code> for the scheme (eg * a HTTP request on 8443) and then determining the real server port (eg HTTP request is * really on 8080). The map of valid ports is obtained from the configured * {@link PortMapper}. * * @author Ben Alex */ public class PortResolverImpl implements PortResolver { private PortMapper portMapper = new PortMapperImpl(); public PortMapper getPortMapper() { return this.portMapper; } @Override public int getServerPort(ServletRequest request) { int serverPort = request.getServerPort(); String scheme = request.getScheme().toLowerCase(); Integer mappedPort = getMappedPort(serverPort, scheme); return (mappedPort != null) ? mappedPort : serverPort; } private Integer getMappedPort(int serverPort, String scheme) { if ("http".equals(scheme)) { return this.portMapper.lookupHttpPort(serverPort); } if ("https".equals(scheme)) { return this.portMapper.lookupHttpsPort(serverPort); } return null; } public void setPortMapper(PortMapper portMapper) { Assert.notNull(portMapper, "portMapper cannot be null"); this.portMapper = portMapper; } }
2,322
32.666667
89
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/SavedRequest.java
/* * Copyright 2002-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 * * 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.savedrequest; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; import jakarta.servlet.http.Cookie; /** * Encapsulates the functionality required of a cached request for both an authentication * mechanism (typically form-based login) to redirect to the original URL and for a * <tt>RequestCache</tt> to build a wrapped request, reproducing the original request * data. * * @author Luke Taylor * @since 3.0 */ public interface SavedRequest extends java.io.Serializable { /** * @return the URL for the saved request, allowing a redirect to be performed. */ String getRedirectUrl(); List<Cookie> getCookies(); String getMethod(); List<String> getHeaderValues(String name); Collection<String> getHeaderNames(); List<Locale> getLocales(); String[] getParameterValues(String name); Map<String, String[]> getParameterMap(); }
1,565
26.473684
89
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/package-info.java
/* * Copyright 2002-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 * * 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. */ /** * Classes related to the caching of an {@code HttpServletRequest} which requires * authentication. While the user is logging in, the request is cached (using the * RequestCache implementation) by the ExceptionTranslationFilter. Once the user has been * authenticated, the original request is restored following a redirect to a matching URL, * and the {@code RequestCache} is queried to obtain the original (matching) request. */ package org.springframework.security.web.savedrequest;
1,117
43.72
90
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/HttpSessionRequestCache.java
/* * Copyright 2002-2022 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.savedrequest; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.web.PortResolver; import org.springframework.security.web.PortResolverImpl; import org.springframework.security.web.util.UrlUtils; import org.springframework.security.web.util.matcher.AnyRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; /** * {@code RequestCache} which stores the {@code SavedRequest} in the HttpSession. * * The {@link DefaultSavedRequest} class is used as the implementation. * * @author Luke Taylor * @author Eddú Meléndez * @since 3.0 */ public class HttpSessionRequestCache implements RequestCache { static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST"; protected final Log logger = LogFactory.getLog(this.getClass()); private PortResolver portResolver = new PortResolverImpl(); private boolean createSessionAllowed = true; private RequestMatcher requestMatcher = AnyRequestMatcher.INSTANCE; private String sessionAttrName = SAVED_REQUEST; private String matchingRequestParameterName = "continue"; /** * Stores the current request, provided the configuration properties allow it. */ @Override public void saveRequest(HttpServletRequest request, HttpServletResponse response) { if (!this.requestMatcher.matches(request)) { if (this.logger.isTraceEnabled()) { this.logger.trace( LogMessage.format("Did not save request since it did not match [%s]", this.requestMatcher)); } return; } if (this.createSessionAllowed || request.getSession(false) != null) { // Store the HTTP request itself. Used by // AbstractAuthenticationProcessingFilter // for redirection after successful authentication (SEC-29) DefaultSavedRequest savedRequest = new DefaultSavedRequest(request, this.portResolver, this.matchingRequestParameterName); request.getSession().setAttribute(this.sessionAttrName, savedRequest); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Saved request %s to session", savedRequest.getRedirectUrl())); } } else { this.logger.trace("Did not save request since there's no session and createSessionAllowed is false"); } } @Override public SavedRequest getRequest(HttpServletRequest currentRequest, HttpServletResponse response) { HttpSession session = currentRequest.getSession(false); return (session != null) ? (SavedRequest) session.getAttribute(this.sessionAttrName) : null; } @Override public void removeRequest(HttpServletRequest currentRequest, HttpServletResponse response) { HttpSession session = currentRequest.getSession(false); if (session != null) { this.logger.trace("Removing DefaultSavedRequest from session if present"); session.removeAttribute(this.sessionAttrName); } } @Override public HttpServletRequest getMatchingRequest(HttpServletRequest request, HttpServletResponse response) { if (this.matchingRequestParameterName != null && request.getParameter(this.matchingRequestParameterName) == null) { this.logger.trace( "matchingRequestParameterName is required for getMatchingRequest to lookup a value, but not provided"); return null; } SavedRequest saved = getRequest(request, response); if (saved == null) { this.logger.trace("No saved request"); return null; } if (!matchesSavedRequest(request, saved)) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Did not match request %s to the saved one %s", UrlUtils.buildRequestUrl(request), saved)); } return null; } removeRequest(request, response); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Loaded matching saved request %s", saved.getRedirectUrl())); } return new SavedRequestAwareWrapper(saved, request); } private boolean matchesSavedRequest(HttpServletRequest request, SavedRequest savedRequest) { if (savedRequest instanceof DefaultSavedRequest) { DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) savedRequest; return defaultSavedRequest.doesRequestMatch(request, this.portResolver); } String currentUrl = UrlUtils.buildFullRequestUrl(request); return savedRequest.getRedirectUrl().equals(currentUrl); } /** * Allows selective use of saved requests for a subset of requests. By default any * request will be cached by the {@code saveRequest} method. * <p> * If set, only matching requests will be cached. * @param requestMatcher a request matching strategy which defines which requests * should be cached. */ public void setRequestMatcher(RequestMatcher requestMatcher) { this.requestMatcher = requestMatcher; } /** * If <code>true</code>, indicates that it is permitted to store the target URL and * exception information in a new <code>HttpSession</code> (the default). In * situations where you do not wish to unnecessarily create <code>HttpSession</code>s * - because the user agent will know the failed URL, such as with BASIC or Digest * authentication - you may wish to set this property to <code>false</code>. */ public void setCreateSessionAllowed(boolean createSessionAllowed) { this.createSessionAllowed = createSessionAllowed; } public void setPortResolver(PortResolver portResolver) { this.portResolver = portResolver; } /** * If the {@code sessionAttrName} property is set, the request is stored in the * session using this attribute name. Default is "SPRING_SECURITY_SAVED_REQUEST". * @param sessionAttrName a new session attribute name. * @since 4.2.1 */ public void setSessionAttrName(String sessionAttrName) { this.sessionAttrName = sessionAttrName; } /** * Specify the name of a query parameter that is added to the URL that specifies the * request cache should be checked in * {@link #getMatchingRequest(HttpServletRequest, HttpServletResponse)} * @param matchingRequestParameterName the parameter name that must be in the request * for {@link #getMatchingRequest(HttpServletRequest, HttpServletResponse)} to check * the session. Default is "continue". */ public void setMatchingRequestParameterName(String matchingRequestParameterName) { this.matchingRequestParameterName = matchingRequestParameterName; } }
7,142
37.197861
108
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/DefaultSavedRequest.java
/* * Copyright 2002-2023 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.savedrequest; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.security.web.PortResolver; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.web.util.UriComponentsBuilder; /** * Represents central information from a {@code HttpServletRequest}. * <p> * This class is used by * {@link org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter} * and {@link org.springframework.security.web.savedrequest.SavedRequestAwareWrapper} to * reproduce the request after successful authentication. An instance of this class is * stored at the time of an authentication exception by * {@link org.springframework.security.web.access.ExceptionTranslationFilter}. * <p> * <em>IMPLEMENTATION NOTE</em>: It is assumed that this object is accessed only from the * context of a single thread, so no synchronization around internal collection classes is * performed. * <p> * This class is based on code in Apache Tomcat. * * @author Craig McClanahan * @author Andrey Grebnev * @author Ben Alex * @author Luke Taylor */ public class DefaultSavedRequest implements SavedRequest { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; protected static final Log logger = LogFactory.getLog(DefaultSavedRequest.class); private static final String HEADER_IF_NONE_MATCH = "If-None-Match"; private static final String HEADER_IF_MODIFIED_SINCE = "If-Modified-Since"; private final ArrayList<SavedCookie> cookies = new ArrayList<>(); private final ArrayList<Locale> locales = new ArrayList<>(); private final Map<String, List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); private final Map<String, String[]> parameters = new TreeMap<>(); private final String contextPath; private final String method; private final String pathInfo; private final String queryString; private final String requestURI; private final String requestURL; private final String scheme; private final String serverName; private final String servletPath; private final int serverPort; private final String matchingRequestParameterName; public DefaultSavedRequest(HttpServletRequest request, PortResolver portResolver) { this(request, portResolver, null); } @SuppressWarnings("unchecked") public DefaultSavedRequest(HttpServletRequest request, PortResolver portResolver, String matchingRequestParameterName) { Assert.notNull(request, "Request required"); Assert.notNull(portResolver, "PortResolver required"); // Cookies addCookies(request.getCookies()); // Headers Enumeration<String> names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); // Skip If-Modified-Since and If-None-Match header. SEC-1412, SEC-1624. if (HEADER_IF_MODIFIED_SINCE.equalsIgnoreCase(name) || HEADER_IF_NONE_MATCH.equalsIgnoreCase(name)) { continue; } Enumeration<String> values = request.getHeaders(name); while (values.hasMoreElements()) { this.addHeader(name, values.nextElement()); } } // Locales addLocales(request.getLocales()); // Parameters addParameters(request.getParameterMap()); // Primitives this.method = request.getMethod(); this.pathInfo = request.getPathInfo(); this.queryString = request.getQueryString(); this.requestURI = request.getRequestURI(); this.serverPort = portResolver.getServerPort(request); this.requestURL = request.getRequestURL().toString(); this.scheme = request.getScheme(); this.serverName = request.getServerName(); this.contextPath = request.getContextPath(); this.servletPath = request.getServletPath(); this.matchingRequestParameterName = matchingRequestParameterName; } /** * Private constructor invoked through Builder */ private DefaultSavedRequest(Builder builder) { this.contextPath = builder.contextPath; this.method = builder.method; this.pathInfo = builder.pathInfo; this.queryString = builder.queryString; this.requestURI = builder.requestURI; this.requestURL = builder.requestURL; this.scheme = builder.scheme; this.serverName = builder.serverName; this.servletPath = builder.servletPath; this.serverPort = builder.serverPort; this.matchingRequestParameterName = builder.matchingRequestParameterName; } /** * @since 4.2 */ private void addCookies(Cookie[] cookies) { if (cookies != null) { for (Cookie cookie : cookies) { this.addCookie(cookie); } } } private void addCookie(Cookie cookie) { this.cookies.add(new SavedCookie(cookie)); } private void addHeader(String name, String value) { List<String> values = this.headers.computeIfAbsent(name, (key) -> new ArrayList<>()); values.add(value); } /** * @since 4.2 */ private void addLocales(Enumeration<Locale> locales) { while (locales.hasMoreElements()) { Locale locale = locales.nextElement(); this.addLocale(locale); } } private void addLocale(Locale locale) { this.locales.add(locale); } /** * @since 4.2 */ private void addParameters(Map<String, String[]> parameters) { if (!ObjectUtils.isEmpty(parameters)) { for (String paramName : parameters.keySet()) { Object paramValues = parameters.get(paramName); if (paramValues instanceof String[]) { this.addParameter(paramName, (String[]) paramValues); } else { logger.warn("ServletRequest.getParameterMap() returned non-String array"); } } } } private void addParameter(String name, String[] values) { this.parameters.put(name, values); } /** * Determines if the current request matches the <code>DefaultSavedRequest</code>. * <p> * All URL arguments are considered but not cookies, locales, headers or parameters. * @param request the actual request to be matched against this one * @param portResolver used to obtain the server port of the request * @return true if the request is deemed to match this one. */ public boolean doesRequestMatch(HttpServletRequest request, PortResolver portResolver) { if (!propertyEquals(this.pathInfo, request.getPathInfo())) { return false; } if (!propertyEquals(createQueryString(this.queryString, this.matchingRequestParameterName), request.getQueryString())) { return false; } if (!propertyEquals(this.requestURI, request.getRequestURI())) { return false; } if (!"GET".equals(request.getMethod()) && "GET".equals(this.method)) { // A save GET should not match an incoming non-GET method return false; } if (!propertyEquals(this.serverPort, portResolver.getServerPort(request))) { return false; } if (!propertyEquals(this.requestURL, request.getRequestURL().toString())) { return false; } if (!propertyEquals(this.scheme, request.getScheme())) { return false; } if (!propertyEquals(this.serverName, request.getServerName())) { return false; } if (!propertyEquals(this.contextPath, request.getContextPath())) { return false; } return propertyEquals(this.servletPath, request.getServletPath()); } public String getContextPath() { return this.contextPath; } @Override public List<Cookie> getCookies() { List<Cookie> cookieList = new ArrayList<>(this.cookies.size()); for (SavedCookie savedCookie : this.cookies) { cookieList.add(savedCookie.getCookie()); } return cookieList; } /** * Indicates the URL that the user agent used for this request. * @return the full URL of this request */ @Override public String getRedirectUrl() { String queryString = createQueryString(this.queryString, this.matchingRequestParameterName); return UrlUtils.buildFullRequestUrl(this.scheme, this.serverName, this.serverPort, this.requestURI, queryString); } @Override public Collection<String> getHeaderNames() { return this.headers.keySet(); } @Override public List<String> getHeaderValues(String name) { List<String> values = this.headers.get(name); return (values != null) ? values : Collections.emptyList(); } @Override public List<Locale> getLocales() { return this.locales; } @Override public String getMethod() { return this.method; } @Override public Map<String, String[]> getParameterMap() { return this.parameters; } public Collection<String> getParameterNames() { return this.parameters.keySet(); } @Override public String[] getParameterValues(String name) { return this.parameters.get(name); } public String getPathInfo() { return this.pathInfo; } public String getQueryString() { return (this.queryString); } public String getRequestURI() { return (this.requestURI); } public String getRequestURL() { return this.requestURL; } public String getScheme() { return this.scheme; } public String getServerName() { return this.serverName; } public int getServerPort() { return this.serverPort; } public String getServletPath() { return this.servletPath; } private boolean propertyEquals(Object arg1, Object arg2) { if ((arg1 == null) && (arg2 == null)) { return true; } if (arg1 == null || arg2 == null) { return false; } if (arg1.equals(arg2)) { return true; } return false; } @Override public String toString() { return "DefaultSavedRequest [" + getRedirectUrl() + "]"; } private static String createQueryString(String queryString, String matchingRequestParameterName) { if (matchingRequestParameterName == null) { return queryString; } if (queryString == null || queryString.length() == 0) { return matchingRequestParameterName; } return UriComponentsBuilder.newInstance().query(queryString).replaceQueryParam(matchingRequestParameterName) .queryParam(matchingRequestParameterName).build().getQuery(); } /** * @since 4.2 */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonPOJOBuilder(withPrefix = "set") public static class Builder { private List<SavedCookie> cookies = null; private List<Locale> locales = null; private Map<String, List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); private Map<String, String[]> parameters = new TreeMap<>(); private String contextPath; private String method; private String pathInfo; private String queryString; private String requestURI; private String requestURL; private String scheme; private String serverName; private String servletPath; private int serverPort = 80; private String matchingRequestParameterName; public Builder setCookies(List<SavedCookie> cookies) { this.cookies = cookies; return this; } public Builder setLocales(List<Locale> locales) { this.locales = locales; return this; } public Builder setHeaders(Map<String, List<String>> header) { this.headers.putAll(header); return this; } public Builder setParameters(Map<String, String[]> parameters) { this.parameters = parameters; return this; } public Builder setContextPath(String contextPath) { this.contextPath = contextPath; return this; } public Builder setMethod(String method) { this.method = method; return this; } public Builder setPathInfo(String pathInfo) { this.pathInfo = pathInfo; return this; } public Builder setQueryString(String queryString) { this.queryString = queryString; return this; } public Builder setRequestURI(String requestURI) { this.requestURI = requestURI; return this; } public Builder setRequestURL(String requestURL) { this.requestURL = requestURL; return this; } public Builder setScheme(String scheme) { this.scheme = scheme; return this; } public Builder setServerName(String serverName) { this.serverName = serverName; return this; } public Builder setServletPath(String servletPath) { this.servletPath = servletPath; return this; } public Builder setServerPort(int serverPort) { this.serverPort = serverPort; return this; } public Builder setMatchingRequestParameterName(String matchingRequestParameterName) { this.matchingRequestParameterName = matchingRequestParameterName; return this; } public DefaultSavedRequest build() { DefaultSavedRequest savedRequest = new DefaultSavedRequest(this); if (!ObjectUtils.isEmpty(this.cookies)) { for (SavedCookie cookie : this.cookies) { savedRequest.addCookie(cookie.getCookie()); } } if (!ObjectUtils.isEmpty(this.locales)) { savedRequest.locales.addAll(this.locales); } savedRequest.addParameters(this.parameters); this.headers.remove(HEADER_IF_MODIFIED_SINCE); this.headers.remove(HEADER_IF_NONE_MATCH); for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) { String headerName = entry.getKey(); List<String> headerValues = entry.getValue(); for (String headerValue : headerValues) { savedRequest.addHeader(headerName, headerValue); } } return savedRequest; } } }
14,212
26.491296
110
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/SimpleSavedRequest.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.savedrequest; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import jakarta.servlet.http.Cookie; import org.springframework.util.Assert; /** * A Bean implementation of SavedRequest * * @author Rob Winch * @since 5.1 */ public class SimpleSavedRequest implements SavedRequest { private String redirectUrl; private List<Cookie> cookies = new ArrayList<>(); private String method = "GET"; private Map<String, List<String>> headers = new HashMap<>(); private List<Locale> locales = new ArrayList<>(); private Map<String, String[]> parameters = new HashMap<>(); public SimpleSavedRequest() { } public SimpleSavedRequest(String redirectUrl) { this.redirectUrl = redirectUrl; } public SimpleSavedRequest(SavedRequest request) { this.redirectUrl = request.getRedirectUrl(); this.cookies = request.getCookies(); for (String headerName : request.getHeaderNames()) { this.headers.put(headerName, request.getHeaderValues(headerName)); } this.locales = request.getLocales(); this.parameters = request.getParameterMap(); this.method = request.getMethod(); } @Override public String getRedirectUrl() { return this.redirectUrl; } @Override public List<Cookie> getCookies() { return this.cookies; } @Override public String getMethod() { return this.method; } @Override public List<String> getHeaderValues(String name) { return this.headers.getOrDefault(name, new ArrayList<>()); } @Override public Collection<String> getHeaderNames() { return this.headers.keySet(); } @Override public List<Locale> getLocales() { return this.locales; } @Override public String[] getParameterValues(String name) { return this.parameters.getOrDefault(name, new String[0]); } @Override public Map<String, String[]> getParameterMap() { return this.parameters; } public void setRedirectUrl(String redirectUrl) { Assert.notNull(redirectUrl, "redirectUrl cannot be null"); this.redirectUrl = redirectUrl; } public void setCookies(List<Cookie> cookies) { Assert.notNull(cookies, "cookies cannot be null"); this.cookies = cookies; } public void setMethod(String method) { Assert.notNull(method, "method cannot be null"); this.method = method; } public void setHeaders(Map<String, List<String>> headers) { Assert.notNull(headers, "headers cannot be null"); this.headers = headers; } public void setLocales(List<Locale> locales) { Assert.notNull(locales, "locales cannot be null"); this.locales = locales; } public void setParameters(Map<String, String[]> parameters) { Assert.notNull(parameters, "parameters cannot be null"); this.parameters = parameters; } }
3,430
23.683453
75
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/CookieRequestCache.java
/* * 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.savedrequest; import java.util.Base64; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.web.util.UrlUtils; import org.springframework.security.web.util.matcher.AnyRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.WebUtils; /** * An Implementation of {@code RequestCache} which saves the original request URI in a * cookie. * * @author Zeeshan Adnan * @since 5.4 */ public class CookieRequestCache implements RequestCache { private RequestMatcher requestMatcher = AnyRequestMatcher.INSTANCE; protected final Log logger = LogFactory.getLog(this.getClass()); private static final String COOKIE_NAME = "REDIRECT_URI"; private static final int COOKIE_MAX_AGE = -1; @Override public void saveRequest(HttpServletRequest request, HttpServletResponse response) { if (!this.requestMatcher.matches(request)) { this.logger.debug("Request not saved as configured RequestMatcher did not match"); return; } String redirectUrl = UrlUtils.buildFullRequestUrl(request); Cookie savedCookie = new Cookie(COOKIE_NAME, encodeCookie(redirectUrl)); savedCookie.setMaxAge(COOKIE_MAX_AGE); savedCookie.setSecure(request.isSecure()); savedCookie.setPath(getCookiePath(request)); savedCookie.setHttpOnly(true); response.addCookie(savedCookie); } @Override public SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response) { Cookie savedRequestCookie = WebUtils.getCookie(request, COOKIE_NAME); if (savedRequestCookie == null) { return null; } String originalURI = decodeCookie(savedRequestCookie.getValue()); UriComponents uriComponents = UriComponentsBuilder.fromUriString(originalURI).build(); DefaultSavedRequest.Builder builder = new DefaultSavedRequest.Builder(); int port = getPort(uriComponents); return builder.setScheme(uriComponents.getScheme()).setServerName(uriComponents.getHost()) .setRequestURI(uriComponents.getPath()).setQueryString(uriComponents.getQuery()).setServerPort(port) .setMethod(request.getMethod()).build(); } private int getPort(UriComponents uriComponents) { int port = uriComponents.getPort(); if (port != -1) { return port; } if ("https".equalsIgnoreCase(uriComponents.getScheme())) { return 443; } return 80; } @Override public HttpServletRequest getMatchingRequest(HttpServletRequest request, HttpServletResponse response) { SavedRequest saved = this.getRequest(request, response); if (!this.matchesSavedRequest(request, saved)) { this.logger.debug("saved request doesn't match"); return null; } this.removeRequest(request, response); return new SavedRequestAwareWrapper(saved, request); } @Override public void removeRequest(HttpServletRequest request, HttpServletResponse response) { Cookie removeSavedRequestCookie = new Cookie(COOKIE_NAME, ""); removeSavedRequestCookie.setSecure(request.isSecure()); removeSavedRequestCookie.setHttpOnly(true); removeSavedRequestCookie.setPath(getCookiePath(request)); removeSavedRequestCookie.setMaxAge(0); response.addCookie(removeSavedRequestCookie); } private static String encodeCookie(String cookieValue) { return Base64.getEncoder().encodeToString(cookieValue.getBytes()); } private static String decodeCookie(String encodedCookieValue) { return new String(Base64.getDecoder().decode(encodedCookieValue.getBytes())); } private static String getCookiePath(HttpServletRequest request) { String contextPath = request.getContextPath(); return (StringUtils.hasLength(contextPath)) ? contextPath : "/"; } private boolean matchesSavedRequest(HttpServletRequest request, SavedRequest savedRequest) { if (savedRequest == null) { return false; } String currentUrl = UrlUtils.buildFullRequestUrl(request); return savedRequest.getRedirectUrl().equals(currentUrl); } /** * Allows selective use of saved requests for a subset of requests. By default any * request will be cached by the {@code saveRequest} method. * <p> * If set, only matching requests will be cached. * @param requestMatcher a request matching strategy which defines which requests * should be cached. */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher should not be null"); this.requestMatcher = requestMatcher; } }
5,430
35.206667
105
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/FastHttpDateFormat.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.savedrequest; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.TimeZone; /** * Utility class to generate HTTP dates. * <p> * This class is based on code in Apache Tomcat. * * @author Remy Maucherat * @author Andrey Grebnev */ public final class FastHttpDateFormat { /** * HTTP date format. */ protected static final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); /** * The set of SimpleDateFormat formats to use in <code>getDateHeader()</code>. */ protected static final SimpleDateFormat[] formats = { new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US), new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) }; /** * GMT time zone - all HTTP dates are on GMT */ protected static final TimeZone gmtZone = TimeZone.getTimeZone("GMT"); static { format.setTimeZone(gmtZone); formats[0].setTimeZone(gmtZone); formats[1].setTimeZone(gmtZone); formats[2].setTimeZone(gmtZone); } /** * Instant on which the currentDate object was generated. */ protected static long currentDateGenerated = 0L; /** * Current formatted date. */ protected static String currentDate = null; /** * Formatter cache. */ protected static final HashMap<Long, String> formatCache = new HashMap<>(); /** * Parser cache. */ protected static final HashMap<String, Long> parseCache = new HashMap<>(); private FastHttpDateFormat() { } /** * Formats a specified date to HTTP format. If local format is not <code>null</code>, * it's used instead. * @param value Date value to format * @param threadLocalformat The format to use (or <code>null</code> -- then HTTP * format will be used) * @return Formatted date */ public static String formatDate(long value, DateFormat threadLocalformat) { String cachedDate = null; Long longValue = value; try { cachedDate = formatCache.get(longValue); } catch (Exception ex) { } if (cachedDate != null) { return cachedDate; } String newDate; Date dateValue = new Date(value); if (threadLocalformat != null) { newDate = threadLocalformat.format(dateValue); synchronized (formatCache) { updateCache(formatCache, longValue, newDate); } } else { synchronized (formatCache) { newDate = format.format(dateValue); updateCache(formatCache, longValue, newDate); } } return newDate; } /** * Gets the current date in HTTP format. * @return Current date in HTTP format */ public static String getCurrentDate() { long now = System.currentTimeMillis(); if ((now - currentDateGenerated) > 1000) { synchronized (format) { if ((now - currentDateGenerated) > 1000) { currentDateGenerated = now; currentDate = format.format(new Date(now)); } } } return currentDate; } /** * Parses date with given formatters. * @param value The string to parse * @param formats Array of formats to use * @return Parsed date (or <code>null</code> if no formatter mached) */ private static Long internalParseDate(String value, DateFormat[] formats) { Date date = null; for (int i = 0; (date == null) && (i < formats.length); i++) { try { date = formats[i].parse(value); } catch (ParseException ex) { } } if (date == null) { return null; } return date.getTime(); } /** * Tries to parse the given date as an HTTP date. If local format list is not * <code>null</code>, it's used instead. * @param value The string to parse * @param threadLocalformats Array of formats to use for parsing. If <code>null</code> * , HTTP formats are used. * @return Parsed date (or -1 if error occurred) */ public static long parseDate(String value, DateFormat[] threadLocalformats) { Long cachedDate = null; try { cachedDate = parseCache.get(value); } catch (Exception ex) { } if (cachedDate != null) { return cachedDate; } Long date; if (threadLocalformats != null) { date = internalParseDate(value, threadLocalformats); synchronized (parseCache) { updateCache(parseCache, value, date); } } else { synchronized (parseCache) { date = internalParseDate(value, formats); updateCache(parseCache, value, date); } } return (date != null) ? date : -1L; } /** * Updates cache. * @param cache Cache to be updated * @param key Key to be updated * @param value New value */ @SuppressWarnings("unchecked") private static void updateCache(HashMap cache, Object key, Object value) { if (value == null) { return; } if (cache.size() > 1000) { cache.clear(); } cache.put(key, value); } }
5,502
25.080569
115
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java
/* * Copyright 2002-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 * * 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.savedrequest; import java.io.IOException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.util.Assert; import org.springframework.web.filter.GenericFilterBean; /** * Responsible for reconstituting the saved request if one is cached and it matches the * current request. * <p> * It will call * {@link RequestCache#getMatchingRequest(HttpServletRequest, HttpServletResponse) * getMatchingRequest} on the configured <tt>RequestCache</tt>. If the method returns a * value (a wrapper of the saved request), it will pass this to the filter chain's * <tt>doFilter</tt> method. If null is returned by the cache, the original request is * used and the filter has no effect. * * @author Luke Taylor * @since 3.0 */ public class RequestCacheAwareFilter extends GenericFilterBean { private RequestCache requestCache; public RequestCacheAwareFilter() { this(new HttpSessionRequestCache()); } public RequestCacheAwareFilter(RequestCache requestCache) { Assert.notNull(requestCache, "requestCache cannot be null"); this.requestCache = requestCache; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest wrappedSavedRequest = this.requestCache.getMatchingRequest((HttpServletRequest) request, (HttpServletResponse) response); chain.doFilter((wrappedSavedRequest != null) ? wrappedSavedRequest : request, response); } }
2,352
34.119403
109
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/SavedCookie.java
/* * Copyright 2002-2023 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.savedrequest; import java.io.Serializable; import jakarta.servlet.http.Cookie; import org.springframework.security.core.SpringSecurityCoreVersion; /** * Stores off the values of a cookie in a serializable holder * * @author Ray Krueger */ public class SavedCookie implements Serializable { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final String name; private final String value; private final String comment; private final String domain; private final int maxAge; private final String path; private final boolean secure; private final int version; /** * @deprecated use * {@link org.springframework.security.web.savedrequest.SavedCookie#SavedCookie(String, String, String, int, String, boolean)} * instead */ @Deprecated(forRemoval = true, since = "6.1") public SavedCookie(String name, String value, String comment, String domain, int maxAge, String path, boolean secure, int version) { this.name = name; this.value = value; this.comment = comment; this.domain = domain; this.maxAge = maxAge; this.path = path; this.secure = secure; this.version = version; } public SavedCookie(String name, String value, String domain, int maxAge, String path, boolean secure) { this(name, value, null, domain, maxAge, path, secure, 0); } public SavedCookie(Cookie cookie) { this(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getMaxAge(), cookie.getPath(), cookie.getSecure()); } public String getName() { return this.name; } public String getValue() { return this.value; } @Deprecated(forRemoval = true, since = "6.1") public String getComment() { return this.comment; } public String getDomain() { return this.domain; } public int getMaxAge() { return this.maxAge; } public String getPath() { return this.path; } public boolean isSecure() { return this.secure; } @Deprecated(forRemoval = true, since = "6.1") public int getVersion() { return this.version; } public Cookie getCookie() { Cookie cookie = new Cookie(getName(), getValue()); if (getComment() != null) { cookie.setComment(getComment()); } if (getDomain() != null) { cookie.setDomain(getDomain()); } if (getPath() != null) { cookie.setPath(getPath()); } cookie.setVersion(getVersion()); cookie.setMaxAge(getMaxAge()); cookie.setSecure(isSecure()); return cookie; } }
3,102
23.054264
127
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/Enumerator.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.savedrequest; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; /** * <p> * Adapter that wraps an <code>Enumeration</code> around a Java 2 collection * <code>Iterator</code>. * </p> * <p> * Constructors are provided to easily create such wrappers. * </p> * <p> * This class is based on code in Apache Tomcat. * </p> * * @author Craig McClanahan * @author Andrey Grebnev */ public class Enumerator<T> implements Enumeration<T> { /** * The <code>Iterator</code> over which the <code>Enumeration</code> represented by * this class actually operates. */ private Iterator<T> iterator = null; /** * Return an Enumeration over the values of the specified Collection. * @param collection Collection whose values should be enumerated */ public Enumerator(Collection<T> collection) { this(collection.iterator()); } /** * Return an Enumeration over the values of the specified Collection. * @param collection Collection whose values should be enumerated * @param clone true to clone iterator */ public Enumerator(Collection<T> collection, boolean clone) { this(collection.iterator(), clone); } /** * Return an Enumeration over the values returned by the specified Iterator. * @param iterator Iterator to be wrapped */ public Enumerator(Iterator<T> iterator) { this.iterator = iterator; } /** * Return an Enumeration over the values returned by the specified Iterator. * @param iterator Iterator to be wrapped * @param clone true to clone iterator */ public Enumerator(Iterator<T> iterator, boolean clone) { if (!clone) { this.iterator = iterator; } else { List<T> list = new ArrayList<>(); while (iterator.hasNext()) { list.add(iterator.next()); } this.iterator = list.iterator(); } } /** * Return an Enumeration over the values of the specified Map. * @param map Map whose values should be enumerated */ public Enumerator(Map<?, T> map) { this(map.values().iterator()); } /** * Return an Enumeration over the values of the specified Map. * @param map Map whose values should be enumerated * @param clone true to clone iterator */ public Enumerator(Map<?, T> map, boolean clone) { this(map.values().iterator(), clone); } /** * Tests if this enumeration contains more elements. * @return <code>true</code> if and only if this enumeration object contains at least * one more element to provide, <code>false</code> otherwise */ @Override public boolean hasMoreElements() { return (this.iterator.hasNext()); } /** * Returns the next element of this enumeration if this enumeration has at least one * more element to provide. * @return the next element of this enumeration * @exception NoSuchElementException if no more elements exist */ @Override public T nextElement() throws NoSuchElementException { return (this.iterator.next()); } }
3,701
27.045455
86
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapper.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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.savedrequest; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequestWrapper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Provides request parameters, headers and cookies from either an original request or a * saved request. * * <p> * Note that not all request parameters in the original request are emulated by this * wrapper. Nevertheless, the important data from the original request is emulated and * this should prove adequate for most purposes (in particular standard HTTP GET and POST * operations). * * <p> * Added into a request by * {@link org.springframework.security.web.savedrequest.RequestCacheAwareFilter}. * * @author Andrey Grebnev * @author Ben Alex * @author Luke Taylor */ class SavedRequestAwareWrapper extends HttpServletRequestWrapper { protected static final Log logger = LogFactory.getLog(SavedRequestAwareWrapper.class); protected static final TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT"); /** The default Locale if none are specified. */ protected static Locale defaultLocale = Locale.getDefault(); protected SavedRequest savedRequest = null; /** * The set of SimpleDateFormat formats to use in getDateHeader(). Notice that because * SimpleDateFormat is not thread-safe, we can't declare formats[] as a static * variable. */ protected final SimpleDateFormat[] formats = new SimpleDateFormat[3]; SavedRequestAwareWrapper(SavedRequest saved, HttpServletRequest request) { super(request); this.savedRequest = saved; this.formats[0] = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); this.formats[1] = new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US); this.formats[2] = new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US); this.formats[0].setTimeZone(GMT_ZONE); this.formats[1].setTimeZone(GMT_ZONE); this.formats[2].setTimeZone(GMT_ZONE); } @Override public long getDateHeader(String name) { String value = getHeader(name); if (value == null) { return -1L; } // Attempt to convert the date header in a variety of formats long result = FastHttpDateFormat.parseDate(value, this.formats); if (result != -1L) { return result; } throw new IllegalArgumentException(value); } @Override public String getHeader(String name) { List<String> values = this.savedRequest.getHeaderValues(name); return values.isEmpty() ? null : values.get(0); } @Override @SuppressWarnings("unchecked") public Enumeration getHeaderNames() { return new Enumerator<>(this.savedRequest.getHeaderNames()); } @Override @SuppressWarnings("unchecked") public Enumeration getHeaders(String name) { return new Enumerator<>(this.savedRequest.getHeaderValues(name)); } @Override public int getIntHeader(String name) { String value = getHeader(name); return (value != null) ? Integer.parseInt(value) : -1; } @Override public Locale getLocale() { List<Locale> locales = this.savedRequest.getLocales(); return locales.isEmpty() ? Locale.getDefault() : locales.get(0); } @Override @SuppressWarnings("unchecked") public Enumeration getLocales() { List<Locale> locales = this.savedRequest.getLocales(); if (locales.isEmpty()) { // Fall back to default locale locales = new ArrayList<>(1); locales.add(Locale.getDefault()); } return new Enumerator<>(locales); } @Override public String getMethod() { return this.savedRequest.getMethod(); } /** * If the parameter is available from the wrapped request then the request has been * forwarded/included to a URL with parameters, either supplementing or overriding the * saved request values. * <p> * In this case, the value from the wrapped request should be used. * <p> * If the value from the wrapped request is null, an attempt will be made to retrieve * the parameter from the saved request. */ @Override public String getParameter(String name) { String value = super.getParameter(name); if (value != null) { return value; } String[] values = this.savedRequest.getParameterValues(name); if (values == null || values.length == 0) { return null; } return values[0]; } @Override @SuppressWarnings("unchecked") public Map getParameterMap() { Set<String> names = getCombinedParameterNames(); Map<String, String[]> parameterMap = new HashMap<>(names.size()); for (String name : names) { parameterMap.put(name, getParameterValues(name)); } return parameterMap; } @SuppressWarnings("unchecked") private Set<String> getCombinedParameterNames() { Set<String> names = new HashSet<>(); names.addAll(super.getParameterMap().keySet()); names.addAll(this.savedRequest.getParameterMap().keySet()); return names; } @Override @SuppressWarnings("unchecked") public Enumeration getParameterNames() { return new Enumerator(getCombinedParameterNames()); } @Override public String[] getParameterValues(String name) { String[] savedRequestParams = this.savedRequest.getParameterValues(name); String[] wrappedRequestParams = super.getParameterValues(name); if (savedRequestParams == null) { return wrappedRequestParams; } if (wrappedRequestParams == null) { return savedRequestParams; } // We have parameters in both saved and wrapped requests so have to merge them List<String> wrappedParamsList = Arrays.asList(wrappedRequestParams); List<String> combinedParams = new ArrayList<>(wrappedParamsList); // We want to add all parameters of the saved request *apart from* duplicates of // those already added for (String savedRequestParam : savedRequestParams) { if (!wrappedParamsList.contains(savedRequestParam)) { combinedParams.add(savedRequestParam); } } return combinedParams.toArray(new String[0]); } }
6,774
30.365741
89
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/NullRequestCache.java
/* * Copyright 2002-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 * * 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.savedrequest; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Null implementation of <tt>RequestCache</tt>. Typically used when creation of a session * is not desired. * * @author Luke Taylor * @since 3.0 */ public class NullRequestCache implements RequestCache { @Override public SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response) { return null; } @Override public void removeRequest(HttpServletRequest request, HttpServletResponse response) { } @Override public void saveRequest(HttpServletRequest request, HttpServletResponse response) { } @Override public HttpServletRequest getMatchingRequest(HttpServletRequest request, HttpServletResponse response) { return null; } }
1,455
27.54902
105
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/savedrequest/RequestCache.java
/* * Copyright 2002-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 * * 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.savedrequest; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Implements "saved request" logic, allowing a single request to be retrieved and * restarted after redirecting to an authentication mechanism. * * @author Luke Taylor * @since 3.0 */ public interface RequestCache { /** * Caches the current request for later retrieval, once authentication has taken * place. Used by <tt>ExceptionTranslationFilter</tt>. * @param request the request to be stored */ void saveRequest(HttpServletRequest request, HttpServletResponse response); /** * Returns the saved request, leaving it cached. * @param request the current request * @return the saved request which was previously cached, or null if there is none. */ SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response); /** * Returns a wrapper around the saved request, if it matches the current request. The * saved request should be removed from the cache. * @param request * @param response * @return the wrapped save request, if it matches the original, or null if there is * no cached request or it doesn't match. */ HttpServletRequest getMatchingRequest(HttpServletRequest request, HttpServletResponse response); /** * Removes the cached request. * @param request the current request, allowing access to the cache. */ void removeRequest(HttpServletRequest request, HttpServletResponse response); }
2,153
33.741935
97
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/debug/Logger.java
/* * Copyright 2002-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 * * 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.debug; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Controls output for the Spring Security debug feature. * * @author Luke Taylor * @since 3.1 */ final class Logger { private static final Log logger = LogFactory.getLog("Spring Security Debugger"); void info(String message) { info(message, false); } void info(String message, boolean dumpStack) { StringBuilder output = new StringBuilder(256); output.append("\n\n************************************************************\n\n"); output.append(message).append("\n"); if (dumpStack) { StringWriter os = new StringWriter(); new Exception().printStackTrace(new PrintWriter(os)); StringBuffer buffer = os.getBuffer(); // Remove the exception in case it scares people. int start = buffer.indexOf("java.lang.Exception"); buffer.replace(start, start + 19, ""); output.append("\nCall stack: \n").append(os.toString()); } output.append("\n\n************************************************************\n\n"); logger.info(output.toString()); } }
1,812
29.216667
88
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/debug/DebugFilter.java
/* * Copyright 2002-2021 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.debug; import java.io.IOException; import java.util.Enumeration; import java.util.List; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequestWrapper; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.util.UrlUtils; /** * Spring Security debugging filter. * <p> * Logs information (such as session creation) to help the user understand how requests * are being handled by Spring Security and provide them with other relevant information * (such as when sessions are being created). * * @author Luke Taylor * @author Rob Winch * @since 3.1 */ public final class DebugFilter implements Filter { static final String ALREADY_FILTERED_ATTR_NAME = DebugFilter.class.getName().concat(".FILTERED"); private final FilterChainProxy filterChainProxy; private final Logger logger = new Logger(); public DebugFilter(FilterChainProxy filterChainProxy) { this.filterChainProxy = filterChainProxy; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { throw new ServletException("DebugFilter just supports HTTP requests"); } doFilter((HttpServletRequest) request, (HttpServletResponse) response, filterChain); } private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { List<Filter> filters = getFilters(request); this.logger.info("Request received for " + request.getMethod() + " '" + UrlUtils.buildRequestUrl(request) + "':\n\n" + request + "\n\n" + "servletPath:" + request.getServletPath() + "\n" + "pathInfo:" + request.getPathInfo() + "\n" + "headers: \n" + formatHeaders(request) + "\n\n" + formatFilters(filters)); if (request.getAttribute(ALREADY_FILTERED_ATTR_NAME) == null) { invokeWithWrappedRequest(request, response, filterChain); } else { this.filterChainProxy.doFilter(request, response, filterChain); } } private void invokeWithWrappedRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { request.setAttribute(ALREADY_FILTERED_ATTR_NAME, Boolean.TRUE); request = new DebugRequestWrapper(request); try { this.filterChainProxy.doFilter(request, response, filterChain); } finally { request.removeAttribute(ALREADY_FILTERED_ATTR_NAME); } } String formatHeaders(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); Enumeration<String> eHeaderNames = request.getHeaderNames(); while (eHeaderNames.hasMoreElements()) { String headerName = eHeaderNames.nextElement(); sb.append(headerName); sb.append(": "); Enumeration<String> eHeaderValues = request.getHeaders(headerName); while (eHeaderValues.hasMoreElements()) { sb.append(eHeaderValues.nextElement()); if (eHeaderValues.hasMoreElements()) { sb.append(", "); } } sb.append("\n"); } return sb.toString(); } String formatFilters(List<Filter> filters) { StringBuilder sb = new StringBuilder(); sb.append("Security filter chain: "); if (filters == null) { sb.append("no match"); } else if (filters.isEmpty()) { sb.append("[] empty (bypassed by security='none') "); } else { sb.append("[\n"); for (Filter f : filters) { sb.append(" ").append(f.getClass().getSimpleName()).append("\n"); } sb.append("]"); } return sb.toString(); } private List<Filter> getFilters(HttpServletRequest request) { for (SecurityFilterChain chain : this.filterChainProxy.getFilterChains()) { if (chain.matches(request)) { return chain.getFilters(); } } return null; } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } public FilterChainProxy getFilterChainProxy() { return this.filterChainProxy; } static class DebugRequestWrapper extends HttpServletRequestWrapper { private static final Logger logger = new Logger(); DebugRequestWrapper(HttpServletRequest request) { super(request); } @Override public HttpSession getSession() { boolean sessionExists = super.getSession(false) != null; HttpSession session = super.getSession(); if (!sessionExists) { DebugRequestWrapper.logger.info("New HTTP session created: " + session.getId(), true); } return session; } @Override public HttpSession getSession(boolean create) { if (!create) { return super.getSession(create); } return getSession(); } } }
5,741
29.705882
107
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolver.java
/* * Copyright 2002-2021 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.reactive.result.method.annotation; import java.lang.annotation.Annotation; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; import org.springframework.core.MethodParameter; import org.springframework.core.ReactiveAdapter; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.expression.BeanResolver; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport; import org.springframework.web.server.ServerWebExchange; /** * Resolves the Authentication * * @author Rob Winch * @since 5.0 */ public class AuthenticationPrincipalArgumentResolver extends HandlerMethodArgumentResolverSupport { private ExpressionParser parser = new SpelExpressionParser(); private BeanResolver beanResolver; public AuthenticationPrincipalArgumentResolver(ReactiveAdapterRegistry adapterRegistry) { super(adapterRegistry); } /** * Sets the {@link BeanResolver} to be used on the expressions * @param beanResolver the {@link BeanResolver} to use */ public void setBeanResolver(BeanResolver beanResolver) { this.beanResolver = beanResolver; } @Override public boolean supportsParameter(MethodParameter parameter) { return findMethodAnnotation(AuthenticationPrincipal.class, parameter) != null; } @Override public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) { ReactiveAdapter adapter = getAdapterRegistry().getAdapter(parameter.getParameterType()); return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication) .flatMap((authentication) -> { Mono<Object> principal = Mono .justOrEmpty(resolvePrincipal(parameter, authentication.getPrincipal())); return (adapter != null) ? Mono.just(adapter.fromPublisher(principal)) : principal; }); } private Object resolvePrincipal(MethodParameter parameter, Object principal) { AuthenticationPrincipal annotation = findMethodAnnotation(AuthenticationPrincipal.class, parameter); String expressionToParse = annotation.expression(); if (StringUtils.hasLength(expressionToParse)) { StandardEvaluationContext context = new StandardEvaluationContext(); context.setRootObject(principal); context.setVariable("this", principal); context.setBeanResolver(this.beanResolver); Expression expression = this.parser.parseExpression(expressionToParse); principal = expression.getValue(context); } if (isInvalidType(parameter, principal)) { if (annotation.errorOnInvalidType()) { throw new ClassCastException(principal + " is not assignable to " + parameter.getParameterType()); } return null; } return principal; } private boolean isInvalidType(MethodParameter parameter, Object principal) { if (principal == null) { return false; } Class<?> typeToCheck = parameter.getParameterType(); boolean isParameterPublisher = Publisher.class.isAssignableFrom(parameter.getParameterType()); if (isParameterPublisher) { ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter); Class<?> genericType = resolvableType.resolveGeneric(0); if (genericType == null) { return false; } typeToCheck = genericType; } return !ClassUtils.isAssignable(typeToCheck, principal.getClass()); } /** * Obtains the specified {@link Annotation} on the specified {@link MethodParameter}. * @param annotationClass the class of the {@link Annotation} to find on the * {@link MethodParameter} * @param parameter the {@link MethodParameter} to search for an {@link Annotation} * @return the {@link Annotation} that was found or null. */ private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass, MethodParameter parameter) { T annotation = parameter.getParameterAnnotation(annotationClass); if (annotation != null) { return annotation; } Annotation[] annotationsToSearch = parameter.getParameterAnnotations(); for (Annotation toSearch : annotationsToSearch) { annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass); if (annotation != null) { return annotation; } } return null; } }
5,606
37.9375
109
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/reactive/result/method/annotation/CurrentSecurityContextArgumentResolver.java
/* * Copyright 2002-2019 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.reactive.result.method.annotation; import java.lang.annotation.Annotation; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; import org.springframework.core.MethodParameter; import org.springframework.core.ReactiveAdapter; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.expression.BeanResolver; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.security.core.annotation.CurrentSecurityContext; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport; import org.springframework.web.server.ServerWebExchange; /** * Resolves the {@link SecurityContext} * * @author Dan Zheng * @since 5.2 */ public class CurrentSecurityContextArgumentResolver extends HandlerMethodArgumentResolverSupport { private ExpressionParser parser = new SpelExpressionParser(); private BeanResolver beanResolver; public CurrentSecurityContextArgumentResolver(ReactiveAdapterRegistry adapterRegistry) { super(adapterRegistry); } /** * Sets the {@link BeanResolver} to be used on the expressions * @param beanResolver the {@link BeanResolver} to use */ public void setBeanResolver(BeanResolver beanResolver) { Assert.notNull(beanResolver, "beanResolver cannot be null"); this.beanResolver = beanResolver; } @Override public boolean supportsParameter(MethodParameter parameter) { return findMethodAnnotation(CurrentSecurityContext.class, parameter) != null; } @Override public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) { ReactiveAdapter adapter = getAdapterRegistry().getAdapter(parameter.getParameterType()); Mono<SecurityContext> reactiveSecurityContext = ReactiveSecurityContextHolder.getContext(); if (reactiveSecurityContext == null) { return null; } return reactiveSecurityContext.flatMap((securityContext) -> { Mono<Object> resolvedSecurityContext = Mono.justOrEmpty(resolveSecurityContext(parameter, securityContext)); return (adapter != null) ? Mono.just(adapter.fromPublisher(resolvedSecurityContext)) : resolvedSecurityContext; }); } /** * resolve the expression from {@link CurrentSecurityContext} annotation to get the * value. * @param parameter the method parameter. * @param securityContext the security context. * @return the resolved object from expression. */ private Object resolveSecurityContext(MethodParameter parameter, SecurityContext securityContext) { CurrentSecurityContext annotation = findMethodAnnotation(CurrentSecurityContext.class, parameter); Object securityContextResult = securityContext; String expressionToParse = annotation.expression(); if (StringUtils.hasLength(expressionToParse)) { StandardEvaluationContext context = new StandardEvaluationContext(); context.setRootObject(securityContext); context.setVariable("this", securityContext); context.setBeanResolver(this.beanResolver); Expression expression = this.parser.parseExpression(expressionToParse); securityContextResult = expression.getValue(context); } if (isInvalidType(parameter, securityContextResult)) { if (annotation.errorOnInvalidType()) { throw new ClassCastException( securityContextResult + " is not assignable to " + parameter.getParameterType()); } return null; } return securityContextResult; } /** * check if the retrieved value match with the parameter type. * @param parameter the method parameter. * @param reactiveSecurityContext the security context. * @return true = is not invalid type. */ private boolean isInvalidType(MethodParameter parameter, Object reactiveSecurityContext) { if (reactiveSecurityContext == null) { return false; } Class<?> typeToCheck = parameter.getParameterType(); boolean isParameterPublisher = Publisher.class.isAssignableFrom(parameter.getParameterType()); if (isParameterPublisher) { ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter); Class<?> genericType = resolvableType.resolveGeneric(0); if (genericType == null) { return false; } typeToCheck = genericType; } return !typeToCheck.isAssignableFrom(reactiveSecurityContext.getClass()); } /** * Obtains the specified {@link Annotation} on the specified {@link MethodParameter}. * @param annotationClass the class of the {@link Annotation} to find on the * {@link MethodParameter} * @param parameter the {@link MethodParameter} to search for an {@link Annotation} * @return the {@link Annotation} that was found or null. */ private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass, MethodParameter parameter) { T annotation = parameter.getParameterAnnotation(annotationClass); if (annotation != null) { return annotation; } Annotation[] annotationsToSearch = parameter.getParameterAnnotations(); for (Annotation toSearch : annotationsToSearch) { annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass); if (annotation != null) { return annotation; } } return null; } }
6,419
38.146341
111
java
null
spring-security-main/web/src/main/java/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessor.java
/* * Copyright 2002-2018 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.reactive.result.view; import java.util.Collections; import java.util.Map; import java.util.regex.Pattern; import org.springframework.lang.NonNull; import org.springframework.security.web.server.csrf.CsrfToken; import org.springframework.web.reactive.result.view.RequestDataValueProcessor; import org.springframework.web.server.ServerWebExchange; /** * @author Rob Winch * @since 5.0 */ public class CsrfRequestDataValueProcessor implements RequestDataValueProcessor { /** * The default request attribute to look for a {@link CsrfToken}. */ public static final String DEFAULT_CSRF_ATTR_NAME = "_csrf"; private static final Pattern DISABLE_CSRF_TOKEN_PATTERN = Pattern.compile("(?i)^(GET|HEAD|TRACE|OPTIONS)$"); private static final String DISABLE_CSRF_TOKEN_ATTR = "DISABLE_CSRF_TOKEN_ATTR"; @Override public String processAction(ServerWebExchange exchange, String action, String httpMethod) { if (httpMethod != null && DISABLE_CSRF_TOKEN_PATTERN.matcher(httpMethod).matches()) { exchange.getAttributes().put(DISABLE_CSRF_TOKEN_ATTR, Boolean.TRUE); } else { exchange.getAttributes().remove(DISABLE_CSRF_TOKEN_ATTR); } return action; } @Override public String processFormFieldValue(ServerWebExchange exchange, String name, String value, String type) { return value; } @NonNull @Override public Map<String, String> getExtraHiddenFields(ServerWebExchange exchange) { if (Boolean.TRUE.equals(exchange.getAttribute(DISABLE_CSRF_TOKEN_ATTR))) { exchange.getAttributes().remove(DISABLE_CSRF_TOKEN_ATTR); return Collections.emptyMap(); } CsrfToken token = exchange.getAttribute(DEFAULT_CSRF_ATTR_NAME); if (token == null) { return Collections.emptyMap(); } return Collections.singletonMap(token.getParameterName(), token.getToken()); } @Override public String processUrl(ServerWebExchange exchange, String url) { return url; } }
2,560
31.417722
109
java