Add WebFlux

Fixes gh-4128
This commit is contained in:
Rob Winch
2017-05-02 21:19:14 -05:00
parent 051e3fb079
commit b4f2777755
91 changed files with 7036 additions and 1 deletions

View File

@@ -0,0 +1,50 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.test.web.reactive.server;
import org.springframework.http.HttpStatus;
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 class WebTestClientBuilder {
public static Builder bindToWebFilters(WebFilter... webFilters) {
return WebTestClient.bindToController(new Http200RestController()).webFilter(webFilters).configureClient();
}
@RestController
static class Http200RestController {
@RequestMapping("/**")
@ResponseStatus(HttpStatus.OK)
public String ok() {
return "ok";
}
}
}

View File

@@ -0,0 +1,63 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.test.web.reactive.server;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest.BaseBuilder;
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;
import reactor.core.publisher.Mono;
import java.util.Arrays;
/**
*
* @author Rob Winch
* @since 5.0
*/
public class WebTestHandler {
private final WebHandler handler;
private WebTestHandler(WebHandler handler) {
this.handler = handler;
}
public WebHandlerResult exchange(BaseBuilder<?> baseBuilder) {
ServerWebExchange exchange = baseBuilder.toExchange();
handler.handle(exchange).block();
return new WebHandlerResult(exchange);
}
public static class WebHandlerResult {
private final ServerWebExchange exchange;
private WebHandlerResult(ServerWebExchange exchange) {
this.exchange = exchange;
}
public ServerWebExchange getExchange() {
return exchange;
}
}
public static WebTestHandler bindToWebFilters(WebFilter... filters) {
return new WebTestHandler(new FilteringWebHandler(exchange -> Mono.empty(), Arrays.asList(filters)));
}
}

View File

@@ -0,0 +1,679 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.method;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.aopalliance.intercept.MethodInterceptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.target.EmptyTargetSource;
import org.springframework.cglib.core.SpringNamingPolicy;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.Factory;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.MethodIntrospector;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.objenesis.ObjenesisException;
import org.springframework.objenesis.SpringObjenesis;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.ValueConstants;
import static java.util.stream.Collectors.joining;
/**
* Convenience class to resolve method parameters from hints.
*
* <h1>Background</h1>
*
* <p>When testing annotated methods we create test classes such as
* "TestController" with a diverse range of method signatures representing
* supported annotations and argument types. It becomes challenging to use
* naming strategies to keep track of methods and arguments especially in
* combination with variables for reflection metadata.
*
* <p>The idea with {@link ResolvableMethod} is NOT to rely on naming techniques
* but to use hints to zero in on method parameters. Such hints can be strongly
* typed and explicit about what is being tested.
*
* <h2>1. Declared Return Type</h2>
*
* When testing return types it's likely to have many methods with a unique
* return type, possibly with or without an annotation.
*
* <pre>
*
* import static org.springframework.web.method.ResolvableMethod.on;
* import static org.springframework.web.method.MvcAnnotationPredicates.requestMapping;
*
* // Return type
* on(TestController.class).resolveReturnType(Foo.class);
* on(TestController.class).resolveReturnType(List.class, Foo.class);
* on(TestController.class).resolveReturnType(Mono.class, responseEntity(Foo.class));
*
* // Annotation + return type
* on(TestController.class).annotPresent(RequestMapping.class).resolveReturnType(Bar.class);
*
* // Annotation not present
* on(TestController.class).annotNotPresent(RequestMapping.class).resolveReturnType();
*
* // Annotation with attributes
* on(TestController.class).annot(requestMapping("/foo").params("p")).resolveReturnType();
* </pre>
*
* <h2>2. Method Arguments</h2>
*
* When testing method arguments it's more likely to have one or a small number
* of methods with a wide array of argument types and parameter annotations.
*
* <pre>
*
* import static org.springframework.web.method.MvcAnnotationPredicates.requestParam;
*
* ResolvableMethod testMethod = ResolvableMethod.on(getClass()).named("handle").build();
*
* testMethod.arg(Foo.class);
* testMethod.annotPresent(RequestParam.class).arg(Integer.class);
* testMethod.annotNotPresent(RequestParam.class)).arg(Integer.class);
* testMethod.annot(requestParam().name("c").notRequired()).arg(Integer.class);
* </pre>
*
* <h3>3. Mock Handler Method Invocation</h3>
*
* Locate a method by invoking it through a proxy of the target handler:
*
* <pre>
*
* ResolvableMethod.on(TestController.class).mockCall(o -> o.handle(null)).method();
* </pre>
*
* @author Rossen Stoyanchev
* @since 5.0
*/
public class ResolvableMethod {
private static final Log logger = LogFactory.getLog(ResolvableMethod.class);
private static final SpringObjenesis objenesis = new SpringObjenesis();
private static final ParameterNameDiscoverer nameDiscoverer =
new LocalVariableTableParameterNameDiscoverer();
private final Method method;
private ResolvableMethod(Method method) {
Assert.notNull(method, "method is required");
this.method = method;
}
/**
* Return the resolved method.
*/
public Method method() {
return this.method;
}
/**
* Return the declared return type of the resolved method.
*/
public MethodParameter returnType() {
return new SynthesizingMethodParameter(this.method, -1);
}
/**
* Find a unique argument matching the given type.
* @param type the expected type
* @param generics optional array of generic types
*/
public MethodParameter arg(Class<?> type, Class<?>... generics) {
return new ArgResolver().arg(type, generics);
}
/**
* Find a unique argument matching the given type.
* @param type the expected type
* @param generic at least one generic type
* @param generics optional array of generic types
*/
public MethodParameter arg(Class<?> type, ResolvableType generic, ResolvableType... generics) {
return new ArgResolver().arg(type, generic, generics);
}
/**
* Find a unique argument matching the given type.
* @param type the expected type
*/
public MethodParameter arg(ResolvableType type) {
return new ArgResolver().arg(type);
}
/**
* Filter on method arguments with annotation.
* See {@link MvcAnnotationPredicates}.
*/
@SafeVarargs
public final ArgResolver annot(Predicate<MethodParameter>... filter) {
return new ArgResolver(filter);
}
@SafeVarargs
public final ArgResolver annotPresent(Class<? extends Annotation>... annotationTypes) {
return new ArgResolver().annotPresent(annotationTypes);
}
/**
* Filter on method arguments that don't have the given annotation type(s).
* @param annotationTypes the annotation types
*/
@SafeVarargs
public final ArgResolver annotNotPresent(Class<? extends Annotation>... annotationTypes) {
return new ArgResolver().annotNotPresent(annotationTypes);
}
@Override
public String toString() {
return "ResolvableMethod=" + formatMethod();
}
private String formatMethod() {
return this.method().getName() +
Arrays.stream(this.method.getParameters())
.map(this::formatParameter)
.collect(joining(",\n\t", "(\n\t", "\n)"));
}
private String formatParameter(Parameter param) {
Annotation[] annot = param.getAnnotations();
return annot.length > 0 ?
Arrays.stream(annot).map(this::formatAnnotation).collect(joining(",", "[", "]")) + " " + param :
param.toString();
}
private String formatAnnotation(Annotation annotation) {
Map<String, Object> map = AnnotationUtils.getAnnotationAttributes(annotation);
map.forEach((key, value) -> {
if (value.equals(ValueConstants.DEFAULT_NONE)) {
map.put(key, "NONE");
}
});
return annotation.annotationType().getName() + map;
}
private static ResolvableType toResolvableType(Class<?> type, Class<?>... generics) {
return ObjectUtils.isEmpty(generics) ?
ResolvableType.forClass(type) :
ResolvableType.forClassWithGenerics(type, generics);
}
private static ResolvableType toResolvableType(Class<?> type, ResolvableType generic, ResolvableType... generics) {
ResolvableType[] genericTypes = new ResolvableType[generics.length + 1];
genericTypes[0] = generic;
System.arraycopy(generics, 0, genericTypes, 1, generics.length);
return ResolvableType.forClassWithGenerics(type, genericTypes);
}
/**
* Main entry point providing access to a {@code ResolvableMethod} builder.
*/
public static <T> Builder<T> on(Class<T> objectClass) {
return new Builder<>(objectClass);
}
/**
* Builder for {@code ResolvableMethod}.
*/
public static class Builder<T> {
private final Class<?> objectClass;
private final List<Predicate<Method>> filters = new ArrayList<>(4);
private Builder(Class<?> objectClass) {
Assert.notNull(objectClass, "Class must not be null");
this.objectClass = objectClass;
}
private void addFilter(String message, Predicate<Method> filter) {
this.filters.add(new LabeledPredicate<>(message, filter));
}
/**
* Filter on methods with the given name.
*/
public Builder<T> named(String methodName) {
addFilter("methodName=" + methodName, m -> m.getName().equals(methodName));
return this;
}
/**
* Filter on annotated methods.
* See {@link MvcAnnotationPredicates}.
*/
@SafeVarargs
public final Builder<T> annot(Predicate<Method>... filters) {
this.filters.addAll(Arrays.asList(filters));
return this;
}
/**
* Filter on methods annotated with the given annotation type.
* @see #annot(Predicate[])
* @see MvcAnnotationPredicates
*/
@SafeVarargs
public final Builder<T> annotPresent(Class<? extends Annotation>... annotationTypes) {
String message = "annotationPresent=" + Arrays.toString(annotationTypes);
addFilter(message, method ->
Arrays.stream(annotationTypes).allMatch(annotType ->
AnnotatedElementUtils.findMergedAnnotation(method, annotType) != null));
return this;
}
/**
* Filter on methods not annotated with the given annotation type.
*/
@SafeVarargs
public final Builder<T> annotNotPresent(Class<? extends Annotation>... annotationTypes) {
String message = "annotationNotPresent=" + Arrays.toString(annotationTypes);
addFilter(message, method -> {
if (annotationTypes.length != 0) {
return Arrays.stream(annotationTypes).noneMatch(annotType ->
AnnotatedElementUtils.findMergedAnnotation(method, annotType) != null);
}
else {
return method.getAnnotations().length == 0;
}
});
return this;
}
/**
* Filter on methods returning the given type.
* @param returnType the return type
* @param generics optional array of generic types
*/
public Builder<T> returning(Class<?> returnType, Class<?>... generics) {
return returning(toResolvableType(returnType, generics));
}
/**
* Filter on methods returning the given type with generics.
* @param returnType the return type
* @param generic at least one generic type
* @param generics optional extra generic types
*/
public Builder<T> returning(Class<?> returnType, ResolvableType generic, ResolvableType... generics) {
return returning(toResolvableType(returnType, generic, generics));
}
/**
* Filter on methods returning the given type.
* @param returnType the return type
*/
public Builder<T> returning(ResolvableType returnType) {
String expected = returnType.toString();
String message = "returnType=" + expected;
addFilter(message, m -> expected.equals(ResolvableType.forMethodReturnType(m).toString()));
return this;
}
/**
* Build a {@code ResolvableMethod} from the provided filters which must
* resolve to a unique, single method.
*
* <p>See additional resolveXxx shortcut methods going directly to
* {@link Method} or return type parameter.
*
* @throws IllegalStateException for no match or multiple matches
*/
public ResolvableMethod build() {
Set<Method> methods = MethodIntrospector.selectMethods(this.objectClass, this::isMatch);
Assert.state(!methods.isEmpty(), "No matching method: " + this);
Assert.state(methods.size() == 1, "Multiple matching methods: " + this + formatMethods(methods));
return new ResolvableMethod(methods.iterator().next());
}
private boolean isMatch(Method method) {
return this.filters.stream().allMatch(p -> p.test(method));
}
private String formatMethods(Set<Method> methods) {
return "\nMatched:\n" + methods.stream()
.map(Method::toGenericString).collect(joining(",\n\t", "[\n\t", "\n]"));
}
public ResolvableMethod mockCall(Consumer<T> invoker) {
MethodInvocationInterceptor interceptor = new MethodInvocationInterceptor();
T proxy = initProxy(this.objectClass, interceptor);
invoker.accept(proxy);
Method method = interceptor.getInvokedMethod();
return new ResolvableMethod(method);
}
// Build & resolve shortcuts...
/**
* Resolve and return the {@code Method} equivalent to:
* <p>{@code build().method()}
*/
public final Method resolveMethod() {
return build().method();
}
/**
* Resolve and return the {@code Method} equivalent to:
* <p>{@code named(methodName).build().method()}
*/
public Method resolveMethod(String methodName) {
return named(methodName).build().method();
}
/**
* Resolve and return the declared return type equivalent to:
* <p>{@code build().returnType()}
*/
public final MethodParameter resolveReturnType() {
return build().returnType();
}
/**
* Shortcut to the unique return type equivalent to:
* <p>{@code returning(returnType).build().returnType()}
* @param returnType the return type
* @param generics optional array of generic types
*/
public MethodParameter resolveReturnType(Class<?> returnType, Class<?>... generics) {
return returning(returnType, generics).build().returnType();
}
/**
* Shortcut to the unique return type equivalent to:
* <p>{@code returning(returnType).build().returnType()}
* @param returnType the return type
* @param generic at least one generic type
* @param generics optional extra generic types
*/
public MethodParameter resolveReturnType(Class<?> returnType, ResolvableType generic,
ResolvableType... generics) {
return returning(returnType, generic, generics).build().returnType();
}
public MethodParameter resolveReturnType(ResolvableType returnType) {
return returning(returnType).build().returnType();
}
@Override
public String toString() {
return "ResolvableMethod.Builder[\n" +
"\tobjectClass = " + this.objectClass.getName() + ",\n" +
"\tfilters = " + formatFilters() + "\n]";
}
private String formatFilters() {
return this.filters.stream().map(Object::toString)
.collect(joining(",\n\t\t", "[\n\t\t", "\n\t]"));
}
}
/**
* Predicate with a descriptive label.
*/
private static class LabeledPredicate<T> implements Predicate<T> {
private final String label;
private final Predicate<T> delegate;
private LabeledPredicate(String label, Predicate<T> delegate) {
this.label = label;
this.delegate = delegate;
}
@Override
public boolean test(T method) {
return this.delegate.test(method);
}
@Override
public Predicate<T> and(Predicate<? super T> other) {
return this.delegate.and(other);
}
@Override
public Predicate<T> negate() {
return this.delegate.negate();
}
@Override
public Predicate<T> or(Predicate<? super T> other) {
return this.delegate.or(other);
}
@Override
public String toString() {
return this.label;
}
}
/**
* Resolver for method arguments.
*/
public class ArgResolver {
private final List<Predicate<MethodParameter>> filters = new ArrayList<>(4);
@SafeVarargs
private ArgResolver(Predicate<MethodParameter>... filter) {
this.filters.addAll(Arrays.asList(filter));
}
/**
* Filter on method arguments with annotations.
* See {@link MvcAnnotationPredicates}.
*/
@SafeVarargs
public final ArgResolver annot(Predicate<MethodParameter>... filters) {
this.filters.addAll(Arrays.asList(filters));
return this;
}
/**
* Filter on method arguments that have the given annotations.
* @param annotationTypes the annotation types
* @see #annot(Predicate[])
* @see MvcAnnotationPredicates
*/
@SafeVarargs
public final ArgResolver annotPresent(Class<? extends Annotation>... annotationTypes) {
this.filters.add(param -> Arrays.stream(annotationTypes).allMatch(param::hasParameterAnnotation));
return this;
}
/**
* Filter on method arguments that don't have the given annotations.
* @param annotationTypes the annotation types
*/
@SafeVarargs
public final ArgResolver annotNotPresent(Class<? extends Annotation>... annotationTypes) {
this.filters.add(param ->
(annotationTypes.length != 0) ?
Arrays.stream(annotationTypes).noneMatch(param::hasParameterAnnotation) :
param.getParameterAnnotations().length == 0);
return this;
}
/**
* Resolve the argument also matching to the given type.
* @param type the expected type
*/
public MethodParameter arg(Class<?> type, Class<?>... generics) {
return arg(toResolvableType(type, generics));
}
/**
* Resolve the argument also matching to the given type.
* @param type the expected type
*/
public MethodParameter arg(Class<?> type, ResolvableType generic, ResolvableType... generics) {
return arg(toResolvableType(type, generic, generics));
}
/**
* Resolve the argument also matching to the given type.
* @param type the expected type
*/
public MethodParameter arg(ResolvableType type) {
this.filters.add(p -> type.toString().equals(ResolvableType.forMethodParameter(p).toString()));
return arg();
}
/**
* Resolve the argument.
*/
public final MethodParameter arg() {
List<MethodParameter> matches = applyFilters();
Assert.state(!matches.isEmpty(), () ->
"No matching arg in method\n" + formatMethod());
Assert.state(matches.size() == 1, () ->
"Multiple matching args in method\n" + formatMethod() + "\nMatches:\n\t" + matches);
return matches.get(0);
}
private List<MethodParameter> applyFilters() {
List<MethodParameter> matches = new ArrayList<>();
for (int i = 0; i < method.getParameterCount(); i++) {
MethodParameter param = new SynthesizingMethodParameter(method, i);
param.initParameterNameDiscovery(nameDiscoverer);
if (this.filters.stream().allMatch(p -> p.test(param))) {
matches.add(param);
}
}
return matches;
}
}
private static class MethodInvocationInterceptor
implements org.springframework.cglib.proxy.MethodInterceptor, MethodInterceptor {
private Method invokedMethod;
Method getInvokedMethod() {
return this.invokedMethod;
}
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) {
if (ReflectionUtils.isObjectMethod(method)) {
return ReflectionUtils.invokeMethod(method, object, args);
}
else {
this.invokedMethod = method;
return null;
}
}
@Override
public Object invoke(org.aopalliance.intercept.MethodInvocation inv) throws Throwable {
return intercept(inv.getThis(), inv.getMethod(), inv.getArguments(), null);
}
}
@SuppressWarnings("unchecked")
private static <T> T initProxy(Class<?> type, MethodInvocationInterceptor interceptor) {
Assert.notNull(type, "'type' must not be null");
if (type.isInterface()) {
ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE);
factory.addInterface(type);
factory.addInterface(Supplier.class);
factory.addAdvice(interceptor);
return (T) factory.getProxy();
}
else {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(type);
enhancer.setInterfaces(new Class<?>[] {Supplier.class});
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);
Class<?> proxyClass = enhancer.createClass();
Object proxy = null;
if (objenesis.isWorthTrying()) {
try {
proxy = objenesis.newInstance(proxyClass, enhancer.getUseCache());
}
catch (ObjenesisException ex) {
logger.debug("Objenesis failed, falling back to default constructor", ex);
}
}
if (proxy == null) {
try {
proxy = ReflectionUtils.accessibleConstructor(proxyClass).newInstance();
}
catch (Throwable ex) {
throw new IllegalStateException("Unable to instantiate proxy " +
"via both Objenesis and default constructor fails as well", ex);
}
}
((Factory) proxy).setCallbacks(new Callback[] {interceptor});
return (T) proxy;
}
}
}

View File

@@ -0,0 +1,167 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.reactive.result.method.annotation;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.web.method.ResolvableMethod;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.lang.annotation.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
* @since 5.0
*/
@RunWith(MockitoJUnitRunner.class)
public class AuthenticationPrincipalArgumentResolverTests {
@Mock
ServerWebExchange exchange;
@Mock
BindingContext bindingContext;
@Mock
Authentication authentication;
ResolvableMethod authenticationPrincipal = ResolvableMethod.on(getClass()).named("authenticationPrincipal").build();
ResolvableMethod spel = ResolvableMethod.on(getClass()).named("spel").build();
ResolvableMethod meta = ResolvableMethod.on(getClass()).named("meta").build();
AuthenticationPrincipalArgumentResolver resolver;
@Before
public void setup() {
resolver = new AuthenticationPrincipalArgumentResolver(new ReactiveAdapterRegistry());
}
@Test
public void supportsParameterAuthenticationPrincipal() throws Exception {
assertThat(resolver.supportsParameter(this.authenticationPrincipal.arg(String.class))).isTrue();
}
@Test
public void supportsParameterCurrentUser() throws Exception {
assertThat(resolver.supportsParameter(this.meta.arg(String.class))).isTrue();
}
@Test
public void resolveArgumentWhenIsAuthenticationThenObtainsPrincipal() throws Exception {
MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
when(authentication.getPrincipal()).thenReturn("user");
when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
assertThat(argument.block()).isEqualTo(authentication.getPrincipal());
}
@Test
public void resolveArgumentWhenIsNotAuthenticationThenMonoEmpty() throws Exception {
MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
when(exchange.getPrincipal()).thenReturn(Mono.just(() -> ""));
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
assertThat(argument).isNotNull();
assertThat(argument.block()).isNull();
}
@Test
public void resolveArgumentWhenIsEmptyThenMonoEmpty() throws Exception {
MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
when(authentication.getPrincipal()).thenReturn("user");
when(exchange.getPrincipal()).thenReturn(Mono.empty());
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
assertThat(argument).isNotNull();
assertThat(argument.block()).isNull();
}
@Test
public void resolveArgumentWhenMonoIsAuthenticationThenObtainsPrincipal() throws Exception {
MethodParameter parameter = this.authenticationPrincipal.arg(Mono.class, String.class);
when(authentication.getPrincipal()).thenReturn("user");
when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
assertThat(argument.cast(Mono.class).block().block()).isEqualTo(authentication.getPrincipal());
}
@Test
public void resolveArgumentWhenSpelThenObtainsPrincipal() throws Exception {
MyUser user = new MyUser(3L);
MethodParameter parameter = this.spel.arg(Long.class);
when(authentication.getPrincipal()).thenReturn(user);
when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
assertThat(argument.block()).isEqualTo(user.getId());
}
@Test
public void resolveArgumentWhenMetaThenObtainsPrincipal() throws Exception {
MethodParameter parameter = this.meta.arg(String.class);
when(authentication.getPrincipal()).thenReturn("user");
when(exchange.getPrincipal()).thenReturn(Mono.just(authentication));
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
assertThat(argument.block()).isEqualTo("user");
}
void authenticationPrincipal(@AuthenticationPrincipal String principal, @AuthenticationPrincipal Mono<String> monoPrincipal) {}
void spel(@AuthenticationPrincipal(expression = "id") Long id) {}
void meta(@CurrentUser String principal) {}
static class MyUser {
private final Long id;
MyUser(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
}
@Target({ ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {}
}

View File

@@ -0,0 +1,83 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
* @since 5.0
*/
public class HttpBasicAuthenticationConverterTests {
HttpBasicAuthenticationConverter converter = new HttpBasicAuthenticationConverter();
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/");
@Test
public void applyWhenNoAuthorizationHeaderThenEmpty() {
Mono<Authentication> result = converter.apply(request.toExchange());
assertThat(result.block()).isNull();
}
@Test
public void applyWhenEmptyAuthorizationHeaderThenEmpty() {
Mono<Authentication> result = converter.apply(request.header(HttpHeaders.AUTHORIZATION, "").toExchange());
assertThat(result.block()).isNull();
}
@Test
public void applyWhenOnlyBasicAuthorizationHeaderThenEmpty() {
Mono<Authentication> result = converter.apply(request.header(HttpHeaders.AUTHORIZATION, "Basic ").toExchange());
assertThat(result.block()).isNull();
}
@Test
public void applyWhenNotBase64ThenEmpty() {
Mono<Authentication> result = converter.apply(request.header(HttpHeaders.AUTHORIZATION, "Basic z").toExchange());
assertThat(result.block()).isNull();
}
@Test
public void applyWhenNoSemicolonThenEmpty() {
Mono<Authentication> result = converter.apply(request.header(HttpHeaders.AUTHORIZATION, "Basic dXNlcg==").toExchange());
assertThat(result.block()).isNull();
}
@Test
public void applyWhenUserPasswordThenAuthentication() {
Mono<Authentication> result = converter.apply(request.header(HttpHeaders.AUTHORIZATION, "Basic dXNlcjpwYXNzd29yZA==").toExchange());
UsernamePasswordAuthenticationToken authentication = result.cast(UsernamePasswordAuthenticationToken.class).block();
assertThat(authentication.getPrincipal()).isEqualTo("user");
assertThat(authentication.getCredentials()).isEqualTo("password");
}
}

View File

@@ -0,0 +1,235 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.authentication;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
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.AuthenticationEntryPoint;
import org.springframework.test.web.reactive.server.EntityExchangeResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.function.Function;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;
/**
* @author Rob Winch
* @since 5.0
*/
@RunWith(MockitoJUnitRunner.class)
public class AuthenticationWebFilterTests {
@Mock
AuthenticationSuccessHandler successHandler;
@Mock
Function<ServerWebExchange,Mono<Authentication>> authenticationConverter;
@Mock
ReactiveAuthenticationManager authenticationManager;
@Mock
AuthenticationEntryPoint entryPoint;
AuthenticationWebFilter filter;
@Before
public void setup() {
filter = new AuthenticationWebFilter(authenticationManager);
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationConverter(authenticationConverter);
filter.setEntryPoint(entryPoint);
}
@Test
public void filterWhenDefaultsAndNoAuthenticationThenContinues() {
filter = new AuthenticationWebFilter(authenticationManager);
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(filter)
.build();
EntityExchangeResult<byte[]> result = client.get()
.uri("/")
.exchange()
.expectStatus().isOk()
.expectBody().consumeAsStringWith(b -> assertThat(b).isEqualTo("ok"))
.returnResult();
verifyZeroInteractions(authenticationManager);
assertThat(result.getResponseCookies()).isEmpty();
}
@Test
public void filterWhenDefaultsAndAuthenticationSuccessThenContinues() {
when(authenticationManager.authenticate(any())).thenReturn(Mono.just(new TestingAuthenticationToken("test","this", "ROLE")));
filter = new AuthenticationWebFilter(authenticationManager);
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(filter)
.build();
EntityExchangeResult<byte[]> result = client
.filter(basicAuthentication("test","this"))
.get()
.uri("/")
.exchange()
.expectStatus().isOk()
.expectBody().consumeAsStringWith(b -> assertThat(b).isEqualTo("ok"))
.returnResult();
assertThat(result.getResponseCookies()).isEmpty();
}
@Test
public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() {
when(authenticationManager.authenticate(any())).thenReturn(Mono.error(new BadCredentialsException("failed")));
filter = new AuthenticationWebFilter(authenticationManager);
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(filter)
.build();
EntityExchangeResult<Void> result = client
.filter(basicAuthentication("test", "this"))
.get()
.uri("/")
.exchange()
.expectStatus().isUnauthorized()
.expectHeader().valueMatches("WWW-Authenticate", "Basic realm=\"Realm\"")
.expectBody().isEmpty();
assertThat(result.getResponseCookies()).isEmpty();
}
@Test
public void filterWhenConvertEmptyThenOk() {
when(authenticationConverter.apply(any())).thenReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(filter)
.build();
EntityExchangeResult<byte[]> result = client
.get()
.uri("/")
.exchange()
.expectStatus().isOk()
.expectBody().consumeAsStringWith(b -> assertThat(b).isEqualTo("ok"))
.returnResult();
verifyZeroInteractions(authenticationManager, successHandler, entryPoint);
}
@Test
public void filterWhenConvertErrorThenServerError() {
when(authenticationConverter.apply(any())).thenReturn(Mono.error(new RuntimeException("Unexpected")));
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(filter)
.build();
client
.get()
.uri("/")
.exchange()
.expectStatus().is5xxServerError()
.expectBody().isEmpty();
verifyZeroInteractions(authenticationManager, successHandler, entryPoint);
}
@Test
public void filterWhenConvertAndAuthenticationSuccessThenSuccessHandler() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
when(authenticationConverter.apply(any())).thenReturn(authentication);
when(authenticationManager.authenticate(any())).thenReturn(authentication);
when(successHandler.success(any(),any(),any())).thenReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(filter)
.build();
client
.get()
.uri("/")
.exchange()
.expectStatus().isOk()
.expectBody().isEmpty();
verify(successHandler).success(eq(authentication.block()), any(), any());
verifyZeroInteractions(entryPoint);
}
@Test
public void filterWhenConvertAndAuthenticationFailThenEntryPoint() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
when(authenticationConverter.apply(any())).thenReturn(authentication);
when(authenticationManager.authenticate(any())).thenReturn(Mono.error(new BadCredentialsException("Failed")));
when(entryPoint.commence(any(),any())).thenReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(filter)
.build();
client
.get()
.uri("/")
.exchange()
.expectStatus().isOk()
.expectBody().isEmpty();
verify(entryPoint).commence(any(),any());
verifyZeroInteractions(successHandler);
}
@Test
public void filterWhenConvertAndAuthenticationExceptionThenServerError() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
when(authenticationConverter.apply(any())).thenReturn(authentication);
when(authenticationManager.authenticate(any())).thenReturn(Mono.error(new RuntimeException("Failed")));
when(entryPoint.commence(any(),any())).thenReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(filter)
.build();
client
.get()
.uri("/")
.exchange()
.expectStatus().is5xxServerError()
.expectBody().isEmpty();
verifyZeroInteractions(successHandler, entryPoint);
}
}

View File

@@ -0,0 +1,92 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.context;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.security.test.web.reactive.server.WebTestHandler;
import reactor.core.publisher.Mono;
import java.security.Principal;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
/**
* @author Rob Winch
* @since 5.0
*/
@RunWith(MockitoJUnitRunner.class)
public class SecurityContextRepositoryWebFilterTests {
@Mock
SecurityContextRepository repository;
MockServerHttpRequest.BaseBuilder<?> exchange = MockServerHttpRequest.get("/");
SecurityContextRepositoryWebFilter filter;
WebTestHandler filters;
@Before
public void setup() {
filter = new SecurityContextRepositoryWebFilter(repository);
filters = WebTestHandler.bindToWebFilters(filter);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullSecurityContextRepository() {
SecurityContextRepository repository = null;
new SecurityContextRepositoryWebFilter(repository);
}
@Test
public void filterWhenNoPrincipalAccessThenNoInteractions() {
filters.exchange(exchange);
verifyZeroInteractions(repository);
}
@Test
public void filterWhenGetPrincipalMonoThenNoInteractions() {
filters = WebTestHandler.bindToWebFilters(filter, (e,c) -> {
Mono<Principal> p = e.getPrincipal();
return c.filter(e);
});
filters.exchange(exchange);
verifyZeroInteractions(repository);
}
@Test
public void filterWhenGetPrincipalThenInteract() {
when(repository.load(any())).thenReturn(Mono.empty());
filters = WebTestHandler.bindToWebFilters(filter, (e,c) -> e.getPrincipal().flatMap( p-> c.filter(e))) ;
filters.exchange(exchange);
verify(repository).load(any());
}
}

View File

@@ -0,0 +1,83 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.header;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
/**
*
* @author Rob Winch
* @since 5.0
*
*/
public class CacheControlHttpHeadersWriterTests {
CacheControlHttpHeadersWriter writer = new CacheControlHttpHeadersWriter();
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
HttpHeaders headers = exchange.getResponse().getHeaders();
@Test
public void writeHeadersWhenCacheHeadersThenWritesAllCacheControl() {
writer.writeHttpHeaders(exchange);
assertThat(headers).hasSize(3);
assertThat(headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(CacheControlHttpHeadersWriter.CACHE_CONTRTOL_VALUE);
assertThat(headers.get(HttpHeaders.EXPIRES)).containsOnly(CacheControlHttpHeadersWriter.EXPIRES_VALUE);
assertThat(headers.get(HttpHeaders.PRAGMA)).containsOnly(CacheControlHttpHeadersWriter.PRAGMA_VALUE);
}
@Test
public void writeHeadersWhenCacheControlThenNoCacheControlHeaders() {
String cacheControl = "max-age=1234";
headers.set(HttpHeaders.CACHE_CONTROL, cacheControl);
writer.writeHttpHeaders(exchange);
assertThat(headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(cacheControl);
}
@Test
public void writeHeadersWhenPragmaThenNoCacheControlHeaders() {
String pragma = "1";
headers.set(HttpHeaders.PRAGMA, pragma);
writer.writeHttpHeaders(exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(HttpHeaders.PRAGMA)).containsOnly(pragma);
}
@Test
public void writeHeadersWhenExpiresThenNoCacheControlHeaders() {
String expires = "1";
headers.set(HttpHeaders.EXPIRES, expires);
writer.writeHttpHeaders(exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(HttpHeaders.EXPIRES)).containsOnly(expires);
}
}

View File

@@ -0,0 +1,102 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.header;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
/**
*
* @author Rob Winch
* @since 5.0
*/
@RunWith(MockitoJUnitRunner.class)
public class CompositeHttpHeadersWriterTests {
@Mock
HttpHeadersWriter writer1;
@Mock
HttpHeadersWriter writer2;
CompositeHttpHeadersWriter writer;
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
@Before
public void setup() {
writer = new CompositeHttpHeadersWriter(Arrays.asList(writer1, writer2));
}
@Test
public void writeHttpHeadersWhenErrorNoErrorThenError() {
when(writer1.writeHttpHeaders(exchange)).thenReturn(Mono.error(new RuntimeException()));
when(writer2.writeHttpHeaders(exchange)).thenReturn(Mono.empty());
Mono<Void> result = writer.writeHttpHeaders(exchange);
StepVerifier.create(result)
.expectError()
.verify();
verify(writer1).writeHttpHeaders(exchange);
verify(writer2).writeHttpHeaders(exchange);
}
@Test
public void writeHttpHeadersWhenErrorErrorThenError() {
when(writer1.writeHttpHeaders(exchange)).thenReturn(Mono.error(new RuntimeException()));
when(writer2.writeHttpHeaders(exchange)).thenReturn(Mono.error(new RuntimeException()));
Mono<Void> result = writer.writeHttpHeaders(exchange);
StepVerifier.create(result)
.expectError()
.verify();
verify(writer1).writeHttpHeaders(exchange);
verify(writer2).writeHttpHeaders(exchange);
}
@Test
public void writeHttpHeadersWhenNoErrorThenNoError() {
when(writer1.writeHttpHeaders(exchange)).thenReturn(Mono.empty());
when(writer2.writeHttpHeaders(exchange)).thenReturn(Mono.empty());
Mono<Void> result = writer.writeHttpHeaders(exchange);
StepVerifier.create(result)
.expectComplete()
.verify();
verify(writer1).writeHttpHeaders(exchange);
verify(writer2).writeHttpHeaders(exchange);
}
}

View File

@@ -0,0 +1,77 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.header;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.security.test.web.reactive.server.WebTestHandler;
import org.springframework.security.test.web.reactive.server.WebTestHandler.WebHandlerResult;
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;
/**
*
* @author Rob Winch
* @since 5.0
*/
@RunWith(MockitoJUnitRunner.class)
public class HttpHeaderWriterWebFilterTests {
@Mock
HttpHeadersWriter writer;
HttpHeaderWriterWebFilter filter;
@Before
public void setup() {
when(writer.writeHttpHeaders(any())).thenReturn(Mono.empty());
filter = new HttpHeaderWriterWebFilter(writer);
}
@Test
public void filterWhenCompleteThenWritten() {
WebTestClient rest = WebTestClientBuilder.bindToWebFilters(filter).build();
rest.get().uri("/foo").exchange();
verify(writer).writeHttpHeaders(any());
}
@Test
public void filterWhenNotCompleteThenNotWritten() {
WebTestHandler handler = WebTestHandler.bindToWebFilters(filter);
WebHandlerResult result = handler.exchange(MockServerHttpRequest.get("/foo"));
verify(writer, never()).writeHttpHeaders(any());
result.getExchange().getResponse().setComplete();
verify(writer).writeHttpHeaders(any());
}
}

View File

@@ -0,0 +1,89 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.header;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
/**
* @author Rob Winch
* @since 5.0
*/
public class StaticHttpHeadersWriterTests {
StaticHttpHeadersWriter writer = StaticHttpHeadersWriter.builder()
.header(ContentTypeOptionsHttpHeadersWriter.X_CONTENT_OPTIONS, ContentTypeOptionsHttpHeadersWriter.NOSNIFF)
.build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
HttpHeaders headers = exchange.getResponse().getHeaders();
@Test
public void writeHeadersWhenSingleHeaderThenWritesHeader() {
writer.writeHttpHeaders(exchange);
assertThat(headers.get(ContentTypeOptionsHttpHeadersWriter.X_CONTENT_OPTIONS)).containsOnly(ContentTypeOptionsHttpHeadersWriter.NOSNIFF);
}
@Test
public void writeHeadersWhenSingleHeaderAndHeaderWrittenThenSuccess() {
String headerValue = "other";
headers.set(ContentTypeOptionsHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue);
writer.writeHttpHeaders(exchange);
assertThat(headers.get(ContentTypeOptionsHttpHeadersWriter.X_CONTENT_OPTIONS)).containsOnly(headerValue);
}
@Test
public void writeHeadersWhenMultiHeaderThenWritesAllHeaders() {
writer = StaticHttpHeadersWriter.builder()
.header(HttpHeaders.CACHE_CONTROL, CacheControlHttpHeadersWriter.CACHE_CONTRTOL_VALUE)
.header(HttpHeaders.PRAGMA, CacheControlHttpHeadersWriter.PRAGMA_VALUE)
.header(HttpHeaders.EXPIRES, CacheControlHttpHeadersWriter.EXPIRES_VALUE)
.build();
writer.writeHttpHeaders(exchange);
assertThat(headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(CacheControlHttpHeadersWriter.CACHE_CONTRTOL_VALUE);
assertThat(headers.get(HttpHeaders.PRAGMA)).containsOnly(CacheControlHttpHeadersWriter.PRAGMA_VALUE);
assertThat(headers.get(HttpHeaders.EXPIRES)).containsOnly(CacheControlHttpHeadersWriter.EXPIRES_VALUE);
}
@Test
public void writeHeadersWhenMultiHeaderAndSingleWrittenThenNoHeadersOverridden() {
String headerValue = "other";
headers.set(HttpHeaders.CACHE_CONTROL, headerValue);
writer = StaticHttpHeadersWriter.builder()
.header(HttpHeaders.CACHE_CONTROL, CacheControlHttpHeadersWriter.CACHE_CONTRTOL_VALUE)
.header(HttpHeaders.PRAGMA, CacheControlHttpHeadersWriter.PRAGMA_VALUE)
.header(HttpHeaders.EXPIRES, CacheControlHttpHeadersWriter.EXPIRES_VALUE)
.build();
writer.writeHttpHeaders(exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(headerValue);
}
}

View File

@@ -0,0 +1,97 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.header;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.Arrays;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
/**
* @author Rob Winch
* @since 5.0
*/
public class StrictTransportSecurityHttpHeadersWriterTests {
StrictTransportSecurityHttpHeadersWriter hsts = new StrictTransportSecurityHttpHeadersWriter();
ServerWebExchange exchange;
@Test
public void writeHttpHeadersWhenHttpsThenWrites() {
exchange = MockServerHttpRequest.get("https://example.com/").toExchange();
hsts.writeHttpHeaders(exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers).containsEntry(StrictTransportSecurityHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
Arrays.asList("max-age=31536000 ; includeSubDomains"));
}
@Test
public void writeHttpHeadersWhenCustomMaxAgeThenWrites() {
Duration maxAge = Duration.ofDays(1);
hsts.setMaxAge(maxAge);
exchange = MockServerHttpRequest.get("https://example.com/").toExchange();
hsts.writeHttpHeaders(exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers).containsEntry(StrictTransportSecurityHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
Arrays.asList("max-age=" + maxAge.getSeconds() + " ; includeSubDomains"));
}
@Test
public void writeHttpHeadersWhenCustomIncludeSubDomainsThenWrites() {
hsts.setIncludeSubDomains(false);
exchange = MockServerHttpRequest.get("https://example.com/").toExchange();
hsts.writeHttpHeaders(exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers).containsEntry(StrictTransportSecurityHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
Arrays.asList("max-age=31536000"));
}
@Test
public void writeHttpHeadersWhenNullSchemeThenNoHeaders() {
exchange = MockServerHttpRequest.get("/").toExchange();
hsts.writeHttpHeaders(exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
assertThat(headers).isEmpty();
}
@Test
public void writeHttpHeadersWhenHttpThenNoHeaders() {
exchange = MockServerHttpRequest.get("http://example.com/").toExchange();
hsts.writeHttpHeaders(exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
assertThat(headers).isEmpty();
}
}

View File

@@ -0,0 +1,57 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.header;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
/**
* @author Rob Winch
* @since 5.0
*/
public class XContentTypeOptionsHttpHeadersWriterTests {
ContentTypeOptionsHttpHeadersWriter writer = new ContentTypeOptionsHttpHeadersWriter();
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
HttpHeaders headers = exchange.getResponse().getHeaders();
@Test
public void writeHeadersWhenNoHeadersThenWriteHeaders() {
writer.writeHttpHeaders(exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(ContentTypeOptionsHttpHeadersWriter.X_CONTENT_OPTIONS)).containsOnly(ContentTypeOptionsHttpHeadersWriter.NOSNIFF);
}
@Test
public void writeHeadersWhenHeaderWrittenThenDoesNotOverrride() {
String headerValue = "value";
headers.set(ContentTypeOptionsHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue);
writer.writeHttpHeaders(exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(ContentTypeOptionsHttpHeadersWriter.X_CONTENT_OPTIONS)).containsOnly(headerValue);
}
}

View File

@@ -0,0 +1,86 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.header;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
/**
* @author Rob Winch
* @since 5.0
*/
public class XFrameOptionsHttpHeadersWriterTests {
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
XFrameOptionsHttpHeadersWriter writer;
@Before
public void setup() {
writer = new XFrameOptionsHttpHeadersWriter();
}
@Test
public void writeHeadersWhenUsingDefaultsThenWritesDeny() {
writer.writeHttpHeaders(exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers.get(XFrameOptionsHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("DENY");
}
@Test
public void writeHeadersWhenUsingExplicitDenyThenWritesDeny() {
writer.setMode(XFrameOptionsHttpHeadersWriter.Mode.DENY);
writer.writeHttpHeaders(exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers.get(XFrameOptionsHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("DENY");
}
@Test
public void writeHeadersWhenUsingSameOriginThenWritesSameOrigin() {
writer.setMode(XFrameOptionsHttpHeadersWriter.Mode.SAMEORIGIN);
writer.writeHttpHeaders(exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers.get(XFrameOptionsHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("SAMEORIGIN");
}
@Test
public void writeHeadersWhenAlreadyWrittenThenWritesHeader() {
String headerValue = "other";
exchange.getResponse().getHeaders().set(XFrameOptionsHttpHeadersWriter.X_FRAME_OPTIONS, headerValue);
writer.writeHttpHeaders(exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers.get(XFrameOptionsHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly(headerValue);
}
}

View File

@@ -0,0 +1,77 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.header;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
/**
* @author Rob Winch
* @since 5.0
*/
public class XXssProtectionHttpHeadersWriterTests {
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
HttpHeaders headers = exchange.getResponse().getHeaders();
XXssProtectionHttpHeadersWriter writer = new XXssProtectionHttpHeadersWriter();
@Test
public void writeHeadersWhenNoHeadersThenWriteHeaders() {
writer.writeHttpHeaders(exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(XXssProtectionHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("1 ; mode=block");
}
@Test
public void writeHeadersWhenBlockFalseThenWriteHeaders() {
writer.setBlock(false);
writer.writeHttpHeaders(exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(XXssProtectionHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("1");
}
@Test
public void writeHeadersWhenEnabledFalseThenWriteHeaders() {
writer.setEnabled(false);
writer.writeHttpHeaders(exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(XXssProtectionHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("0");
}
@Test
public void writeHeadersWhenHeaderWrittenThenDoesNotOverrride() {
String headerValue = "value";
headers.set(XXssProtectionHttpHeadersWriter.X_XSS_PROTECTION, headerValue);
writer.writeHttpHeaders(exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(XXssProtectionHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly(headerValue);
}
}

View File

@@ -0,0 +1,116 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.util.matcher;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.web.server.ServerWebExchange;
import java.util.Collections;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
* @since 5.0
*/
@RunWith(MockitoJUnitRunner.class)
public class AndServerWebExchangeMatcherTests {
@Mock
ServerWebExchange exchange;
@Mock
ServerWebExchangeMatcher matcher1;
@Mock
ServerWebExchangeMatcher matcher2;
AndServerWebExchangeMatcher matcher;
@Before
public void setUp() throws Exception {
matcher = new AndServerWebExchangeMatcher(matcher1, matcher2);
}
@Test
public void matchesWhenTrueTrueThenTrue() throws Exception {
Map<String, Object> params1 = Collections.singletonMap("foo", "bar");
Map<String, Object> params2 = Collections.singletonMap("x", "y");
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params1));
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params2));
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange);
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).hasSize(2);
assertThat(matches.getVariables()).containsAllEntriesOf(params1);
assertThat(matches.getVariables()).containsAllEntriesOf(params2);
verify(matcher1).matches(exchange);
verify(matcher2).matches(exchange);
}
@Test
public void matchesWhenFalseFalseThenFalseAndMatcher2NotInvoked() throws Exception {
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange);
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(matcher1).matches(exchange);
verify(matcher2, never()).matches(exchange);
}
@Test
public void matchesWhenTrueFalseThenFalse() throws Exception {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange);
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(matcher1).matches(exchange);
verify(matcher2).matches(exchange);
}
@Test
public void matchesWhenFalseTrueThenFalse() throws Exception {
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange);
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(matcher1).matches(exchange);
verify(matcher2, never()).matches(exchange);
}
}

View File

@@ -0,0 +1,99 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.util.matcher;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.web.server.ServerWebExchange;
import java.util.Collections;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
* @since 5.0
*/
@RunWith(MockitoJUnitRunner.class)
public class OrServerWebExchangeMatcherTests {
@Mock
ServerWebExchange exchange;
@Mock
ServerWebExchangeMatcher matcher1;
@Mock
ServerWebExchangeMatcher matcher2;
OrServerWebExchangeMatcher matcher;
@Before
public void setUp() throws Exception {
matcher = new OrServerWebExchangeMatcher(matcher1, matcher2);
}
@Test
public void matchesWhenFalseFalseThenFalse() throws Exception {
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange);
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(matcher1).matches(exchange);
verify(matcher2).matches(exchange);
}
@Test
public void matchesWhenTrueFalseThenTrueAndMatcher2NotInvoked() throws Exception {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange);
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEqualTo(params);
verify(matcher1).matches(exchange);
verify(matcher2, never()).matches(exchange);
}
@Test
public void matchesWhenFalseTrueThenTrue() throws Exception {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange);
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEqualTo(params);
verify(matcher1).matches(exchange);
verify(matcher2).matches(exchange);
}
}

View File

@@ -0,0 +1,115 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.util.matcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.HttpMethod;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.MockServerWebExchange;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.DefaultWebSessionManager;
/**
* @author Rob Winch
* @since 5.0
*/
@RunWith(MockitoJUnitRunner.class)
public class PathMatcherServerWebExchangeMatcherTests {
@Mock
PathMatcher pathMatcher;
MockServerWebExchange exchange;
PathMatcherServerWebExchangeMatcher matcher;
String pattern;
String path;
@Before
public void setup() {
MockServerHttpRequest request = MockServerHttpRequest.post("/path").build();
MockServerHttpResponse response = new MockServerHttpResponse();
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
exchange = request.toExchange();
pattern = "/pattern";
path = "/path";
matcher = new PathMatcherServerWebExchangeMatcher(pattern);
matcher.setPathMatcher(pathMatcher);
}
@Test(expected = IllegalArgumentException.class)
public void constructorPatternWhenPatternNullThenThrowsException() {
new PathMatcherServerWebExchangeMatcher(null);
}
@Test(expected = IllegalArgumentException.class)
public void constructorPatternAndMethodWhenPatternNullThenThrowsException() {
new PathMatcherServerWebExchangeMatcher(null, HttpMethod.GET);
}
@Test
public void matchesWhenPathMatcherTrueThenReturnTrue() {
when(pathMatcher.match(pattern, path)).thenReturn(true);
assertThat(matcher.matches(exchange).isMatch()).isTrue();
}
@Test
public void matchesWhenPathMatcherFalseThenReturnFalse() {
when(pathMatcher.match(pattern, path)).thenReturn(false);
assertThat(matcher.matches(exchange).isMatch()).isFalse();
verify(pathMatcher).match(pattern, path);
}
@Test
public void matchesWhenPathMatcherTrueAndMethodTrueThenReturnTrue() {
matcher = new PathMatcherServerWebExchangeMatcher(pattern, exchange.getRequest().getMethod());
matcher.setPathMatcher(pathMatcher);
when(pathMatcher.match(pattern, path)).thenReturn(true);
assertThat(matcher.matches(exchange).isMatch()).isTrue();
}
@Test
public void matchesWhenPathMatcherTrueAndMethodFalseThenReturnFalse() {
HttpMethod method = HttpMethod.OPTIONS;
assertThat(exchange.getRequest().getMethod()).isNotEqualTo(method);
matcher = new PathMatcherServerWebExchangeMatcher(pattern, method);
matcher.setPathMatcher(pathMatcher);
assertThat(matcher.matches(exchange).isMatch()).isFalse();
verifyZeroInteractions(pathMatcher);
}
@Test(expected = IllegalArgumentException.class)
public void setPathMatcherWhenNullThenThrowException() {
matcher.setPathMatcher(null);
}
}

View File

@@ -0,0 +1,86 @@
/*
*
* * 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
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.security.web.server.util.matcher;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.antMatchers;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.anyExchange;
/**
* @author Rob Winch
* @since 5.0
*/
public class ServerWebExchangeMatchersTests {
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
@Test
public void antMatchersWhenSingleAndSamePatternThenMatches() throws Exception {
assertThat(antMatchers("/").matches(exchange).isMatch()).isTrue();
}
@Test
public void antMatchersWhenSingleAndSamePatternAndMethodThenMatches() throws Exception {
assertThat(antMatchers(HttpMethod.GET, "/").matches(exchange).isMatch()).isTrue();
}
@Test
public void antMatchersWhenSingleAndSamePatternAndDiffMethodThenDoesNotMatch() throws Exception {
assertThat(antMatchers(HttpMethod.POST, "/").matches(exchange).isMatch()).isFalse();
}
@Test
public void antMatchersWhenSingleAndDifferentPatternThenDoesNotMatch() throws Exception {
assertThat(antMatchers("/foobar").matches(exchange).isMatch()).isFalse();
}
@Test
public void antMatchersWhenMultiThenMatches() throws Exception {
assertThat(antMatchers("/foobar", "/").matches(exchange).isMatch()).isTrue();
}
@Test
public void anyExchangeWhenMockThenMatches() {
ServerWebExchange mockExchange = mock(ServerWebExchange.class);
assertThat(anyExchange().matches(mockExchange).isMatch()).isTrue();
verifyZeroInteractions(mockExchange);
}
/**
* If a LinkedMap is used and anyRequest equals anyRequest then the following is added:
* anyRequest() -> authenticated()
* antMatchers("/admin/**") -> hasRole("ADMIN")
* anyRequest() -> permitAll
*
* will result in the first entry being overridden
*/
@Test
public void anyExchangeWhenTwoCreatedThenDifferentToPreventIssuesInMap() {
assertThat(anyExchange()).isNotEqualTo(anyExchange());
}
}