From d23e431020cece6adc7e9bf37055bf4b9eeae865 Mon Sep 17 00:00:00 2001 From: HappyTobi Date: Tue, 26 Nov 2019 09:40:44 +0100 Subject: [PATCH 1/7] New quota filter for spring cloud gateway --- .../config/GatewayAutoConfiguration.java | 15 +- .../config/GatewayRedisAutoConfiguration.java | 21 +- .../RequestQuotaGatewayFilterFactory.java | 207 ++++++++++ .../{ratelimit => redis}/KeyResolver.java | 2 +- .../PrincipalNameKeyResolver.java | 2 +- .../redis/quota/AbstractQuotaLimiter.java | 91 +++++ .../filter/redis/quota/QuotaFilter.java | 65 +++ .../filter/redis/quota/RedisQuotaFilter.java | 376 ++++++++++++++++++ .../route/builder/GatewayFilterSpec.java | 56 ++- .../scripts/request_quota_limiter.lua | 25 ++ ...tRateLimiterGatewayFilterFactoryTests.java | 6 +- ...ncipalNameKeyResolverIntegrationTests.java | 163 ++++++++ .../quota/RedisQuotaFilterConfigTests.java | 141 +++++++ ...isQuotaFilterDefaultFilterConfigTests.java | 82 ++++ .../redis/quota/RedisQuotaFilterTests.java | 161 ++++++++ .../application-redis-quota-filter-config.yml | 17 + ...tion-redis-quota-filter-default-config.yml | 14 + 17 files changed, 1433 insertions(+), 11 deletions(-) create mode 100644 spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestQuotaGatewayFilterFactory.java rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{ratelimit => redis}/KeyResolver.java (93%) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{ratelimit => redis}/PrincipalNameKeyResolver.java (94%) create mode 100644 spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/AbstractQuotaLimiter.java create mode 100644 spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/QuotaFilter.java create mode 100644 spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilter.java create mode 100644 spring-cloud-gateway-core/src/main/resources/META-INF/scripts/request_quota_limiter.lua create mode 100644 spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/PrincipalNameKeyResolverIntegrationTests.java create mode 100644 spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterConfigTests.java create mode 100644 spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterDefaultFilterConfigTests.java create mode 100644 spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterTests.java create mode 100644 spring-cloud-gateway-core/src/test/resources/application-redis-quota-filter-config.yml create mode 100644 spring-cloud-gateway-core/src/test/resources/application-redis-quota-filter-default-config.yml diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java index 581a032aa0..cf2ea2698d 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java @@ -78,6 +78,7 @@ import org.springframework.cloud.gateway.filter.factory.RemoveResponseHeaderGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.RequestHeaderSizeGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.RequestHeaderToRequestUriGatewayFilterFactory; +import org.springframework.cloud.gateway.filter.factory.RequestQuotaGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.RequestRateLimiterGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.RequestSizeGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.RetryGatewayFilterFactory; @@ -98,9 +99,10 @@ import org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter; import org.springframework.cloud.gateway.filter.headers.RemoveHopByHopHeadersFilter; import org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter; -import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; -import org.springframework.cloud.gateway.filter.ratelimit.PrincipalNameKeyResolver; -import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; +import org.springframework.cloud.gateway.filter.redis.KeyResolver; +import org.springframework.cloud.gateway.filter.redis.PrincipalNameKeyResolver; +import org.springframework.cloud.gateway.filter.redis.quota.QuotaFilter; +import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter; import org.springframework.cloud.gateway.handler.FilteringWebHandler; import org.springframework.cloud.gateway.handler.RoutePredicateHandlerMapping; import org.springframework.cloud.gateway.handler.predicate.AfterRoutePredicateFactory; @@ -487,6 +489,13 @@ public RequestRateLimiterGatewayFilterFactory requestRateLimiterGatewayFilterFac return new RequestRateLimiterGatewayFilterFactory(rateLimiter, resolver); } + @Bean + @ConditionalOnBean({ QuotaFilter.class, KeyResolver.class }) + public RequestQuotaGatewayFilterFactory requestQuotaGatewayFilterFactory( + QuotaFilter quotaFilter, KeyResolver resolver) { + return new RequestQuotaGatewayFilterFactory(quotaFilter, resolver); + } + @Bean public RewritePathGatewayFilterFactory rewritePathGatewayFilterFactory() { return new RewritePathGatewayFilterFactory(); diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayRedisAutoConfiguration.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayRedisAutoConfiguration.java index 28d55a4fd8..e1663080c6 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayRedisAutoConfiguration.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayRedisAutoConfiguration.java @@ -25,7 +25,8 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration; -import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; +import org.springframework.cloud.gateway.filter.redis.quota.RedisQuotaFilter; +import org.springframework.cloud.gateway.filter.redis.ratelimit.RedisRateLimiter; import org.springframework.cloud.gateway.support.ConfigurationService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -55,6 +56,16 @@ public RedisScript redisRequestRateLimiterScript() { return redisScript; } + @Bean + @SuppressWarnings("unchecked") + public RedisScript redisRequestQuotaLimiterScript() { + DefaultRedisScript redisScript = new DefaultRedisScript<>(); + redisScript.setScriptSource(new ResourceScriptSource( + new ClassPathResource("META-INF/scripts/request_quota_limiter.lua"))); + redisScript.setResultType(List.class); + return redisScript; + } + @Bean @ConditionalOnMissingBean public RedisRateLimiter redisRateLimiter(ReactiveStringRedisTemplate redisTemplate, @@ -63,4 +74,12 @@ public RedisRateLimiter redisRateLimiter(ReactiveStringRedisTemplate redisTempla return new RedisRateLimiter(redisTemplate, redisScript, configurationService); } + @Bean + @ConditionalOnMissingBean + public RedisQuotaFilter redisQuotaFilter(ReactiveStringRedisTemplate redisTemplate, + @Qualifier(RedisQuotaFilter.REDIS_SCRIPT_NAME) RedisScript> redisScript, + ConfigurationService configurationService) { + return new RedisQuotaFilter(redisTemplate, redisScript, configurationService); + } + } diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestQuotaGatewayFilterFactory.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestQuotaGatewayFilterFactory.java new file mode 100644 index 0000000000..bfbeebdfbf --- /dev/null +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestQuotaGatewayFilterFactory.java @@ -0,0 +1,207 @@ +/* + * Copyright 2013-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.cloud.gateway.filter.factory; + +import java.util.Map; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.gateway.filter.GatewayFilter; +import org.springframework.cloud.gateway.filter.redis.KeyResolver; +import org.springframework.cloud.gateway.filter.redis.quota.QuotaFilter; +import org.springframework.cloud.gateway.route.Route; +import org.springframework.cloud.gateway.support.HasRouteId; +import org.springframework.cloud.gateway.support.HttpStatusHolder; +import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; +import org.springframework.http.HttpStatus; + +import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.setResponseStatus; + +/** + * @author Tobias Schug + */ +@ConfigurationProperties("spring.cloud.gateway.filter.request-quota-filter") +public class RequestQuotaGatewayFilterFactory + extends AbstractGatewayFilterFactory { + + /** + * Key-Resolver key. + */ + public static final String KEY_RESOLVER_KEY = "keyResolver"; + + private static final String EMPTY_KEY = "____EMPTY_KEY__"; + + private final QuotaFilter defaultQuotaFilter; + + private final KeyResolver defaultKeyResolver; + + /** + * Switch to deny requests if the Key Resolver returns an empty key, defaults to true. + */ + private boolean denyEmptyKey = true; + + /** HttpStatus to return when denyEmptyKey is true, defaults to FORBIDDEN. */ + private String emptyKeyStatusCode = HttpStatus.FORBIDDEN.name(); + + public RequestQuotaGatewayFilterFactory(QuotaFilter defaultQuotaFilter, + KeyResolver defaultKeyResolver) { + super(Config.class); + this.defaultQuotaFilter = defaultQuotaFilter; + this.defaultKeyResolver = defaultKeyResolver; + } + + public KeyResolver getDefaultKeyResolver() { + return defaultKeyResolver; + } + + public QuotaFilter getDefaultQuotaFilter() { + return defaultQuotaFilter; + } + + public boolean isDenyEmptyKey() { + return denyEmptyKey; + } + + public void setDenyEmptyKey(boolean denyEmptyKey) { + this.denyEmptyKey = denyEmptyKey; + } + + public String getEmptyKeyStatusCode() { + return emptyKeyStatusCode; + } + + public void setEmptyKeyStatusCode(String emptyKeyStatusCode) { + this.emptyKeyStatusCode = emptyKeyStatusCode; + } + + @SuppressWarnings("unchecked") + @Override + public GatewayFilter apply(Config config) { + KeyResolver resolver = getOrDefault(config.keyResolver, defaultKeyResolver); + QuotaFilter limiter = getOrDefault(config.quotaFilter, + defaultQuotaFilter); + boolean denyEmpty = getOrDefault(config.denyEmptyKey, this.denyEmptyKey); + HttpStatusHolder emptyKeyStatus = HttpStatusHolder + .parse(getOrDefault(config.emptyKeyStatus, this.emptyKeyStatusCode)); + + return (exchange, chain) -> resolver.resolve(exchange).defaultIfEmpty(EMPTY_KEY) + .flatMap(key -> { + if (EMPTY_KEY.equals(key)) { + if (denyEmpty) { + setResponseStatus(exchange, emptyKeyStatus); + return exchange.getResponse().setComplete(); + } + return chain.filter(exchange); + } + String routeId = config.getRouteId(); + if (routeId == null) { + Route route = exchange + .getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR); + routeId = route.getId(); + } + return limiter.isAllowed(routeId, key).flatMap(response -> { + for (Map.Entry header : response.getHeaders() + .entrySet()) { + exchange.getResponse().getHeaders().add(header.getKey(), + header.getValue()); + } + + if (response.isAllowed()) { + return chain.filter(exchange); + } + + setResponseStatus(exchange, config.getStatusCode()); + return exchange.getResponse().setComplete(); + }); + }); + } + + private T getOrDefault(T configValue, T defaultValue) { + return (configValue != null) ? configValue : defaultValue; + } + + public static class Config implements HasRouteId { + + private KeyResolver keyResolver; + + private QuotaFilter quotaFilter; + + private HttpStatus statusCode = HttpStatus.TOO_MANY_REQUESTS; + + private Boolean denyEmptyKey; + + private String emptyKeyStatus; + + private String routeId; + + public KeyResolver getKeyResolver() { + return keyResolver; + } + + public Config setKeyResolver(KeyResolver keyResolver) { + this.keyResolver = keyResolver; + return this; + } + + public QuotaFilter getQuotaFilter() { + return quotaFilter; + } + + public Config setQuotaFilter(QuotaFilter quotaFilter) { + this.quotaFilter = quotaFilter; + return this; + } + + public HttpStatus getStatusCode() { + return statusCode; + } + + public Config setStatusCode(HttpStatus statusCode) { + this.statusCode = statusCode; + return this; + } + + public Boolean getDenyEmptyKey() { + return denyEmptyKey; + } + + public Config setDenyEmptyKey(Boolean denyEmptyKey) { + this.denyEmptyKey = denyEmptyKey; + return this; + } + + public String getEmptyKeyStatus() { + return emptyKeyStatus; + } + + public Config setEmptyKeyStatus(String emptyKeyStatus) { + this.emptyKeyStatus = emptyKeyStatus; + return this; + } + + @Override + public void setRouteId(String routeId) { + this.routeId = routeId; + } + + @Override + public String getRouteId() { + return this.routeId; + } + + } + +} diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/KeyResolver.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/KeyResolver.java similarity index 93% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/KeyResolver.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/KeyResolver.java index c15df5ebf2..d524aaf23f 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/KeyResolver.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/KeyResolver.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.ratelimit; +package org.springframework.cloud.gateway.filter.redis; import reactor.core.publisher.Mono; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/PrincipalNameKeyResolver.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/PrincipalNameKeyResolver.java similarity index 94% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/PrincipalNameKeyResolver.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/PrincipalNameKeyResolver.java index a36c7e56a1..02f2f276e6 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/PrincipalNameKeyResolver.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/PrincipalNameKeyResolver.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.ratelimit; +package org.springframework.cloud.gateway.filter.redis; import java.security.Principal; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/AbstractQuotaLimiter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/AbstractQuotaLimiter.java new file mode 100644 index 0000000000..21da6182c9 --- /dev/null +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/AbstractQuotaLimiter.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013-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.cloud.gateway.filter.redis.quota; + +import java.util.Map; + +import org.springframework.cloud.gateway.event.FilterArgsEvent; +import org.springframework.cloud.gateway.support.AbstractStatefulConfigurable; +import org.springframework.cloud.gateway.support.ConfigurationService; +import org.springframework.context.ApplicationListener; +import org.springframework.core.style.ToStringCreator; +import org.springframework.validation.Validator; + +public abstract class AbstractQuotaLimiter extends AbstractStatefulConfigurable + implements QuotaFilter, ApplicationListener { + + private String configurationPropertyName; + + private ConfigurationService configurationService; + + @Deprecated + protected AbstractQuotaLimiter(Class configClass, String configurationPropertyName, + Validator validator) { + super(configClass); + this.configurationPropertyName = configurationPropertyName; + this.configurationService = new ConfigurationService(); + this.configurationService.setValidator(validator); + } + + protected AbstractQuotaLimiter(Class configClass, String configurationPropertyName, + ConfigurationService configurationService) { + super(configClass); + this.configurationPropertyName = configurationPropertyName; + this.configurationService = configurationService; + } + + protected String getConfigurationPropertyName() { + return configurationPropertyName; + } + + protected void setConfigurationService(ConfigurationService configurationService) { + this.configurationService = configurationService; + } + + @Override + public void onApplicationEvent(FilterArgsEvent event) { + Map args = event.getArgs(); + + if (args.isEmpty() || !hasRelevantKey(args)) { + return; + } + + String routeId = event.getRouteId(); + + C routeConfig = newConfig(); + if (this.configurationService != null) { + this.configurationService.with(routeConfig) + .name(this.configurationPropertyName).normalizedProperties(args) + .bind(); + } + getConfig().put(routeId, routeConfig); + } + + private boolean hasRelevantKey(Map args) { + return args.keySet().stream() + .anyMatch(key -> key.startsWith(configurationPropertyName + ".")); + } + + @Override + public String toString() { + return new ToStringCreator(this) + .append("configurationPropertyName", configurationPropertyName) + .append("config", getConfig()).append("configClass", getConfigClass()) + .toString(); + } + +} diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/QuotaFilter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/QuotaFilter.java new file mode 100644 index 0000000000..52e348d5db --- /dev/null +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/QuotaFilter.java @@ -0,0 +1,65 @@ +/* + * Copyright 2017-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.cloud.gateway.filter.redis.quota; + +import java.util.Collections; +import java.util.Map; + +import reactor.core.publisher.Mono; + +import org.springframework.cloud.gateway.support.StatefulConfigurable; +import org.springframework.util.Assert; + +/** + * @author Tobias Schug + */ +public interface QuotaFilter extends StatefulConfigurable { + + Mono isAllowed(String routeId, String id); + + class Response { + + private final boolean allowed; + + private final Map headers; + + public Response(boolean allowed, Map headers) { + this.allowed = allowed; + Assert.notNull(headers, "headers may not be null"); + this.headers = headers; + } + + public boolean isAllowed() { + return allowed; + } + + public Map getHeaders() { + return Collections.unmodifiableMap(headers); + } + + @Override + public String toString() { + final StringBuffer sb = new StringBuffer("Response{"); + sb.append("allowed=").append(allowed); + sb.append(", headers=").append(headers); + sb.append('}'); + return sb.toString(); + } + + } + +} diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilter.java new file mode 100644 index 0000000000..9dc3b3dc0e --- /dev/null +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilter.java @@ -0,0 +1,376 @@ +/* + * Copyright 2017-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.cloud.gateway.filter.redis.quota; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.validation.constraints.Min; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jetbrains.annotations.NotNull; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import org.springframework.beans.BeansException; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator; +import org.springframework.cloud.gateway.support.ConfigurationService; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.data.redis.core.ReactiveStringRedisTemplate; +import org.springframework.data.redis.core.script.RedisScript; +import org.springframework.util.Assert; +import org.springframework.validation.annotation.Validated; + +/** + * @author Tobias Schug + */ +@ConfigurationProperties("spring.cloud.gateway.redis-quota-filter") +public class RedisQuotaFilter extends AbstractQuotaLimiter + implements ApplicationContextAware { + + /** Redis Quota Filter property name. */ + public static final String CONFIGURATION_PROPERTY_NAME = "redis-quota-filter"; + + /** + * Redis Script name. + */ + public static final String REDIS_SCRIPT_NAME = "redisRequestQuotaLimiterScript"; + + /** + * Remaining Quota Rate header name. + */ + public static final String REMAINING_HEADER = "X-Quota-Remaining"; + + /** + * Quota Limit (count) Header name. + */ + public static final String QUOTA_LIMIT_HEADER = "X-Quota-Limit"; + + /** + * Quota Period Header name. + */ + public static final String QUOTA_PERIOD_HEADER = "X-Quota-Period"; + + private Log log = LogFactory.getLog(getClass()); + + private ReactiveStringRedisTemplate redisTemplate; + + private AtomicBoolean initialized = new AtomicBoolean(false); + + private RedisScript> script; + + private Config defaultConfig; + + // configuration properties + /** + * Whether or not to include headers containing rate limiter information, defaults to + * true. + */ + private boolean includeHeaders = true; + + /** + * The name of the header that returns number of remaining requests during the current + * second. + */ + private String remainingHeader = REMAINING_HEADER; + + /** The name of the header that returns the quota limit configuration. */ + private String limitHeader = QUOTA_LIMIT_HEADER; + + /** The name of the header that returns the quota period configuration. */ + private String periodHeader = QUOTA_PERIOD_HEADER; + + public RedisQuotaFilter(ReactiveStringRedisTemplate redisTemplate, + RedisScript> script, ConfigurationService configurationService) { + super(Config.class, CONFIGURATION_PROPERTY_NAME, configurationService); + this.redisTemplate = redisTemplate; + this.script = script; + this.initialized.compareAndSet(false, true); + } + + /** + * This creates an instance with default static configuration, useful in Java DSL. + * @param limit how many tokens per "Period" can be used. + * @param period where the limit will be checked, after the period the limit starts at + * zero again. + */ + public RedisQuotaFilter(int limit, String period) { + super(Config.class, CONFIGURATION_PROPERTY_NAME, (ConfigurationService) null); + this.defaultConfig = new Config().setLimit(limit).setPeriod(period); + } + + static List getKey(String id) { + // use `{}` around keys to use Redis Key hash tags + // this allows for using redis cluster + + // Make a unique key per user. + return Collections + .singletonList(String.format("request_quota_limiter.{%s}.tokens", id)); + } + + public boolean isIncludeHeaders() { + return includeHeaders; + } + + public void setIncludeHeaders(boolean includeHeaders) { + this.includeHeaders = includeHeaders; + } + + public String getRemainingHeader() { + return remainingHeader; + } + + public void setRemainingHeader(String remainingHeader) { + this.remainingHeader = remainingHeader; + } + + String getLimitHeader() { + return limitHeader; + } + + void setLimitHeader(String limitHeader) { + this.limitHeader = limitHeader; + } + + String getPeriodHeader() { + return periodHeader; + } + + void setPeriodHeader(String periodHeader) { + this.periodHeader = periodHeader; + } + + /** + * Used when setting default configuration in constructor. + * @param context the ApplicationContext object to be used by this object + * @throws BeansException if thrown by application context methods + */ + @Override + @SuppressWarnings("unchecked") + public void setApplicationContext(ApplicationContext context) throws BeansException { + if (initialized.compareAndSet(false, true)) { + if (this.redisTemplate == null) { + this.redisTemplate = context.getBean(ReactiveStringRedisTemplate.class); + } + this.script = context.getBean(REDIS_SCRIPT_NAME, RedisScript.class); + if (context.getBeanNamesForType(ConfigurationService.class).length > 0) { + setConfigurationService(context.getBean(ConfigurationService.class)); + } + } + } + + /* for testing */ Config getDefaultConfig() { + return defaultConfig; + } + + /** + * This uses a basic token bucket algorithm and relies on the fact that Redis scripts + * execute atomically. No other operations can run between fetching the count and + * writing the new count. + */ + @Override + @SuppressWarnings("unchecked") + public Mono isAllowed(String routeId, String id) { + if (!this.initialized.get()) { + throw new IllegalStateException("RedisRateLimiter is not initialized"); + } + + Config routeConfig = loadConfiguration(routeId); + + // How many requests do you allow + int limit = routeConfig.getLimit(); + // How many requests can be done by a period + QuotaPeriods period = routeConfig.getPeriod(); + // load redis keys + List keys = getKey(id); + try { + // build arugments to pass to the LUA script, time will passed as unixtime in + // seconds + Long ttl = -1L; // ABS + if (period.getTimeUnit().isPresent()) { + ttl = period.getTimeUnit().get().toSeconds(1); + } + List scriptArgs = Arrays.asList(String.valueOf(limit), + String.valueOf(ttl)); + + Flux> redTempExec = this.redisTemplate.execute(this.script, keys, + scriptArgs); + return redTempExec + .onErrorResume(throwable -> Flux.just(Collections.singletonList(-1L))) + .reduce(new ArrayList(), (longs, l) -> { + longs.addAll(l); + return longs; + }).map(results -> { + Long tokensRemaining = results.get(0); + boolean allowed = tokensRemaining >= 0L; + + QuotaFilter.Response response = new QuotaFilter.Response(allowed, + getHeaders(routeConfig, tokensRemaining)); + + if (log.isDebugEnabled()) { + log.debug("response: " + response); + } + return response; + }); + + } + catch (Exception e) { + /* + * We don't want a hard dependency on Redis to allow quota traffic. + */ + log.error("Error determining if user allowed from redis", e); + } + + return Mono.just(new QuotaFilter.Response(true, getHeaders(routeConfig, -1L))); + } + + /* for testing */ + Config loadConfiguration(String routeId) { + Config routeConfig = getConfig().getOrDefault(routeId, defaultConfig); + + if (routeConfig == null) { + routeConfig = getConfig().get(RouteDefinitionRouteLocator.DEFAULT_FILTERS); + } + + if (routeConfig == null) { + throw new IllegalArgumentException( + "No Configuration found for route " + routeId + " or defaultFilters"); + } + return routeConfig; + } + + @NotNull + public Map getHeaders(Config config, Long tokensLeft) { + Map headers = new HashMap<>(); + if (isIncludeHeaders()) { + headers.put(this.remainingHeader, tokensLeft.toString()); + headers.put(this.limitHeader, String.valueOf(config.getLimit())); + headers.put(this.periodHeader, String.valueOf(config.getPeriod())); + } + return headers; + } + + @Validated + public static class Config { + + @Min(1) + private int limit; + + /* SECOND, MINUTE, DAY, YEAR, ABS */ + private QuotaPeriods period = QuotaPeriods.SECONDS; + + public int getLimit() { + return limit; + } + + public Config setLimit(int limit) { + this.limit = limit; + return this; + } + + public QuotaPeriods getPeriod() { + return period; + } + + public Config setPeriod(String period) { + QuotaPeriods quotaPeriods = QuotaPeriods.fromStringWithDefault(period); + // Assert thats not null + Assert.notNull(quotaPeriods, + "The period is wrong, it has to be [ " + + QuotaPeriods.SECONDS.timeUnitName + ", " + + QuotaPeriods.MINUTES.timeUnitName + ", " + + QuotaPeriods.HOURS.timeUnitName + ", " + + QuotaPeriods.DAYS.timeUnitName + " ]"); + this.period = quotaPeriods; + return this; + } + + @Override + public String toString() { + return "Config{" + "limit=" + limit + ", period=" + period + '}'; + } + + } + + /** + * QuotaFilter time periods. + */ + @SuppressWarnings("unchecked") + public enum QuotaPeriods { + + /** + * Available Timeunits for creating time bases quotas. + */ + SECONDS(TimeUnit.SECONDS), MINUTES(TimeUnit.MINUTES), HOURS(TimeUnit.HOURS), DAYS( + TimeUnit.DAYS), + /** + * ABS have no timeunit, we have vo handle null here. + */ + ABS(null); + + private TimeUnit timeUnit; + + private String timeUnitName; + + QuotaPeriods(TimeUnit timeUnit) { + this.timeUnit = timeUnit; + if (this.timeUnit == null) { + this.timeUnitName = "ABS"; + } + else { + this.timeUnitName = timeUnit.name(); + } + } + + Optional getTimeUnit() { + return Optional.ofNullable(this.timeUnit); + } + + public String getTimeUnitName() { + return this.timeUnitName; + } + + @Override + public String toString() { + return this.timeUnitName; + } + + /* + * look for description in enums, return seconds as default. + */ + public static QuotaPeriods fromStringWithDefault(String value) { + for (QuotaPeriods quotaPeriod : QuotaPeriods.values()) { + if (quotaPeriod.timeUnitName.equalsIgnoreCase(value)) { + return quotaPeriod; + } + } + return null; + } + + } + +} diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/route/builder/GatewayFilterSpec.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/route/builder/GatewayFilterSpec.java index df8aca9979..c30f51dec0 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/route/builder/GatewayFilterSpec.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/route/builder/GatewayFilterSpec.java @@ -52,6 +52,7 @@ import org.springframework.cloud.gateway.filter.factory.RemoveResponseHeaderGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.RequestHeaderSizeGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.RequestHeaderToRequestUriGatewayFilterFactory; +import org.springframework.cloud.gateway.filter.factory.RequestQuotaGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.RequestRateLimiterGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.RequestSizeGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.RetryGatewayFilterFactory; @@ -70,11 +71,11 @@ import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction; -import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; +import org.springframework.cloud.gateway.filter.redis.quota.QuotaFilter; +import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter; import org.springframework.cloud.gateway.route.Route; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; -import org.springframework.util.StringUtils; import org.springframework.util.unit.DataSize; import org.springframework.web.server.ServerWebExchange; @@ -500,6 +501,27 @@ public RequestRateLimiterSpec requestRateLimiter() { getBean(RequestRateLimiterGatewayFilterFactory.class)); } + /** + * A filter that will set up a request quota for a route. + * @param configConsumer a {@link Consumer} that will return configuration for the + * quota filter + * @return a {@link GatewayFilterSpec} that can be used to apply additional filters + */ + public GatewayFilterSpec requestQuotaFilter( + Consumer configConsumer) { + return filter( + getBean(RequestQuotaGatewayFilterFactory.class).apply(configConsumer)); + } + + /** + * A filter that will set up a request rate limiter for a route. + * @return a {@link GatewayFilterSpec} that can be used to apply additional filters + */ + public RequestQuotaFilterSpec requestQuotaFilter() { + return new RequestQuotaFilterSpec( + getBean(RequestQuotaGatewayFilterFactory.class)); + } + /** * A filter which rewrites the request path before it is routed by the Gateway * @param regex a Java regular expression to match the path against @@ -818,4 +840,34 @@ public GatewayFilterSpec and() { } + public class RequestQuotaFilterSpec { + + private final RequestQuotaGatewayFilterFactory filter; + + public RequestQuotaFilterSpec(RequestQuotaGatewayFilterFactory filter) { + this.filter = filter; + } + + public > RequestQuotaFilterSpec quotaFilter( + Class quotaFilterType, Consumer configConsumer) { + R quotaFilter = getBean(quotaFilterType); + C config = quotaFilter.newConfig(); + configConsumer.accept(config); + quotaFilter.getConfig().put(routeBuilder.getId(), config); + return this; + } + + public GatewayFilterSpec configure( + Consumer configConsumer) { + filter(this.filter.apply(configConsumer)); + return GatewayFilterSpec.this; + } + + public GatewayFilterSpec and() { + return configure(config -> { + }); + } + + } + } diff --git a/spring-cloud-gateway-core/src/main/resources/META-INF/scripts/request_quota_limiter.lua b/spring-cloud-gateway-core/src/main/resources/META-INF/scripts/request_quota_limiter.lua new file mode 100644 index 0000000000..d5cd00915a --- /dev/null +++ b/spring-cloud-gateway-core/src/main/resources/META-INF/scripts/request_quota_limiter.lua @@ -0,0 +1,25 @@ +local tokens_key = KEYS[1] + +local limit = tonumber(ARGV[1]) +local ttl = tonumber(ARGV[2]) + +local start_count = 0 +-- check if token exist else start quota at zero +local last_tokens = tonumber(redis.call("get", tokens_key)) +if last_tokens == nil then + redis.log(redis.LOG_WARNING, "last tokens ") + -- set new token with ttl and value + if ttl > 0 then + redis.call("setex", tokens_key, ttl, start_count) + else + redis.call("set", tokens_key, start_count) + end + last_tokens = start_count +end + +redis.call("incr", tokens_key) + +-- set last_tokens + 1 because of the increment +local req_left = limit - (last_tokens + 1) + +return { req_left } \ No newline at end of file diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactoryTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactoryTests.java index e2fe13aa4d..b03a6d2ce6 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactoryTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactoryTests.java @@ -31,9 +31,9 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; -import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; -import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; -import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter.Response; +import org.springframework.cloud.gateway.filter.redis.KeyResolver; +import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter; +import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter.Response; import org.springframework.cloud.gateway.route.Route; import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; import org.springframework.cloud.gateway.test.BaseWebClientTests; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/PrincipalNameKeyResolverIntegrationTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/PrincipalNameKeyResolverIntegrationTests.java new file mode 100644 index 0000000000..572e2a5bfa --- /dev/null +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/PrincipalNameKeyResolverIntegrationTests.java @@ -0,0 +1,163 @@ +/* + * Copyright 2013-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.cloud.gateway.filter.redis.quota; + +import java.security.Principal; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import reactor.core.publisher.Mono; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.util.SocketUtils; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; +import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = DEFINED_PORT) +@ActiveProfiles("principalname") +public class PrincipalNameKeyResolverIntegrationTests { + + @LocalServerPort + protected int port = 0; + + protected WebTestClient client; + + protected String baseUri; + + @BeforeClass + public static void beforeClass() { + System.setProperty("server.port", + String.valueOf(SocketUtils.findAvailableTcpPort())); + } + + @AfterClass + public static void afterClass() { + System.clearProperty("server.port"); + } + + @Before + public void setup() { + this.baseUri = String.format("%s:%s", "http://localhost", port); + this.client = WebTestClient.bindToServer().baseUrl(baseUri).build(); + } + + @Test + public void keyResolverWorks() { + this.client.mutate().filter(basicAuthentication("user", "password")).build().get() + .uri("/myapi/1").exchange().expectStatus().isOk().expectBody() + .json("{\"user\":\"1\"}"); + } + + @RestController + @RequestMapping("/downstream") + @EnableAutoConfiguration + @SpringBootConfiguration + protected static class TestConfig { + + @Value("${server.port}") + private int port; + + @RequestMapping("/myapi/{id}") + public Map myapi(@PathVariable String id, Principal principal) { + return Collections.singletonMap(principal.getName(), id); + } + + @Bean + public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { + return builder.routes().route(r -> r.path("/myapi/**") + .filters(f -> f + .requestQuotaFilter(c -> c.setQuotaFilter(myQuotaFilter())) + .prefixPath("/downstream")) + .uri("http://localhost:" + port)).build(); + } + + @Bean + @Primary + MyQuotaFilter myQuotaFilter() { + return new MyQuotaFilter(); + } + + @Bean + SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) { + return http.httpBasic().and().authorizeExchange().pathMatchers("/myapi/**") + .authenticated().anyExchange().permitAll().and().build(); + } + + @Bean + public MapReactiveUserDetailsService reactiveUserDetailsService() { + UserDetails user = User.withUsername("user").password("{noop}password") + .roles("USER").build(); + return new MapReactiveUserDetailsService(user); + } + + class MyQuotaFilter implements QuotaFilter { + + private HashMap map = new HashMap<>(); + + @Override + public Mono isAllowed(String routeId, String id) { + return Mono.just(new Response(true, + Collections.singletonMap("X-Value", "5000000"))); + } + + @Override + public Class getConfigClass() { + return Object.class; + } + + @Override + public Map getConfig() { + return map; + } + + @Override + public Object newConfig() { + return null; + } + + } + + } + +} diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterConfigTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterConfigTests.java new file mode 100644 index 0000000000..1cadfc75e5 --- /dev/null +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterConfigTests.java @@ -0,0 +1,141 @@ +/* + * Copyright 2013-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.cloud.gateway.filter.redis.quota; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.gateway.route.Route; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Tobias Schug + */ +@RunWith(SpringRunner.class) +@SpringBootTest +@DirtiesContext +@ActiveProfiles("redis-quota-filter-config") +public class RedisQuotaFilterConfigTests { + + @Autowired + private RedisQuotaFilter quotaFilter; + + @Autowired + private RouteLocator routeLocator; + + @Before + public void init() { + routeLocator.getRoutes().collectList().block(); // prime routes since getRoutes() + // no longer blocks + } + + /* test with values from application-redis-quota-filter-config.yml could be loaded */ + @Test + public void redisQuotaFilterConfiguredFromEnvironment() { + assertFilter("redis_quota_filter_config_test", 10, "DAYS", false); + } + + @Test + public void redisQuotaFilterConfiguredFromJavaAPI() { + assertFilter("custom_redis_quota_filter", 1, "MINUTES", false); + } + + @Test + public void redisQuotaFilterConfiguredFromJavaAPIDirectBean() { + assertFilter("alt_custom_redis_redis_quota_filter", 2, "SECONDS", true); + } + + @Test + public void redisQuotaFilterAbsPeriod() { + assertFilter("abs_custom_redis_redis_quota_filter", 1, "ABS", false); + } + + @Test(expected = IllegalArgumentException.class) + public void redisQuotaFilterConfigWrongPeriod() { + quotaFilter.getDefaultConfig().setPeriod("WRONG_TYPE"); + } + + private void assertFilter(String key, int limit, String period, + boolean useDefaultConfig) { + RedisQuotaFilter.Config config; + + if (useDefaultConfig) { + config = quotaFilter.getDefaultConfig(); + } + else { + assertThat(quotaFilter.getConfig()).containsKey(key); + config = quotaFilter.getConfig().get(key); + } + assertThat(config).isNotNull(); + assertThat(config.getLimit()).isEqualTo(limit); + assertThat(config.getPeriod().getTimeUnitName()).isEqualTo(period); + + Route route = routeLocator.getRoutes().filter(r -> r.getId().equals(key)).next() + .block(); + assertThat(route).isNotNull(); + assertThat(route.getFilters()).hasSize(1); + } + + @EnableAutoConfiguration + @SpringBootConfiguration + public static class TestConfig { + + @Bean + public RouteLocator testRouteLocator(RouteLocatorBuilder builder) { + return builder.routes().route("custom_redis_quota_filter", r -> r + .path("/custom") + .filters(f -> f.requestQuotaFilter().quotaFilter( + RedisQuotaFilter.class, + qf -> qf.setLimit(1).setPeriod( + RedisQuotaFilter.QuotaPeriods.MINUTES.toString())) + .and()) + .uri("http://localhost")) + .route("alt_custom_redis_redis_quota_filter", + r -> r.path("/custom") + .filters(f -> f.requestQuotaFilter( + c -> c.setQuotaFilter(customQuotaFilter()))) + .uri("http://localhost")) + .route("abs_custom_redis_redis_quota_filter", r -> r.path("/custom") + .filters(f -> f.requestQuotaFilter().quotaFilter( + RedisQuotaFilter.class, + qf -> qf.setLimit(1).setPeriod( + RedisQuotaFilter.QuotaPeriods.ABS.toString())) + .and()) + .uri("http://localhost")) + .build(); + } + + @Bean + public RedisQuotaFilter customQuotaFilter() { + return new RedisQuotaFilter(2, "SECONDS"); + } + + } + +} diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterDefaultFilterConfigTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterDefaultFilterConfigTests.java new file mode 100644 index 0000000000..2ec482460b --- /dev/null +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterDefaultFilterConfigTests.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013-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.cloud.gateway.filter.redis.quota; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.gateway.route.Route; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Spencer Gibb + * @author Tobias Schug + */ +@RunWith(SpringRunner.class) +@SpringBootTest +@DirtiesContext +@ActiveProfiles("redis-quota-filter-default-config") +public class RedisQuotaFilterDefaultFilterConfigTests { + + @Autowired + private RedisQuotaFilter quotaFilter; + + @Autowired + private RouteLocator routeLocator; + + @Before + public void init() { + routeLocator.getRoutes().collectList().block(); // prime routes since getRoutes() + // no longer blocks + } + + @Test + public void redisRateConfiguredFromEnvironmentDefaultFilters() { + String routeId = "redis_quota_filter_config_default_test"; + RedisQuotaFilter.Config config = quotaFilter.loadConfiguration(routeId); + assertConfigAndRoute(routeId, 10, RedisQuotaFilter.QuotaPeriods.DAYS, config); + } + + private void assertConfigAndRoute(String key, int limit, + RedisQuotaFilter.QuotaPeriods period, RedisQuotaFilter.Config config) { + assertThat(config).isNotNull(); + assertThat(config.getLimit()).isEqualTo(limit); + assertThat(config.getPeriod()).isEqualTo(period); + + Route route = routeLocator.getRoutes().filter(r -> r.getId().equals(key)).next() + .block(); + assertThat(route).isNotNull(); + assertThat(route.getFilters()).isNotEmpty(); + } + + @EnableAutoConfiguration + @SpringBootConfiguration + public static class TestConfig { + + } + +} diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterTests.java new file mode 100644 index 0000000000..1796690cd7 --- /dev/null +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterTests.java @@ -0,0 +1,161 @@ +/* + * Copyright 2017-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.cloud.gateway.filter.redis.quota; + +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.gateway.test.BaseWebClientTests; +import org.springframework.cloud.gateway.test.support.redis.RedisRule; +import org.springframework.context.annotation.Import; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assume.assumeThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +import static org.springframework.cloud.gateway.filter.redis.quota.QuotaFilter.Response; + +/** + * @author Tobias Schug + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = RANDOM_PORT) +@DirtiesContext +public class RedisQuotaFilterTests extends BaseWebClientTests { + + @Rule + public final RedisRule redis = RedisRule.bindToDefaultPort(); + + @Autowired + private RedisQuotaFilter quotaFilter; + + @Test + public void redisQuotaFilterWorks() throws Exception { + assumeThat("Ignore on Circle", System.getenv("CIRCLECI"), is(nullValue())); + + String id = UUID.randomUUID().toString(); + + String routeId = "myroute"; + String period = "days"; + int limit = 2; + + quotaFilter.getConfig().put(routeId, + new RedisQuotaFilter.Config().setLimit(limit).setPeriod(period)); + for (int i = 0; i < limit; i++) { + Response response = quotaFilter.isAllowed(routeId, id).block(); + assertThat(response.isAllowed()).as("Quota filter not exceeded - %s", i) + .isTrue(); + + assertThat(response.getHeaders()) + .containsKey(RedisQuotaFilter.REMAINING_HEADER); + + assertThat(response.getHeaders().get(RedisQuotaFilter.REMAINING_HEADER)) + .isEqualTo(String.valueOf(limit - (i + 1))); + + assertThat(response.getHeaders()) + .containsKey(RedisQuotaFilter.QUOTA_PERIOD_HEADER); + assertThat(response.getHeaders().get(RedisQuotaFilter.QUOTA_PERIOD_HEADER)) + .isEqualTo(RedisQuotaFilter.QuotaPeriods.DAYS.getTimeUnitName()); + + assertThat(response.getHeaders()) + .containsKey(RedisQuotaFilter.QUOTA_LIMIT_HEADER); + assertThat(response.getHeaders().get(RedisQuotaFilter.QUOTA_LIMIT_HEADER)) + .isEqualTo(String.valueOf(limit)); + } + + Response response = quotaFilter.isAllowed(routeId, id).block(); + assertThat(response.isAllowed()).as("Quota filter has exceeded").isFalse(); + } + + @Test + public void redisQuotaFilterLockQuotaAfterTimedOut() throws Exception { + assumeThat("Ignore on Circle", System.getenv("CIRCLECI"), is(nullValue())); + + String id = UUID.randomUUID().toString(); + + String routeId = "myroute"; + String period = "seconds"; + int limit = 1; + + quotaFilter.getConfig().put(routeId, + new RedisQuotaFilter.Config().setLimit(limit).setPeriod(period)); + + Response response = quotaFilter.isAllowed(routeId, id).block(); + assertThat(response.isAllowed()).as("Quota filter not exceeded").isTrue(); + + assertThat(response.getHeaders().get(RedisQuotaFilter.REMAINING_HEADER)) + .isEqualTo(String.valueOf(0)); + assertThat(response.getHeaders().get(RedisQuotaFilter.QUOTA_PERIOD_HEADER)) + .isEqualTo(RedisQuotaFilter.QuotaPeriods.SECONDS.getTimeUnitName()); + assertThat(response.getHeaders().get(RedisQuotaFilter.QUOTA_LIMIT_HEADER)) + .isEqualTo(String.valueOf(limit)); + + // check that the filter block the request + response = quotaFilter.isAllowed(routeId, id).block(); + assertThat(response.isAllowed()).as("Quota filter has exceeded").isFalse(); + // wait 2sec till the quota was dropped and started from 0 again + Thread.sleep(TimeUnit.SECONDS.toMillis(2L)); + response = quotaFilter.isAllowed(routeId, id).block(); + assertThat(response.isAllowed()).as("Quota filter has exceeded").isTrue(); + assertThat(response.getHeaders().get(RedisQuotaFilter.REMAINING_HEADER)) + .isEqualTo(String.valueOf(0)); + } + + @Test + public void keysUseRedisKeyHashTags() { + assertThat(RedisQuotaFilter.getKey("1")) + .containsExactly("request_quota_limiter.{1}.tokens"); + } + + @Test + public void redisRateQuotaFilterDoesNotSendHeadersIfDeactivated() throws Exception { + assumeThat("Ignore on Circle", System.getenv("CIRCLECI"), is(nullValue())); + + String id = UUID.randomUUID().toString(); + String routeId = "myroute"; + + quotaFilter.setIncludeHeaders(false); + + Response response = quotaFilter.isAllowed(routeId, id).block(); + assertThat(response.isAllowed()).isTrue(); + assertThat(response.getHeaders()) + .doesNotContainKey(RedisQuotaFilter.QUOTA_PERIOD_HEADER); + assertThat(response.getHeaders()) + .doesNotContainKey(RedisQuotaFilter.QUOTA_LIMIT_HEADER); + assertThat(response.getHeaders()) + .doesNotContainKey(RedisQuotaFilter.REMAINING_HEADER); + } + + @EnableAutoConfiguration + @SpringBootConfiguration + @Import(DefaultTestConfig.class) + public static class TestConfig { + + } + +} diff --git a/spring-cloud-gateway-core/src/test/resources/application-redis-quota-filter-config.yml b/spring-cloud-gateway-core/src/test/resources/application-redis-quota-filter-config.yml new file mode 100644 index 0000000000..ddc003be57 --- /dev/null +++ b/spring-cloud-gateway-core/src/test/resources/application-redis-quota-filter-config.yml @@ -0,0 +1,17 @@ +spring: + cloud: + gateway: + default-filters: + routes: + # ===================================== + - id: redis_quota_filter_config_test + key-resolvers: ipPortLimit + uri: ${test.uri} + predicates: + - Path=/ + filters: + - name: RequestQuota + args: + redis-quota-filter: + limit: 10 + period: DAYS \ No newline at end of file diff --git a/spring-cloud-gateway-core/src/test/resources/application-redis-quota-filter-default-config.yml b/spring-cloud-gateway-core/src/test/resources/application-redis-quota-filter-default-config.yml new file mode 100644 index 0000000000..8841cfb5c4 --- /dev/null +++ b/spring-cloud-gateway-core/src/test/resources/application-redis-quota-filter-default-config.yml @@ -0,0 +1,14 @@ +spring: + cloud: + gateway: + default-filters: + - name: RequestQuota + args: + redis-quota-filter: + limit: 10 + period: DAYS + routes: + - id: redis_quota_filter_config_default_test + uri: ${test.uri} + predicates: + - Path=/default From e48c52f2af42200b82e3bc9840198a2ffcc02fc4 Mon Sep 17 00:00:00 2001 From: HappyTobi Date: Tue, 26 Nov 2019 09:41:09 +0100 Subject: [PATCH 2/7] Move rate limiter to redis package --- .../factory/RequestRateLimiterGatewayFilterFactory.java | 4 ++-- .../filter/{ => redis}/ratelimit/AbstractRateLimiter.java | 2 +- .../gateway/filter/{ => redis}/ratelimit/RateLimiter.java | 2 +- .../filter/{ => redis}/ratelimit/RedisRateLimiter.java | 2 +- .../ratelimit/PrincipalNameKeyResolverIntegrationTests.java | 2 +- .../{ => redis}/ratelimit/RedisRateLimiterConfigTests.java | 2 +- .../ratelimit/RedisRateLimiterDefaultFilterConfigTests.java | 2 +- .../filter/{ => redis}/ratelimit/RedisRateLimiterTests.java | 4 ++-- .../springframework/cloud/gateway/test/AdhocTestSuite.java | 6 +++--- 9 files changed, 13 insertions(+), 13 deletions(-) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{ => redis}/ratelimit/AbstractRateLimiter.java (98%) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{ => redis}/ratelimit/RateLimiter.java (96%) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{ => redis}/ratelimit/RedisRateLimiter.java (99%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{ => redis}/ratelimit/PrincipalNameKeyResolverIntegrationTests.java (98%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{ => redis}/ratelimit/RedisRateLimiterConfigTests.java (98%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{ => redis}/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java (97%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{ => redis}/ratelimit/RedisRateLimiterTests.java (96%) diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactory.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactory.java index 6042b9d683..88ff79c25b 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactory.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactory.java @@ -20,8 +20,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.gateway.filter.GatewayFilter; -import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; -import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; +import org.springframework.cloud.gateway.filter.redis.KeyResolver; +import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter; import org.springframework.cloud.gateway.route.Route; import org.springframework.cloud.gateway.support.HasRouteId; import org.springframework.cloud.gateway.support.HttpStatusHolder; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/AbstractRateLimiter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/AbstractRateLimiter.java similarity index 98% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/AbstractRateLimiter.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/AbstractRateLimiter.java index ca48a979f2..454bcf726b 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/AbstractRateLimiter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/AbstractRateLimiter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.ratelimit; +package org.springframework.cloud.gateway.filter.redis.ratelimit; import java.util.Map; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RateLimiter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RateLimiter.java similarity index 96% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RateLimiter.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RateLimiter.java index a15c1e74d7..ea2697e257 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RateLimiter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RateLimiter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.ratelimit; +package org.springframework.cloud.gateway.filter.redis.ratelimit; import java.util.Collections; import java.util.Map; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiter.java similarity index 99% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiter.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiter.java index 522f70edc6..955720d819 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.ratelimit; +package org.springframework.cloud.gateway.filter.redis.ratelimit; import java.time.Instant; import java.util.ArrayList; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/PrincipalNameKeyResolverIntegrationTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/PrincipalNameKeyResolverIntegrationTests.java similarity index 98% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/PrincipalNameKeyResolverIntegrationTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/PrincipalNameKeyResolverIntegrationTests.java index 4db24df700..9991cea33c 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/PrincipalNameKeyResolverIntegrationTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/PrincipalNameKeyResolverIntegrationTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.ratelimit; +package org.springframework.cloud.gateway.filter.redis.ratelimit; import java.security.Principal; import java.util.Collections; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterConfigTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterConfigTests.java similarity index 98% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterConfigTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterConfigTests.java index a76780c539..8951f29d53 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterConfigTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterConfigTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.ratelimit; +package org.springframework.cloud.gateway.filter.redis.ratelimit; import org.junit.Before; import org.junit.Test; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java similarity index 97% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java index e1e90a7d0b..3d663b43b8 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.ratelimit; +package org.springframework.cloud.gateway.filter.redis.ratelimit; import org.junit.Before; import org.junit.Test; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterTests.java similarity index 96% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterTests.java index 425e9a2cba..46add34c58 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.ratelimit; +package org.springframework.cloud.gateway.filter.redis.ratelimit; import java.util.UUID; @@ -26,7 +26,7 @@ import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter.Response; +import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter.Response; import org.springframework.cloud.gateway.test.BaseWebClientTests; import org.springframework.cloud.gateway.test.support.redis.RedisRule; import org.springframework.context.annotation.Import; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/test/AdhocTestSuite.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/test/AdhocTestSuite.java index 69df004448..0d3daa6088 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/test/AdhocTestSuite.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/test/AdhocTestSuite.java @@ -93,9 +93,9 @@ org.springframework.cloud.gateway.filter.headers.NonStandardHeadersInResponseTests.class, org.springframework.cloud.gateway.filter.headers.RemoveHopByHopHeadersFilterTests.class, org.springframework.cloud.gateway.filter.WebsocketRoutingFilterTests.class, - org.springframework.cloud.gateway.filter.ratelimit.PrincipalNameKeyResolverIntegrationTests.class, - org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiterConfigTests.class, - org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiterTests.class, + org.springframework.cloud.gateway.filter.redis.ratelimit.PrincipalNameKeyResolverIntegrationTests.class, + org.springframework.cloud.gateway.filter.redis.ratelimit.RedisRateLimiterConfigTests.class, + org.springframework.cloud.gateway.filter.redis.ratelimit.RedisRateLimiterTests.class, org.springframework.cloud.gateway.filter.LoadBalancerClientFilterTests.class, org.springframework.cloud.gateway.filter.NettyRoutingFilterIntegrationTests.class, GatewayMetricsFilterTests.class, From a24a81c322e994215f6882194a13a1c0d7114de8 Mon Sep 17 00:00:00 2001 From: HappyTobi Date: Tue, 26 Nov 2019 09:41:31 +0100 Subject: [PATCH 3/7] New Documentation how to use the quota filter --- .../main/asciidoc/spring-cloud-gateway.adoc | 673 ++++++++++++------ 1 file changed, 468 insertions(+), 205 deletions(-) diff --git a/docs/src/main/asciidoc/spring-cloud-gateway.adoc b/docs/src/main/asciidoc/spring-cloud-gateway.adoc index ff0a358177..bfbe169601 100644 --- a/docs/src/main/asciidoc/spring-cloud-gateway.adoc +++ b/docs/src/main/asciidoc/spring-cloud-gateway.adoc @@ -1,4 +1,5 @@ = Spring Cloud Gateway + include::_attributes.adoc[] *{spring-cloud-version}* @@ -9,43 +10,57 @@ include::intro.adoc[] == How to Include Spring Cloud Gateway To include Spring Cloud Gateway in your project use the starter with group `org.springframework.cloud` -and artifact id `spring-cloud-starter-gateway`. See the https://projects.spring.io/spring-cloud/[Spring Cloud Project page] +and artifact id `spring-cloud-starter-gateway`. +See the https://projects.spring.io/spring-cloud/[Spring Cloud Project page] for details on setting up your build system with the current Spring Cloud Release Train. If you include the starter, but, for some reason, you do not want the gateway to be enabled, set `spring.cloud.gateway.enabled=false`. IMPORTANT: Spring Cloud Gateway is built upon https://spring.io/projects/spring-boot#learn[Spring Boot 2.x], -https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html[Spring WebFlux], -and https://projectreactor.io/docs[Project Reactor]. As a consequence -many of the familiar synchronous libraries (Spring Data and Spring Security, for example) and patterns you may -not apply when using Spring Cloud Gateway. If you are unfamiliar with these projects we suggest you -begin by reading their documentation to familiarize yourself with some of the new concepts before -working with Spring Cloud Gateway. +https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html[Spring WebFlux], and https://projectreactor.io/docs[Project Reactor]. +As a consequence many of the familiar synchronous libraries (Spring Data and Spring Security, for example) and patterns you may not apply when using Spring Cloud Gateway. +If you are unfamiliar with these projects we suggest you begin by reading their documentation to familiarize yourself with some of the new concepts before working with Spring Cloud Gateway. -IMPORTANT: Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spring Webflux. It does not work in a traditional Servlet Container or built as a WAR. +IMPORTANT: Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spring Webflux. +It does not work in a traditional Servlet Container or built as a WAR. == Glossary -* *Route*: Route the basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates and a collection of filters. A route is matched if aggregate predicate is true. -* *Predicate*: This is a https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html[Java 8 Function Predicate]. The input type is a https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/server/ServerWebExchange.html[Spring Framework `ServerWebExchange`]. This allows developers to match on anything from the HTTP request, such as headers or parameters. -* *Filter*: These are instances https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/server/GatewayFilter.html[Spring Framework `GatewayFilter`] constructed in with a specific factory. Here, requests and responses can be modified before or after sending the downstream request. +* *Route*: Route the basic building block of the gateway. +It is defined by an ID, a destination URI, a collection of predicates and a collection of filters. +A route is matched if aggregate predicate is true. +* *Predicate*: This is a https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html[Java 8 Function Predicate]. +The input type is a https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/server/ServerWebExchange.html[Spring Framework `ServerWebExchange`]. +This allows developers to match on anything from the HTTP request, such as headers or parameters. +* *Filter*: These are instances https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/server/GatewayFilter.html[Spring Framework `GatewayFilter`] constructed in with a specific factory. +Here, requests and responses can be modified before or after sending the downstream request. [[gateway-how-it-works]] == How It Works image::{imagesurl}/spring_cloud_gateway_diagram.png[Spring Cloud Gateway Diagram] -Clients make requests to Spring Cloud Gateway. If the Gateway Handler Mapping determines that a request matches a Route, it is sent to the Gateway Web Handler. This handler runs sends the request through a filter chain that is specific to the request. The reason the filters are divided by the dotted line, is that filters may execute logic before the proxy request is sent or after. All "pre" filter logic is executed, then the proxy request is made. After the proxy request is made, the "post" filter logic is executed. +Clients make requests to Spring Cloud Gateway. +If the Gateway Handler Mapping determines that a request matches a Route, it is sent to the Gateway Web Handler. +This handler runs sends the request through a filter chain that is specific to the request. +The reason the filters are divided by the dotted line, is that filters may execute logic before the proxy request is sent or after. +All "pre" filter logic is executed, then the proxy request is made. +After the proxy request is made, the "post" filter logic is executed. NOTE: URIs defined in routes without a port will get a default port set to 80 and 443 for HTTP and HTTPS URIs respectively. [[gateway-request-predicates-factories]] == Route Predicate Factories -Spring Cloud Gateway matches routes as part of the Spring WebFlux `HandlerMapping` infrastructure. Spring Cloud Gateway includes many built-in Route Predicate Factories. All of these predicates match on different attributes of the HTTP request. Multiple Route Predicate Factories can be combined and are combined via logical `and`. +Spring Cloud Gateway matches routes as part of the Spring WebFlux `HandlerMapping` infrastructure. +Spring Cloud Gateway includes many built-in Route Predicate Factories. +All of these predicates match on different attributes of the HTTP request. +Multiple Route Predicate Factories can be combined and are combined via logical `and`. === After Route Predicate Factory -The After Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen after the current datetime. + +The After Route Predicate Factory takes one parameter, a datetime. +This predicate matches requests that happen after the current datetime. .application.yml [source,yaml] @@ -63,7 +78,9 @@ spring: This route matches any request after Jan 20, 2017 17:42 Mountain Time (Denver). === Before Route Predicate Factory -The Before Route Predicate Factory takes one parameter, a datetime. This predicate matches requests that happen before the current datetime. + +The Before Route Predicate Factory takes one parameter, a datetime. +This predicate matches requests that happen before the current datetime. .application.yml [source,yaml] @@ -81,6 +98,7 @@ spring: This route matches any request before Jan 20, 2017 17:42 Mountain Time (Denver). === Between Route Predicate Factory + The Between Route Predicate Factory takes two parameters, datetime1 and datetime2. This predicate matches requests that happen after datetime1 and before datetime2. The datetime2 parameter must be after datetime1. .application.yml @@ -96,10 +114,13 @@ spring: - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver] ---- -This route matches any request after Jan 20, 2017 17:42 Mountain Time (Denver) and before Jan 21, 2017 17:42 Mountain Time (Denver). This could be useful for maintenance windows. +This route matches any request after Jan 20, 2017 17:42 Mountain Time (Denver) and before Jan 21, 2017 17:42 Mountain Time (Denver). +This could be useful for maintenance windows. === Cookie Route Predicate Factory -The Cookie Route Predicate Factory takes two parameters, the cookie name and a regular expression. This predicate matches cookies that have the given name and the value matches the regular expression. + +The Cookie Route Predicate Factory takes two parameters, the cookie name and a regular expression. +This predicate matches cookies that have the given name and the value matches the regular expression. .application.yml [source,yaml] @@ -117,7 +138,9 @@ spring: This route matches the request has a cookie named `chocolate` who's value matches the `ch.p` regular expression. === Header Route Predicate Factory -The Header Route Predicate Factory takes two parameters, the header name and a regular expression. This predicate matches with a header that has the given name and the value matches the regular expression. + +The Header Route Predicate Factory takes two parameters, the header name and a regular expression. +This predicate matches with a header that has the given name and the value matches the regular expression. .application.yml [source,yaml] @@ -135,7 +158,10 @@ spring: This route matches if the request has a header named `X-Request-Id` whose value matches the `\d+` regular expression (has a value of one or more digits). === Host Route Predicate Factory -The Host Route Predicate Factory takes one parameter: a list of host name patterns. The pattern is an Ant style pattern with `.` as the separator. This predicates matches the `Host` header that matches the pattern. + +The Host Route Predicate Factory takes one parameter: a list of host name patterns. +The pattern is an Ant style pattern with `.` as the separator. +This predicates matches the `Host` header that matches the pattern. .application.yml [source,yaml] @@ -154,15 +180,12 @@ URI template variables are supported as well, such as `{sub}.myhost.org`. This route would match if the request has a `Host` header has the value `www.somehost.org` or `beta.somehost.org` or `www.anotherhost.org`. -This predicate extracts the URI template variables (like `sub` defined in the example above) as a map of names and values and places it in the `ServerWebExchange.getAttributes()` with a key defined in `ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`. Those values are then available for use by <> - +This predicate extracts the URI template variables (like `sub` defined in the example above) as a map of names and values and places it in the `ServerWebExchange.getAttributes()` with a key defined in `ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`. +Those values are then available for use by <> === Method Route Predicate Factory -The Method Route Predicate Factory takes one or more parameters: the HTTP methods to match. - .application.yml [source,yaml] ----- spring: cloud: gateway: @@ -176,6 +199,7 @@ spring: This route would match if the request method was a `GET` or a `POST`. === Path Route Predicate Factory + The Path Route Predicate Factory takes two parameters: a list of Spring `PathMatcher` patterns and an optional flag to `matchOptionalTrailingSeparator`. .application.yml @@ -193,7 +217,8 @@ spring: This route would match if the request path was, for example: `/foo/1` or `/foo/bar` or `/bar/baz`. -This predicate extracts the URI template variables (like `segment` defined in the example above) as a map of names and values and places it in the `ServerWebExchange.getAttributes()` with a key defined in `ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`. Those values are then available for use by <> +This predicate extracts the URI template variables (like `segment` defined in the example above) as a map of names and values and places it in the `ServerWebExchange.getAttributes()` with a key defined in `ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE`. +Those values are then available for use by <> A utility method is available to make access to these variables easier. @@ -205,6 +230,7 @@ String segment = uriVariables.get("segment"); ---- === Query Route Predicate Factory + The Query Route Predicate Factory takes two parameters: a required `param` and an optional `regexp`. .application.yml @@ -237,8 +263,8 @@ spring: This route would match if the request contained a `foo` query parameter whose value matched the `ba.` regexp, so `bar` and `baz` would match. - === RemoteAddr Route Predicate Factory + The RemoteAddr Route Predicate Factory takes a list (min size 1) of CIDR-notation (IPv4 or IPv6) strings, e.g. `192.168.0.1/16` (where `192.168.0.1` is an IP address and `16` is a subnet mask). .application.yml @@ -257,7 +283,9 @@ spring: This route would match if the remote address of the request was, for example, `192.168.1.10`. === Weight Route Predicate Factory -The Weight Route Predicate Factory takes two argument group and weight. The weights are calculated per group. + +The Weight Route Predicate Factory takes two argument group and weight. +The weights are calculated per group. .application.yml [source,yaml] @@ -279,6 +307,7 @@ spring: This route would forward ~80% of traffic to https://weighthigh.org and ~20% of traffic to https://weighlow.org ==== Modifying the way remote addresses are resolved + By default the RemoteAddr Route Predicate Factory uses the remote address from the incoming request. This may not match the actual client IP address if Spring Cloud Gateway sits behind a proxy layer. @@ -299,7 +328,6 @@ Given the following header value: [source] X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3 - The `maxTrustedIndex` values below will yield the following remote addresses. [options="header"] @@ -311,11 +339,12 @@ The `maxTrustedIndex` values below will yield the following remote addresses. |3 | 0.0.0.1 |[4, `Integer.MAX_VALUE`] | 0.0.0.1 |=== -[[gateway-route-filters]] +[[gateway-route-filters]] Using Java config: GatewayConfig.java + [source,java] ---- RemoteAddressResolver resolver = XForwardedRemoteAddressResolver @@ -334,11 +363,14 @@ RemoteAddressResolver resolver = XForwardedRemoteAddressResolver == GatewayFilter Factories -Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. Route filters are scoped to a particular route. Spring Cloud Gateway includes many built-in GatewayFilter Factories. +Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. +Route filters are scoped to a particular route. +Spring Cloud Gateway includes many built-in GatewayFilter Factories. NOTE For more detailed examples on how to use any of the following filters, take a look at the https://github.com/spring-cloud/spring-cloud-gateway/tree/master/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/factory[unit tests]. === AddRequestHeader GatewayFilter Factory + The AddRequestHeader GatewayFilter Factory takes a name and value parameter. .application.yml @@ -356,7 +388,8 @@ spring: This will add `X-Request-Foo:Bar` header to the downstream request's headers for all matching requests. -AddRequestHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime. +AddRequestHeader is aware of URI variables used to match a path or host. +URI variables may be used in the value and will be expanded at runtime. .application.yml [source,yaml] @@ -374,6 +407,7 @@ spring: ---- === AddRequestParameter GatewayFilter Factory + The AddRequestParameter GatewayFilter Factory takes a name and value parameter. .application.yml @@ -391,7 +425,8 @@ spring: This will add `foo=bar` to the downstream request's query string for all matching requests. -AddRequestParameter is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime. +AddRequestParameter is aware of URI variables used to match a path or host. +URI variables may be used in the value and will be expanded at runtime. .application.yml [source,yaml] @@ -409,6 +444,7 @@ spring: ---- === AddResponseHeader GatewayFilter Factory + The AddResponseHeader GatewayFilter Factory takes a name and value parameter. .application.yml @@ -426,7 +462,8 @@ spring: This will add `X-Response-Foo:Bar` header to the downstream response's headers for all matching requests. -AddResponseHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime. +AddResponseHeader is aware of URI variables used to match a path or host. +URI variables may be used in the value and will be expanded at runtime. .application.yml [source,yaml] @@ -444,6 +481,7 @@ spring: ---- === DedupeResponseHeader GatewayFilter Factory + The DedupeResponseHeader GatewayFilter Factory takes a `name` parameter and an optional `strategy` parameter. `name` can contain a list of header names, space separated. .application.yml @@ -461,13 +499,14 @@ spring: This will remove duplicate values of `Access-Control-Allow-Credentials` and `Access-Control-Allow-Origin` response headers in cases when both the gateway CORS logic and the downstream add them. -The DedupeResponseHeader filter also accepts an optional `strategy` parameter. The accepted values are `RETAIN_FIRST` (default), `RETAIN_LAST`, and `RETAIN_UNIQUE`. +The DedupeResponseHeader filter also accepts an optional `strategy` parameter. +The accepted values are `RETAIN_FIRST` (default), `RETAIN_LAST`, and `RETAIN_UNIQUE`. [[hystrix]] === Hystrix GatewayFilter Factory -NOTE: https://cloud.spring.io/spring-cloud-netflix/multi/multi__modules_in_maintenance_mode.html[Netflix has put Hystrix in maintenance mode]. It is suggested you use the <> with Resilience4J as support for Hystrix will be removed in a future release. +NOTE: https://cloud.spring.io/spring-cloud-netflix/multi/multi__modules_in_maintenance_mode.html[Netflix has put Hystrix in maintenance mode]. +It is suggested you use the <> with Resilience4J as support for Hystrix will be removed in a future release. https://github.com/Netflix/Hystrix[Hystrix] is a library from Netflix that implements the https://martinfowler.com/bliki/CircuitBreaker.html[circuit breaker pattern]. @@ -492,8 +531,9 @@ spring: This wraps the remaining filters in a `HystrixCommand` with command name `myCommandName`. -The Hystrix filter can also accept an optional `fallbackUri` parameter. Currently, only `forward:` schemed URIs are supported. If the fallback is called, the request will be forwarded to the controller matched by the URI. - +The Hystrix filter can also accept an optional `fallbackUri` parameter. +Currently, only `forward:` schemed URIs are supported. +If the fallback is called, the request will be forwarded to the controller matched by the URI. .application.yml [source,yaml] @@ -513,7 +553,9 @@ spring: fallbackUri: forward:/incaseoffailureusethis - RewritePath=/consumingserviceendpoint, /backingserviceendpoint ---- -This will forward to the `/incaseoffailureusethis` URI when the Hystrix fallback is called. Note that this example also demonstrates (optional) Spring Cloud Netflix Ribbon load-balancing via the `lb` prefix on the destination URI. + +This will forward to the `/incaseoffailureusethis` URI when the Hystrix fallback is called. +Note that this example also demonstrates (optional) Spring Cloud Netflix Ribbon load-balancing via the `lb` prefix on the destination URI. The primary scenario is to use the `fallbackUri` to an internal controller or handler within the gateway app. However, it is also possible to reroute the request to a controller or handler in an external application, like so: @@ -540,16 +582,14 @@ spring: - Path=/fallback ---- -In this example, there is no `fallback` endpoint or handler in the gateway application, however, there is one in another -app, registered under `http://localhost:9994`. +In this example, there is no `fallback` endpoint or handler in the gateway application, however, there is one in another app, registered under `http://localhost:9994`. -In case of the request being forwarded to fallback, the Hystrix Gateway filter also provides the `Throwable` that has -caused it. It's added to the `ServerWebExchange` as the -`ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR` attribute that can be used when -handling the fallback within the gateway app. +In case of the request being forwarded to fallback, the Hystrix Gateway filter also provides the `Throwable` that has caused it. +It's added to the `ServerWebExchange` as the +`ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR` attribute that can be used when handling the fallback within the gateway app. -For the external controller/ handler scenario, headers can be added with exception details. You can find more information -on it in the <>. +For the external controller/ handler scenario, headers can be added with exception details. +You can find more information on it in the <>. Hystrix settings (such as timeouts) can be configured with global defaults or on a route by route basis using application properties as explained on the https://github.com/Netflix/Hystrix/wiki/Configuration[Hystrix wiki]. @@ -562,9 +602,8 @@ hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 50 [[spring-cloud-circuitbreaker-filter-factory]] === Spring Cloud CircuitBreaker GatewayFilter Factory -The Spring Cloud CircuitBreaker filter factory leverages the Spring Cloud CircuitBreaker APIs to wrap Gateway routes in -a circuit breaker. Spring Cloud CircuitBreaker supports two libraries which can be used with Spring Cloud Gateway, Hystrix -and Resilience4J. Since Netflix has places Hystrix in maintenance only mode we suggest you use Resilience4J. +The Spring Cloud CircuitBreaker filter factory leverages the Spring Cloud CircuitBreaker APIs to wrap Gateway routes in a circuit breaker. +Spring Cloud CircuitBreaker supports two libraries which can be used with Spring Cloud Gateway, Hystrix and Resilience4J. Since Netflix has places Hystrix in maintenance only mode we suggest you use Resilience4J. To enable the Spring Cloud CircuitBreaker filter you will need to either place `spring-cloud-starter-circuitbreaker-reactor-resilience4j` or `spring-cloud-starter-netflix-hystrix` on the classpath. @@ -581,13 +620,15 @@ spring: filters: - CircuitBreaker=myCircuitBreaker ---- + To configure the circuit breaker, see the configuration for the underlying circuit breaker implementation you are using. * https://cloud.spring.io/spring-cloud-circuitbreaker/reference/html/spring-cloud-circuitbreaker.html[Resilience4J Documentation] * https://cloud.spring.io/spring-cloud-netflix/reference/html/[Hystrix Documentation] -The Spring Cloud CircuitBreaker filter can also accept an optional `fallbackUri` parameter. Currently, only `forward:` schemed URIs are supported. If the fallback is called, the request will be forwarded to the controller matched by the URI. - +The Spring Cloud CircuitBreaker filter can also accept an optional `fallbackUri` parameter. +Currently, only `forward:` schemed URIs are supported. +If the fallback is called, the request will be forwarded to the controller matched by the URI. .application.yml [source,yaml] @@ -621,7 +662,8 @@ public RouteLocator routes(RouteLocatorBuilder builder) { } ---- -This will forward to the `/inCaseofFailureUseThis` URI when the circuit breaker fallback is called. Note that this example also demonstrates (optional) Spring Cloud Netflix Ribbon load-balancing via the `lb` prefix on the destination URI. +This will forward to the `/inCaseofFailureUseThis` URI when the circuit breaker fallback is called. +Note that this example also demonstrates (optional) Spring Cloud Netflix Ribbon load-balancing via the `lb` prefix on the destination URI. The primary scenario is to use the `fallbackUri` to an internal controller or handler within the gateway app. However, it is also possible to reroute the request to a controller or handler in an external application, like so: @@ -648,22 +690,19 @@ spring: - Path=/fallback ---- -In this example, there is no `fallback` endpoint or handler in the gateway application, however, there is one in another -app, registered under `http://localhost:9994`. +In this example, there is no `fallback` endpoint or handler in the gateway application, however, there is one in another app, registered under `http://localhost:9994`. -In case of the request being forwarded to fallback, the Spring Cloud CircuitBreaker Gateway filter also provides the `Throwable` that has -caused it. It's added to the `ServerWebExchange` as the -`ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR` attribute that can be used when -handling the fallback within the gateway app. +In case of the request being forwarded to fallback, the Spring Cloud CircuitBreaker Gateway filter also provides the `Throwable` that has caused it. +It's added to the `ServerWebExchange` as the +`ServerWebExchangeUtils.CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR` attribute that can be used when handling the fallback within the gateway app. -For the external controller/handler scenario, headers can be added with exception details. You can find more information -on it in the <>. +For the external controller/handler scenario, headers can be added with exception details. +You can find more information on it in the <>. [[fallback-headers]] === FallbackHeaders GatewayFilter Factory -The `FallbackHeaders` factory allows you to add Hystrix or Spring Cloud CircuitBreaker execution exception details in headers of a request forwarded to -a `fallbackUri` in an external application, like in the following scenario: +The `FallbackHeaders` factory allows you to add Hystrix or Spring Cloud CircuitBreaker execution exception details in headers of a request forwarded to a `fallbackUri` in an external application, like in the following scenario: .application.yml [source,yaml] @@ -691,12 +730,10 @@ spring: executionExceptionTypeHeaderName: Test-Header ---- -In this example, after an execution exception occurs while running the circuit breaker, the request will be forwarded to -the `fallback` endpoint or handler in an app running on `localhost:9994`. The headers with the exception type, message -and -if available- root cause exception type and message will be added to that request by the `FallbackHeaders` filter. +In this example, after an execution exception occurs while running the circuit breaker, the request will be forwarded to the `fallback` endpoint or handler in an app running on `localhost:9994`. +The headers with the exception type, message and -if available- root cause exception type and message will be added to that request by the `FallbackHeaders` filter. -The names of the headers can be overwritten in the config by setting the values of the arguments listed below, along with -their default values: +The names of the headers can be overwritten in the config by setting the values of the arguments listed below, along with their default values: * `executionExceptionTypeHeaderName` (`"Execution-Exception-Type"`) * `executionExceptionMessageHeaderName` (`"Execution-Exception-Message"`) @@ -707,7 +744,11 @@ For more information of circuit beakers and the Gateway see the <>. === MapRequestHeader GatewayFilter Factory -The MapRequestHeader GatewayFilter Factory takes 'fromHeader' and 'toHeader' parameters. It creates a new named header (toHeader) and the value is extracted out of an existing named header (fromHeader) from the incoming http request. If the input header does not exist then the filter has no impact. If the new named header already exists then it's values will be augmented with the new values. + +The MapRequestHeader GatewayFilter Factory takes 'fromHeader' and 'toHeader' parameters. +It creates a new named header (toHeader) and the value is extracted out of an existing named header (fromHeader) from the incoming http request. +If the input header does not exist then the filter has no impact. +If the new named header already exists then it's values will be augmented with the new values. .application.yml [source,yaml] @@ -725,6 +766,7 @@ spring: This will add `X-Request-Foo:` header to the downstream request's with updated values from the incoming http request `Bar` header. === PrefixPath GatewayFilter Factory + The PrefixPath GatewayFilter Factory takes a single `prefix` parameter. .application.yml @@ -740,10 +782,13 @@ spring: - PrefixPath=/mypath ---- -This will prefix `/mypath` to the path of all matching requests. So a request to `/hello`, would be sent to `/mypath/hello`. +This will prefix `/mypath` to the path of all matching requests. +So a request to `/hello`, would be sent to `/mypath/hello`. === PreserveHostHeader GatewayFilter Factory -The PreserveHostHeader GatewayFilter Factory has no parameters. This filter sets a request attribute that the routing filter will inspect to determine if the original host header should be sent, rather than the host header determined by the http client. + +The PreserveHostHeader GatewayFilter Factory has no parameters. +This filter sets a request attribute that the routing filter will inspect to determine if the original host header should be sent, rather than the host header determined by the http client. .application.yml [source,yaml] @@ -760,11 +805,13 @@ spring: === RequestRateLimiter GatewayFilter Factory -The RequestRateLimiter GatewayFilter Factory is uses a `RateLimiter` implementation to determine if the current request is allowed to proceed. If it is not, a status of `HTTP 429 - Too Many Requests` (by default) is returned. +The RequestRateLimiter GatewayFilter Factory is uses a `RateLimiter` implementation to determine if the current request is allowed to proceed. +If it is not, a status of `HTTP 429 - Too Many Requests` (by default) is returned. This filter takes an optional `keyResolver` parameter and parameters specific to the rate limiter (see below). -`keyResolver` is a bean that implements the `KeyResolver` interface. In configuration, reference the bean by name using SpEL. `#{@myKeyResolver}` is a SpEL expression referencing a bean with the name `myKeyResolver`. +`keyResolver` is a bean that implements the `KeyResolver` interface. +In configuration, reference the bean by name using SpEL. `#{@myKeyResolver}` is a SpEL expression referencing a bean with the name `myKeyResolver`. .KeyResolver.java [source,java] @@ -774,13 +821,16 @@ public interface KeyResolver { } ---- -The `KeyResolver` interface allows pluggable strategies to derive the key for limiting requests. In future milestones, there will be some `KeyResolver` implementations. +The `KeyResolver` interface allows pluggable strategies to derive the key for limiting requests. +In future milestones, there will be some `KeyResolver` implementations. The default implementation of `KeyResolver` is the `PrincipalNameKeyResolver` which retrieves the `Principal` from the `ServerWebExchange` and calls `Principal.getName()`. -By default, if the `KeyResolver` does not find a key, requests will be denied. This behavior can be adjusted with the `spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key` (true or false) and `spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code` properties. +By default, if the `KeyResolver` does not find a key, requests will be denied. +This behavior can be adjusted with the `spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key` (true or false) and `spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code` properties. -NOTE: The RequestRateLimiter is not configurable via the "shortcut" notation. The example below is __invalid__ +NOTE: The RequestRateLimiter is not configurable via the "shortcut" notation. +The example below is __invalid__ .application.properties ---- @@ -790,15 +840,21 @@ spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=2, 2, #{@userkeyres ==== Redis RateLimiter -The redis implementation is based off of work done at https://stripe.com/blog/rate-limiters[Stripe]. It requires the use of the `spring-boot-starter-data-redis-reactive` Spring Boot starter. +The redis implementation is based off of work done at https://stripe.com/blog/rate-limiters[Stripe]. +It requires the use of the `spring-boot-starter-data-redis-reactive` Spring Boot starter. The algorithm used is the https://en.wikipedia.org/wiki/Token_bucket[Token Bucket Algorithm]. -The `redis-rate-limiter.replenishRate` is how many requests per second do you want a user to be allowed to do, without any dropped requests. This is the rate that the token bucket is filled. +The `redis-rate-limiter.replenishRate` is how many requests per second do you want a user to be allowed to do, without any dropped requests. +This is the rate that the token bucket is filled. -The `redis-rate-limiter.burstCapacity` is the maximum number of requests a user is allowed to do in a single second. This is the number of tokens the token bucket can hold. Setting this value to zero will block all requests. +The `redis-rate-limiter.burstCapacity` is the maximum number of requests a user is allowed to do in a single second. +This is the number of tokens the token bucket can hold. +Setting this value to zero will block all requests. -A steady rate is accomplished by setting the same value in `replenishRate` and `burstCapacity`. Temporary bursts can be allowed by setting `burstCapacity` higher than `replenishRate`. In this case, the rate limiter needs to be allowed some time between bursts (according to `replenishRate`), as 2 consecutive bursts will result in dropped requests (`HTTP 429 - Too Many Requests`). +A steady rate is accomplished by setting the same value in `replenishRate` and `burstCapacity`. +Temporary bursts can be allowed by setting `burstCapacity` higher than `replenishRate`. +In this case, the rate limiter needs to be allowed some time between bursts (according to `replenishRate`), as 2 consecutive bursts will result in dropped requests (`HTTP 429 - Too Many Requests`). .application.yml [source,yaml] @@ -826,9 +882,12 @@ KeyResolver userKeyResolver() { } ---- -This defines a request rate limit of 10 per user. A burst of 20 is allowed, but the next second only 10 requests will be available. The `KeyResolver` is a simple one that gets the `user` request parameter (note: this is not recommended for production). +This defines a request rate limit of 10 per user. +A burst of 20 is allowed, but the next second only 10 requests will be available. +The `KeyResolver` is a simple one that gets the `user` request parameter (note: this is not recommended for production). -A rate limiter can also be defined as a bean implementing the `RateLimiter` interface. In configuration, reference the bean by name using SpEL. `#{@myRateLimiter}` is a SpEL expression referencing a bean with the name `myRateLimiter`. +A rate limiter can also be defined as a bean implementing the `RateLimiter` interface. +In configuration, reference the bean by name using SpEL. `#{@myRateLimiter}` is a SpEL expression referencing a bean with the name `myRateLimiter`. .application.yml [source,yaml] @@ -847,8 +906,107 @@ spring: ---- +=== RequestQuotaFilter GatewayFilter Factory + +The RequestQuotaFilter GatewayFilter Factory is uses a `QuotaFilter` implementation to determine if the current request is allowed to proceed. +If it is not, a status of `HTTP 429 - Too Many Requests` (by default) is returned. + +This filter takes an optional `keyResolver` parameter and parameters specific to the quota filter (see RequestRateLimiter above). + +By default, if the `KeyResolver` does not find a key, requests will be denied. +This behavior can be adjusted with the `spring.cloud.gateway.filter.request-quota-filter.deny-empty-key` (true or false) and `spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code` properties. + +NOTE: The RequestQuotaFilter is not configurable via the "shortcut" notation. + +==== Redis QuotaFilter + +The redis quota filter requires the use of the `spring-boot-starter-data-redis-reactive` Spring Boot starter. + +The `redis-quota-filter.limit` is how many requests a user is allowed to do, without any dropped requests. + +The `redis-quota-filter.period` is the period how long the limit will exist. +The allowed units are: +`SECONDS, DAYS, HOURS, DAYS or ABS` +The implementation can be found in the `RedisQuotaFilter.QuotaPeriods.class`. +The `ABS` filter period will never expire, so the the limit will be not volatile as the other periods. + +.application.yml +[source,yaml] +---- +spring: + cloud: + gateway: + routes: + - id: request_quota_filter_route + uri: https://example.org + filters: + - name: RequestQuota + args: + redis-quota-filter.limit: 10 + redis-quota-filter.period: DAYS + +---- + +This defines a request quota limit of 10 requests per day. + +You can use a custom `KeyResolver` where you can specify patterns or request parameter matches where the quota filter will look for. + +.Config.java +[source,java] +---- +@Bean +KeyResolver customAuth() { + return exchange -> Mono.just(exchange.getRequest().getHeaders().getFirst("X-Authentication")); +} +---- + +The `KeyResolver` is a simple one that gets the first custom header in the request `X-Authentication`. + +The defined `KeyResolver` can be uses with the quota filter like: +.application.yml + +[source,yaml] +---- +spring: + cloud: + gateway: + routes: + - id: request_quota_filter_route + uri: https://example.org + filters: + - name: RequestQuota + args: + redis-quota-filter.limit: 10 + redis-quota-filter.period: DAYS + key-resolver: customAuth + +---- + +A quota filter can also be defined as a bean implementing the `QuotaFilter` interface. +In configuration, reference the bean by name using SpEL. `#{@myQuotaFilter}` is a SpEL expression referencing a bean with the name `myQuotaFilter`. + +.application.yml +[source,yaml] +---- +spring: + cloud: + gateway: + routes: + - id: requestratelimiter_route + uri: https://example.org + filters: + - name: RequestQuota + args: + quota-filter: "#{@myQuotaFilter}" + key-resolver: "#{@userKeyResolver}" + +---- + === RedirectTo GatewayFilter Factory -The RedirectTo GatewayFilter Factory takes a `status` and a `url` parameter. The status should be a 300 series redirect http code, such as 301. The url should be a valid url. This will be the value of the `Location` header. + +The RedirectTo GatewayFilter Factory takes a `status` and a `url` parameter. +The status should be a 300 series redirect http code, such as 301. The url should be a valid url. +This will be the value of the `Location` header. .application.yml [source,yaml] @@ -866,22 +1024,26 @@ spring: This will send a status 302 with a `Location:https://acme.org` header to perform a redirect. === RemoveHopByHopHeadersFilter GatewayFilter Factory -The RemoveHopByHopHeadersFilter GatewayFilter Factory removes headers from forwarded requests. The default list of headers that is removed comes from the https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-14#section-7.1.3[IETF]. + +The RemoveHopByHopHeadersFilter GatewayFilter Factory removes headers from forwarded requests. +The default list of headers that is removed comes from the https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-14#section-7.1.3[IETF]. .The default removed headers are: - * Connection - * Keep-Alive - * Proxy-Authenticate - * Proxy-Authorization - * TE - * Trailer - * Transfer-Encoding - * Upgrade +* Connection +* Keep-Alive +* Proxy-Authenticate +* Proxy-Authorization +* TE +* Trailer +* Transfer-Encoding +* Upgrade To change this, set the `spring.cloud.gateway.filter.remove-non-proxy-headers.headers` property to the list of header names to remove. === RemoveRequestHeader GatewayFilter Factory -The RemoveRequestHeader GatewayFilter Factory takes a `name` parameter. It is the name of the header to be removed. + +The RemoveRequestHeader GatewayFilter Factory takes a `name` parameter. +It is the name of the header to be removed. .application.yml [source,yaml] @@ -899,7 +1061,9 @@ spring: This will remove the `X-Request-Foo` header before it is sent downstream. === RemoveResponseHeader GatewayFilter Factory -The RemoveResponseHeader GatewayFilter Factory takes a `name` parameter. It is the name of the header to be removed. + +The RemoveResponseHeader GatewayFilter Factory takes a `name` parameter. +It is the name of the header to be removed. .application.yml [source,yaml] @@ -916,12 +1080,14 @@ spring: This will remove the `X-Response-Foo` header from the response before it is returned to the gateway client. -To remove any kind of sensitive header you should configure this filter for any routes that you may -want to do so. In addition you can configure this filter once using `spring.cloud.gateway.default-filters` +To remove any kind of sensitive header you should configure this filter for any routes that you may want to do so. +In addition you can configure this filter once using `spring.cloud.gateway.default-filters` and have it applied to all routes. === RemoveRequestParameter GatewayFilter Factory -The RemoveRequestParameter GatewayFilter Factory takes a `name` parameter. It is the name of the query parameter to be removed. + +The RemoveRequestParameter GatewayFilter Factory takes a `name` parameter. +It is the name of the query parameter to be removed. .application.yml [source,yaml] @@ -939,7 +1105,9 @@ spring: This will remove the `foo` parameter before it is sent downstream. === RewritePath GatewayFilter Factory -The RewritePath GatewayFilter Factory takes a path `regexp` parameter and a `replacement` parameter. This uses Java regular expressions for a flexible way to rewrite the request path. + +The RewritePath GatewayFilter Factory takes a path `regexp` parameter and a `replacement` parameter. +This uses Java regular expressions for a flexible way to rewrite the request path. .application.yml [source,yaml] @@ -956,10 +1124,13 @@ spring: - RewritePath=/foo(?/?.*), $\{segment} ---- -For a request path of `/foo/bar`, this will set the path to `/bar` before making the downstream request. Notice the `$` Should be replaced with `$\` because of the YAML spec. +For a request path of `/foo/bar`, this will set the path to `/bar` before making the downstream request. +Notice the `$` Should be replaced with `$\` because of the YAML spec. === RewriteLocationResponseHeader GatewayFilter Factory -The RewriteLocationResponseHeader GatewayFilter Factory modifies the value of `Location` response header, usually to get rid of backend specific details. It takes `stripVersionMode`, `locationHeaderName`, `hostValue`, and `protocolsRegex` parameters. + +The RewriteLocationResponseHeader GatewayFilter Factory modifies the value of `Location` response header, usually to get rid of backend specific details. +It takes `stripVersionMode`, `locationHeaderName`, `hostValue`, and `protocolsRegex` parameters. .application.yml [source,yaml] @@ -978,16 +1149,21 @@ For example, for a request `POST https://api.example.com/some/object/name`, `Loc Parameter `stripVersionMode` has the following possible values: `NEVER_STRIP`, `AS_IN_REQUEST` (default), `ALWAYS_STRIP`. - * `NEVER_STRIP` - Version will not be stripped, even if the original request path contains no version - * `AS_IN_REQUEST` - Version will be stripped only if the original request path contains no version - * `ALWAYS_STRIP` - Version will be stripped, even if the original request path contains version +* `NEVER_STRIP` - Version will not be stripped, even if the original request path contains no version +* `AS_IN_REQUEST` - Version will be stripped only if the original request path contains no version +* `ALWAYS_STRIP` - Version will be stripped, even if the original request path contains version -Parameter `hostValue`, if provided, will be used to replace the `host:port` portion of the response `Location` header. If not provided, the value of the `Host` request header will be used. +Parameter `hostValue`, if provided, will be used to replace the `host:port` portion of the response `Location` header. +If not provided, the value of the `Host` request header will be used. -Parameter `protocolsRegex` must be a valid regex `String`, against which the protocol name will be matched. If not matched, the filter will do nothing. Default is `http|https|ftp|ftps`. +Parameter `protocolsRegex` must be a valid regex `String`, against which the protocol name will be matched. +If not matched, the filter will do nothing. +Default is `http|https|ftp|ftps`. === RewriteResponseHeader GatewayFilter Factory -The RewriteResponseHeader GatewayFilter Factory takes `name`, `regexp`, and `replacement` parameters. It uses Java regular expressions for a flexible way to rewrite the response header value. + +The RewriteResponseHeader GatewayFilter Factory takes `name`, `regexp`, and `replacement` parameters. +It uses Java regular expressions for a flexible way to rewrite the response header value. .application.yml [source,yaml] @@ -1002,11 +1178,13 @@ spring: - RewriteResponseHeader=X-Response-Foo, , password=[^&]+, password=*** ---- -For a header value of `/42?user=ford&password=omg!what&flag=true`, it will be set to `/42?user=ford&password=\***&flag=true` after making the downstream request. Please use `$\` to mean `$` because of the YAML spec. +For a header value of `/42?user=ford&password=omg!what&flag=true`, it will be set to `/42?user=ford&password=\***&flag=true` after making the downstream request. +Please use `$\` to mean `$` because of the YAML spec. === SaveSession GatewayFilter Factory -The SaveSession GatewayFilter Factory forces a `WebSession::save` operation _before_ forwarding the call downstream. This is of particular use when -using something like https://projects.spring.io/spring-session/[Spring Session] with a lazy data store and need to ensure the session state has been saved before making the forwarded call. + +The SaveSession GatewayFilter Factory forces a `WebSession::save` operation _before_ forwarding the call downstream. +This is of particular use when using something like https://projects.spring.io/spring-session/[Spring Session] with a lazy data store and need to ensure the session state has been saved before making the forwarded call. .application.yml [source,yaml] @@ -1026,29 +1204,30 @@ spring: If you are integrating https://projects.spring.io/spring-security/[Spring Security] with Spring Session, and want to ensure security details have been forwarded to the remote process, this is critical. === SecureHeaders GatewayFilter Factory + The SecureHeaders GatewayFilter Factory adds a number of headers to the response at the recommendation from https://blog.appcanary.com/2017/http-security-headers.html[this blog post]. .The following headers are added (along with default values): - * `X-Xss-Protection:1; mode=block` - * `Strict-Transport-Security:max-age=631138519` - * `X-Frame-Options:DENY` - * `X-Content-Type-Options:nosniff` - * `Referrer-Policy:no-referrer` - * `Content-Security-Policy:default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'` - * `X-Download-Options:noopen` - * `X-Permitted-Cross-Domain-Policies:none` +* `X-Xss-Protection:1; mode=block` +* `Strict-Transport-Security:max-age=631138519` +* `X-Frame-Options:DENY` +* `X-Content-Type-Options:nosniff` +* `Referrer-Policy:no-referrer` +* `Content-Security-Policy:default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'` +* `X-Download-Options:noopen` +* `X-Permitted-Cross-Domain-Policies:none` To change the default values set the appropriate property in the `spring.cloud.gateway.filter.secure-headers` namespace: .Property to change: - * `xss-protection-header` - * `strict-transport-security` - * `frame-options` - * `content-type-options` - * `referrer-policy` - * `content-security-policy` - * `download-options` - * `permitted-cross-domain-policies` +* `xss-protection-header` +* `strict-transport-security` +* `frame-options` +* `content-type-options` +* `referrer-policy` +* `content-security-policy` +* `download-options` +* `permitted-cross-domain-policies` To disable the default values set the property `spring.cloud.gateway.filter.secure-headers.disable` with comma separated values. @@ -1056,7 +1235,11 @@ To disable the default values set the property `spring.cloud.gateway.filter.secu `spring.cloud.gateway.filter.secure-headers.disable=frame-options,download-options` === SetPath GatewayFilter Factory -The SetPath GatewayFilter Factory takes a path `template` parameter. It offers a simple way to manipulate the request path by allowing templated segments of the path. This uses the uri templates from Spring Framework. Multiple matching segments are allowed. + +The SetPath GatewayFilter Factory takes a path `template` parameter. +It offers a simple way to manipulate the request path by allowing templated segments of the path. +This uses the uri templates from Spring Framework. +Multiple matching segments are allowed. .application.yml [source,yaml] @@ -1076,6 +1259,7 @@ spring: For a request path of `/foo/bar`, this will set the path to `/bar` before making the downstream request. === SetRequestHeader GatewayFilter Factory + The SetRequestHeader GatewayFilter Factory takes `name` and `value` parameters. .application.yml @@ -1091,9 +1275,11 @@ spring: - SetRequestHeader=X-Request-Foo, Bar ---- -This GatewayFilter replaces all headers with the given name, rather than adding. So if the downstream server responded with a `X-Request-Foo:1234`, this would be replaced with `X-Request-Foo:Bar`, which is what the downstream service would receive. +This GatewayFilter replaces all headers with the given name, rather than adding. +So if the downstream server responded with a `X-Request-Foo:1234`, this would be replaced with `X-Request-Foo:Bar`, which is what the downstream service would receive. -SetRequestHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime. +SetRequestHeader is aware of URI variables used to match a path or host. +URI variables may be used in the value and will be expanded at runtime. .application.yml [source,yaml] @@ -1111,6 +1297,7 @@ spring: ---- === SetResponseHeader GatewayFilter Factory + The SetResponseHeader GatewayFilter Factory takes `name` and `value` parameters. .application.yml @@ -1126,9 +1313,11 @@ spring: - SetResponseHeader=X-Response-Foo, Bar ---- -This GatewayFilter replaces all headers with the given name, rather than adding. So if the downstream server responded with a `X-Response-Foo:1234`, this would be replaced with `X-Response-Foo:Bar`, which is what the gateway client would receive. +This GatewayFilter replaces all headers with the given name, rather than adding. +So if the downstream server responded with a `X-Response-Foo:1234`, this would be replaced with `X-Response-Foo:Bar`, which is what the gateway client would receive. -SetResponseHeader is aware of URI variables used to match a path or host. URI variables may be used in the value and will be expanded at runtime. +SetResponseHeader is aware of URI variables used to match a path or host. +URI variables may be used in the value and will be expanded at runtime. .application.yml [source,yaml] @@ -1146,7 +1335,10 @@ spring: ---- === SetStatus GatewayFilter Factory -The SetStatus GatewayFilter Factory takes a single `status` parameter. It must be a valid Spring `HttpStatus`. It may be the integer value `404` or the string representation of the enumeration `NOT_FOUND`. + +The SetStatus GatewayFilter Factory takes a single `status` parameter. +It must be a valid Spring `HttpStatus`. +It may be the integer value `404` or the string representation of the enumeration `NOT_FOUND`. .application.yml [source,yaml] @@ -1167,7 +1359,8 @@ spring: In either case, the HTTP status of the response will be set to 401. -The SetStatus GatewayFilter can be configured to return the original HTTP status code from the proxied request in a header in the response. Header will be added to the response if configured using following property. +The SetStatus GatewayFilter can be configured to return the original HTTP status code from the proxied request in a header in the response. +Header will be added to the response if configured using following property. .application.yml [source,yaml] @@ -1180,7 +1373,9 @@ spring: ---- === StripPrefix GatewayFilter Factory -The StripPrefix GatewayFilter Factory takes one parameter, `parts`. The `parts` parameter indicated the number of parts in the path to strip from the request before sending it downstream. + +The StripPrefix GatewayFilter Factory takes one parameter, `parts`. +The `parts` parameter indicated the number of parts in the path to strip from the request before sending it downstream. .application.yml [source,yaml] @@ -1208,7 +1403,8 @@ The Retry GatewayFilter Factory support following set of parameters: * `methods`: the HTTP methods that should be retried, represented using `org.springframework.http.HttpMethod` * `series`: the series of status codes to be retried, represented using `org.springframework.http.HttpStatus.Series` * `exceptions`: list of exceptions thrown that should be retried -* `backoff`: configured exponential backoff for the retries. Retries are performed after a backoff interval of `firstBackoff * (factor ^ n)` where `n` is the iteration. +* `backoff`: configured exponential backoff for the retries. +Retries are performed after a backoff interval of `firstBackoff * (factor ^ n)` where `n` is the iteration. If `maxBackoff` is configured, the maximum backoff applied will be limited to `maxBackoff`. If `basedOnPreviousValue` is true, backoff will be calculated using `prevBackoff * factor`. @@ -1245,10 +1441,14 @@ spring: NOTE: The retry filter does not currently support retrying with a body (e.g. for POST or PUT requests with a body). -NOTE: When using the retry filter with a `forward:` prefixed URL, the target endpoint should be written carefully so that in case of an error it does not do anything that could result in a response being sent to the client and committed. For example, if the target endpoint is an annotated controller, the target controller method should not return `ResponseEntity` with an error status code. Instead it should throw an `Exception`, or signal an error, e.g. via a `Mono.error(ex)` return value, which the retry filter can be configured to handle by retrying. +NOTE: When using the retry filter with a `forward:` prefixed URL, the target endpoint should be written carefully so that in case of an error it does not do anything that could result in a response being sent to the client and committed. +For example, if the target endpoint is an annotated controller, the target controller method should not return `ResponseEntity` with an error status code. +Instead it should throw an `Exception`, or signal an error, e.g. via a `Mono.error(ex)` return value, which the retry filter can be configured to handle by retrying. === RequestSize GatewayFilter Factory -The RequestSize GatewayFilter Factory can restrict a request from reaching the downstream service , when the request size is greater than the permissible limit. The filter takes `RequestSize` as parameter which is the permissible size limit of the request defined in bytes. + +The RequestSize GatewayFilter Factory can restrict a request from reaching the downstream service , when the request size is greater than the permissible limit. +The filter takes `RequestSize` as parameter which is the permissible size limit of the request defined in bytes. .application.yml [source,yaml] @@ -1267,7 +1467,8 @@ spring: maxSize: 5000000 ---- -The RequestSize GatewayFilter Factory set the response status as `413 Payload Too Large` with a additional header `errorMessage` when the Request is rejected due to size. Following is an example of such an `errorMessage` . +The RequestSize GatewayFilter Factory set the response status as `413 Payload Too Large` with a additional header `errorMessage` when the Request is rejected due to size. +Following is an example of such an `errorMessage` . `errorMessage` : `Request size is larger than permissible limit. Request size is 6.0 MB where permissible limit is 5.0 MB` @@ -1333,7 +1534,6 @@ public RouteLocator routes(RouteLocatorBuilder builder) { } ---- - === Default Filters If you would like to add a filter and apply it to all routes you can use `spring.cloud.gateway.default-filters`. @@ -1352,11 +1552,14 @@ spring: == Global Filters -The `GlobalFilter` interface has the same signature as `GatewayFilter`. These are special filters that are conditionally applied to all routes. (This interface and usage are subject to change in future milestones). +The `GlobalFilter` interface has the same signature as `GatewayFilter`. +These are special filters that are conditionally applied to all routes. +(This interface and usage are subject to change in future milestones). === Combined Global Filter and GatewayFilter Ordering -When a request comes in (and matches a Route) the Filtering Web Handler will add all instances of `GlobalFilter` and all route specific instances of `GatewayFilter` to a filter chain. This combined filter chain is sorted by the `org.springframework.core.Ordered` interface, which can be set by implementing the `getOrder()` method. +When a request comes in (and matches a Route) the Filtering Web Handler will add all instances of `GlobalFilter` and all route specific instances of `GatewayFilter` to a filter chain. +This combined filter chain is sorted by the `org.springframework.core.Ordered` interface, which can be set by implementing the `getOrder()` method. As Spring Cloud Gateway distinguishes between "pre" and "post" phases for filter logic execution (see: <>), the filter with the highest precedence will be the first in the "pre"-phase and the last in the "post"-phase. @@ -1385,11 +1588,16 @@ public class CustomGlobalFilter implements GlobalFilter, Ordered { === Forward Routing Filter -The `ForwardRoutingFilter` looks for a URI in the exchange attribute `ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`. If the url has a `forward` scheme (ie `forward:///localendpoint`), it will use the Spring `DispatcherHandler` to handler the request. The path part of the request URL will be overridden with the path in the forward URL. The unmodified original url is appended to the list in the `ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR` attribute. +The `ForwardRoutingFilter` looks for a URI in the exchange attribute `ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`. +If the url has a `forward` scheme (ie `forward:///localendpoint`), it will use the Spring `DispatcherHandler` to handler the request. +The path part of the request URL will be overridden with the path in the forward URL. The unmodified original url is appended to the list in the `ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR` attribute. === LoadBalancerClient Filter -The `LoadBalancerClientFilter` looks for a URI in the exchange attribute `ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`. If the url has a `lb` scheme (ie `lb://myservice`), it will use the Spring Cloud `LoadBalancerClient` to resolve the name (`myservice` in the previous example) to an actual host and port and replace the URI in the same attribute. The unmodified original url is appended to the list in the `ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR` attribute. The filter will also look in the `ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR` attribute to see if it equals `lb` and then the same rules apply. +The `LoadBalancerClientFilter` looks for a URI in the exchange attribute `ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`. +If the url has a `lb` scheme (ie `lb://myservice`), it will use the Spring Cloud `LoadBalancerClient` to resolve the name (`myservice` in the previous example) to an actual host and port and replace the URI in the same attribute. +The unmodified original url is appended to the list in the `ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR` attribute. +The filter will also look in the `ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR` attribute to see if it equals `lb` and then the same rules apply. .application.yml [source,yaml] @@ -1407,12 +1615,12 @@ spring: NOTE: By default when a service instance cannot be found in the `LoadBalancer` a `503` will be returned. You can configure the Gateway to return a `404` by setting `spring.cloud.gateway.loadbalancer.use404=true`. -NOTE: The `isSecure` value of the `ServiceInstance` returned from the `LoadBalancer` will override -the scheme specified in the request made to the Gateway. For example, if the request comes into the Gateway over `HTTPS` +NOTE: The `isSecure` value of the `ServiceInstance` returned from the `LoadBalancer` will override the scheme specified in the request made to the Gateway. +For example, if the request comes into the Gateway over `HTTPS` but the `ServiceInstance` indicates it is not secure, then the downstream request will be made over -`HTTP`. The opposite situation can also apply. However if `GATEWAY_SCHEME_PREFIX_ATTR` is specified for the -route in the Gateway configuration, the prefix will be stripped and the resulting scheme from the -route URL will override the `ServiceInstance` configuration. +`HTTP`. +The opposite situation can also apply. +However if `GATEWAY_SCHEME_PREFIX_ATTR` is specified for the route in the Gateway configuration, the prefix will be stripped and the resulting scheme from the route URL will override the `ServiceInstance` configuration. WARNING: `LoadBalancerClientFilter` uses a blocking Ribbon `LoadBalancerClient` under the hood. We suggest you use <>. @@ -1422,10 +1630,9 @@ You can switch to using it by setting the value of the `spring.cloud.loadbalance === ReactiveLoadBalancerClientFilter The `ReactiveLoadBalancerClientFilter` looks for a URI in the exchange attribute -`ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`. If the url has a `lb` scheme (ie `lb://myservice`), -it will use the Spring Cloud `ReactorLoadBalancer` to resolve the name (`myservice` in the previous example) -to an actual host and port and replace the URI in the same attribute. The unmodified -original url is appended to the list in the `ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR` attribute. +`ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR`. +If the url has a `lb` scheme (ie `lb://myservice`), it will use the Spring Cloud `ReactorLoadBalancer` to resolve the name (`myservice` in the previous example) to an actual host and port and replace the URI in the same attribute. +The unmodified original url is appended to the list in the `ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR` attribute. The filter will also look in the `ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR` attribute to see if it equals `lb` and then the same rules apply. @@ -1445,30 +1652,38 @@ spring: NOTE: By default when a service instance cannot be found by the `ReactorLoadBalancer`, a `503` will be returned. You can configure the Gateway to return a `404` by setting `spring.cloud.gateway.loadbalancer.use404=true`. -NOTE: The `isSecure` value of the `ServiceInstance` returned from the `ReactiveLoadBalancerClientFilter` will override -the scheme specified in the request made to the Gateway. For example, if the request comes into the Gateway over `HTTPS` +NOTE: The `isSecure` value of the `ServiceInstance` returned from the `ReactiveLoadBalancerClientFilter` will override the scheme specified in the request made to the Gateway. +For example, if the request comes into the Gateway over `HTTPS` but the `ServiceInstance` indicates it is not secure, then the downstream request will be made over -`HTTP`. The opposite situation can also apply. However if `GATEWAY_SCHEME_PREFIX_ATTR` is specified for the -route in the Gateway configuration, the prefix will be stripped and the resulting scheme from the -route URL will override the `ServiceInstance` configuration. +`HTTP`. +The opposite situation can also apply. +However if `GATEWAY_SCHEME_PREFIX_ATTR` is specified for the route in the Gateway configuration, the prefix will be stripped and the resulting scheme from the route URL will override the `ServiceInstance` configuration. === Netty Routing Filter -The Netty Routing Filter runs if the url located in the `ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR` exchange attribute has a `http` or `https` scheme. It uses the Netty `HttpClient` to make the downstream proxy request. The response is put in the `ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR` exchange attribute for use in a later filter. (There is an experimental `WebClientHttpRoutingFilter` that performs the same function, but does not require netty) +The Netty Routing Filter runs if the url located in the `ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR` exchange attribute has a `http` or `https` scheme. +It uses the Netty `HttpClient` to make the downstream proxy request. +The response is put in the `ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR` exchange attribute for use in a later filter. +(There is an experimental `WebClientHttpRoutingFilter` that performs the same function, but does not require netty) === Netty Write Response Filter -The `NettyWriteResponseFilter` runs if there is a Netty `HttpClientResponse` in the `ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR` exchange attribute. It is run after all other filters have completed and writes the proxy response back to the gateway client response. (There is an experimental `WebClientWriteResponseFilter` that performs the same function, but does not require netty) +The `NettyWriteResponseFilter` runs if there is a Netty `HttpClientResponse` in the `ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR` exchange attribute. +It is run after all other filters have completed and writes the proxy response back to the gateway client response. +(There is an experimental `WebClientWriteResponseFilter` that performs the same function, but does not require netty) === RouteToRequestUrl Filter -The `RouteToRequestUrlFilter` runs if there is a `Route` object in the `ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR` exchange attribute. It creates a new URI, based off of the request URI, but updated with the URI attribute of the `Route` object. The new URI is placed in the `ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR` exchange attribute`. +The `RouteToRequestUrlFilter` runs if there is a `Route` object in the `ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR` exchange attribute. +It creates a new URI, based off of the request URI, but updated with the URI attribute of the `Route` object. +The new URI is placed in the `ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR` exchange attribute`. If the URI has a scheme prefix, such as `lb:ws://serviceid`, the `lb` scheme is stripped from the URI and placed in the `ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR` for use later in the filter chain. === Websocket Routing Filter -The Websocket Routing Filter runs if the url located in the `ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR` exchange attribute has a `ws` or `wss` scheme. It uses the Spring Web Socket infrastructure to forward the Websocket request downstream. +The Websocket Routing Filter runs if the url located in the `ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR` exchange attribute has a `ws` or `wss` scheme. +It uses the Spring Web Socket infrastructure to forward the Websocket request downstream. Websockets may be load-balanced by prefixing the URI with `lb`, such as `lb:ws://serviceid`. @@ -1495,7 +1710,9 @@ spring: === Gateway Metrics Filter -To enable Gateway Metrics add spring-boot-starter-actuator as a project dependency. Then, by default, the Gateway Metrics Filter runs as long as the property `spring.cloud.gateway.metrics.enabled` is not set to `false`. This filter adds a timer metric named "gateway.requests" with the following tags: +To enable Gateway Metrics add spring-boot-starter-actuator as a project dependency. +Then, by default, the Gateway Metrics Filter runs as long as the property `spring.cloud.gateway.metrics.enabled` is not set to `false`. +This filter adds a timer metric named "gateway.requests" with the following tags: * `routeId`: The route id * `routeUri`: The URI that the API will be routed to @@ -1511,15 +1728,17 @@ NOTE: To enable the prometheus endpoint add micrometer-registry-prometheus as a === Marking An Exchange As Routed After the Gateway has routed a `ServerWebExchange` it will mark that exchange as "routed" by adding `gatewayAlreadyRouted` -to the exchange attributes. Once a request has been marked as routed, other routing filters will not route the request again, -essentially skipping the filter. There are convenience methods that you can use to mark an exchange as routed -or check if an exchange has already been routed. +to the exchange attributes. +Once a request has been marked as routed, other routing filters will not route the request again, essentially skipping the filter. +There are convenience methods that you can use to mark an exchange as routed or check if an exchange has already been routed. * `ServerWebExchangeUtils.isAlreadyRouted` takes a `ServerWebExchange` object and checks if it has been "routed" * `ServerWebExchangeUtils.setAlreadyRouted` takes a `ServerWebExchange` object and marks it as "routed" == TLS / SSL -The Gateway can listen for requests on https by following the usual Spring server configuration. Example: + +The Gateway can listen for requests on https by following the usual Spring server configuration. +Example: .application.yml [source,yaml] @@ -1533,7 +1752,8 @@ server: key-store-type: PKCS12 ---- -Gateway routes can be routed to both http and https backends. If routing to a https backend then the Gateway can be configured to trust all downstream certificates with the following configuration: +Gateway routes can be routed to both http and https backends. +If routing to a https backend then the Gateway can be configured to trust all downstream certificates with the following configuration: .application.yml [source,yaml] @@ -1546,7 +1766,8 @@ spring: useInsecureTrustManager: true ---- -Using an insecure trust manager is not suitable for production. For a production deployment the Gateway can be configured with a set of known certificates that it can trust with the following configuration: +Using an insecure trust manager is not suitable for production. +For a production deployment the Gateway can be configured with a set of known certificates that it can trust with the following configuration: .application.yml [source,yaml] @@ -1565,7 +1786,10 @@ If the Spring Cloud Gateway is not provisioned with trusted certificates the def === TLS Handshake -The Gateway maintains a client pool that it uses to route to backends. When communicating over https the client initiates a TLS handshake. A number of timeouts are associated with this handshake. These timeouts can be configured (defaults shown): +The Gateway maintains a client pool that it uses to route to backends. +When communicating over https the client initiates a TLS handshake. +A number of timeouts are associated with this handshake. +These timeouts can be configured (defaults shown): .application.yml [source,yaml] @@ -1594,7 +1818,8 @@ public interface RouteDefinitionLocator { By default, a `PropertiesRouteDefinitionLocator` loads properties using Spring Boot's `@ConfigurationProperties` mechanism. -The configuration examples above all use a shortcut notation that uses positional arguments rather than named ones. The two examples below are equivalent: +The configuration examples above all use a shortcut notation that uses positional arguments rather than named ones. +The two examples below are equivalent: .application.yml [source,yaml] @@ -1615,9 +1840,11 @@ spring: - SetStatus=401 ---- -For some usages of the gateway, properties will be adequate, but some production use cases will benefit from loading configuration from an external source, such as a database. Future milestone versions will have `RouteDefinitionLocator` implementations based off of Spring Data Repositories such as: Redis, MongoDB and Cassandra. +For some usages of the gateway, properties will be adequate, but some production use cases will benefit from loading configuration from an external source, such as a database. +Future milestone versions will have `RouteDefinitionLocator` implementations based off of Spring Data Repositories such as: Redis, MongoDB and Cassandra. == Route metadata configuration + Additional parameters can be configured for each route using metadata: .application.yml @@ -1637,6 +1864,7 @@ spring: ---- All metadata properties could be acquired from exchange: + ``` Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR); // get all metadata properties @@ -1705,6 +1933,7 @@ import static org.springframework.cloud.gateway.support.RouteMetadataUtils.RESPO ---- === Fluent Java Routes API + To allow for simple configuration in Java, there is a fluent API defined in the `RouteLocatorBuilder` bean. .GatewaySampleApplication.java @@ -1738,7 +1967,9 @@ public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGate } ---- -This style also allows for more custom predicate assertions. The predicates defined by `RouteDefinitionLocator` beans are combined using logical `and`. By using the fluent Java API, you can use the `and()`, `or()` and `negate()` operators on the `Predicate` class. +This style also allows for more custom predicate assertions. +The predicates defined by `RouteDefinitionLocator` beans are combined using logical `and`. +By using the fluent Java API, you can use the `and()`, `or()` and `negate()` operators on the `Predicate` class. === DiscoveryClient Route Definition Locator @@ -1750,17 +1981,15 @@ To enable this, set `spring.cloud.gateway.discovery.locator.enabled=true` and ma By default the Gateway defines a single predicate and filter for routes created via a `DiscoveryClient`. -The default predicate is a path predicate defined with the pattern `/serviceId/**`, where `serviceId` is -the id of the service from the `DiscoveryClient`. +The default predicate is a path predicate defined with the pattern `/serviceId/**`, where `serviceId` is the id of the service from the `DiscoveryClient`. The default filter is rewrite path filter with the regex `/serviceId/(?.*)` and the replacement -`/${remaining}`. This just strips the service id from the path before the request is sent -downstream. +`/${remaining}`. +This just strips the service id from the path before the request is sent downstream. -If you would like to customize the predicates and/or filters used by the `DiscoveryClient` routes you can do so -by setting `spring.cloud.gateway.discovery.locator.predicates[x]` and `spring.cloud.gateway.discovery.locator.filters[y]`. -When doing so you need to make sure to include the default predicate and filter above, if you want to retain -that functionality. Below is an example of what this looks like. +If you would like to customize the predicates and/or filters used by the `DiscoveryClient` routes you can do so by setting `spring.cloud.gateway.discovery.locator.predicates[x]` and `spring.cloud.gateway.discovery.locator.filters[y]`. +When doing so you need to make sure to include the default predicate and filter above, if you want to retain that functionality. +Below is an example of what this looks like. .application.properties [soure,properties] @@ -1778,9 +2007,11 @@ spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remain == Reactor Netty Access Logs -To enable Reactor Netty access logs, set `-Dreactor.netty.http.server.accessLogEnabled=true`. (It must be a Java System Property, not a Spring Boot property). +To enable Reactor Netty access logs, set `-Dreactor.netty.http.server.accessLogEnabled=true`. +(It must be a Java System Property, not a Spring Boot property). -The logging system can be configured to have a separate access log file. Below is an example logback configuration: +The logging system can be configured to have a separate access log file. +Below is an example logback configuration: .logback.xml [source,xml] @@ -1802,7 +2033,8 @@ The logging system can be configured to have a separate access log file. Below i == CORS Configuration -The gateway can be configured to control CORS behavior. The "global" CORS configuration is a map of URL patterns to https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/cors/CorsConfiguration.html[Spring Framework `CorsConfiguration`]. +The gateway can be configured to control CORS behavior. +The "global" CORS configuration is a map of URL patterns to https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/cors/CorsConfiguration.html[Spring Framework `CorsConfiguration`]. .application.yml [source,yaml] @@ -1820,11 +2052,13 @@ spring: In the example above, CORS requests will be allowed from requests that originate from docs.spring.io for all GET requested paths. -To provide the same CORS configuration to requests that are not handled by some gateway route predicate, set the property `spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping` equal to true. This is useful when trying to support CORS preflight requests and your route predicate doesn't evalute to true because the http method is `options`. +To provide the same CORS configuration to requests that are not handled by some gateway route predicate, set the property `spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping` equal to true. +This is useful when trying to support CORS preflight requests and your route predicate doesn't evalute to true because the http method is `options`. == Actuator API -The `/gateway` actuator endpoint allows to monitor and interact with a Spring Cloud Gateway application. To be remotely accessible, the endpoint has to be https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#production-ready-endpoints-enabling-endpoints[enabled] and https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#production-ready-endpoints-exposing-endpoints[exposed via HTTP or JMX] in the application properties. +The `/gateway` actuator endpoint allows to monitor and interact with a Spring Cloud Gateway application. +To be remotely accessible, the endpoint has to be https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#production-ready-endpoints-enabling-endpoints[enabled] and https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#production-ready-endpoints-exposing-endpoints[exposed via HTTP or JMX] in the application properties. .application.properties [source,properties] @@ -1835,9 +2069,11 @@ management.endpoints.web.exposure.include=gateway === Verbose Actuator Format -A new, more verbose format has been added to Gateway. This adds more detail to each route allowing to view the predicates and filters associated to each route along with any configuration that is available. +A new, more verbose format has been added to Gateway. +This adds more detail to each route allowing to view the predicates and filters associated to each route along with any configuration that is available. `/actuator/gateway/routes` + [source,json] ---- [ @@ -1855,7 +2091,8 @@ A new, more verbose format has been added to Gateway. This adds more detail to e ] ---- -This feature is enabled by default. To disable it, set the following property: +This feature is enabled by default. +To disable it, set the following property: .application.properties [source,properties] @@ -1866,8 +2103,11 @@ spring.cloud.gateway.actuator.verbose.enabled=false This will default to true in a future release. === Retrieving route filters + ==== Global Filters -To retrieve the <> applied to all routes, make a `GET` request to `/actuator/gateway/globalfilters`. The resulting response is similar to the following: + +To retrieve the <> applied to all routes, make a `GET` request to `/actuator/gateway/globalfilters`. +The resulting response is similar to the following: ---- { @@ -1882,10 +2122,13 @@ To retrieve the <> applied to all routes, make a } ---- -The response contains details of the global filters in place. For each global filter is provided the string representation of the filter object (e.g., `org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5`) and the corresponding <> in the filter chain. +The response contains details of the global filters in place. +For each global filter is provided the string representation of the filter object (e.g., `org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5`) and the corresponding <> in the filter chain. ==== Route Filters -To retrieve the <> applied to routes, make a `GET` request to `/actuator/gateway/routefilters`. The resulting response is similar to the following: + +To retrieve the <> applied to routes, make a `GET` request to `/actuator/gateway/routefilters`. +The resulting response is similar to the following: ---- { @@ -1895,13 +2138,19 @@ To retrieve the <> applied to r } ---- -The response contains details of the GatewayFilter factories applied to any particular route. For each factory is provided the string representation of the corresponding object (e.g., `[SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]`). Note that the `null` value is due to an incomplete implementation of the endpoint controller, for that it tries to set the order of the object in the filter chain, which does not apply to a GatewayFilter factory object. +The response contains details of the GatewayFilter factories applied to any particular route. +For each factory is provided the string representation of the corresponding object (e.g., `[SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]`). +Note that the `null` value is due to an incomplete implementation of the endpoint controller, for that it tries to set the order of the object in the filter chain, which does not apply to a GatewayFilter factory object. === Refreshing the route cache -To clear the routes cache, make a `POST` request to `/actuator/gateway/refresh`. The request returns a 200 without response body. + +To clear the routes cache, make a `POST` request to `/actuator/gateway/refresh`. +The request returns a 200 without response body. === Retrieving the routes defined in the gateway -To retrieve the routes defined in the gateway, make a `GET` request to `/actuator/gateway/routes`. The resulting response is similar to the following: + +To retrieve the routes defined in the gateway, make a `GET` request to `/actuator/gateway/routes`. +The resulting response is similar to the following: ---- [{ @@ -1924,7 +2173,8 @@ To retrieve the routes defined in the gateway, make a `GET` request to `/actuato }] ---- -The response contains details of all the routes defined in the gateway. The following table describes the structure of each element (i.e., a route) of the response. +The response contains details of all the routes defined in the gateway. +The following table describes the structure of each element (i.e., a route) of the response. [cols="3,2,4"] |=== @@ -1949,7 +2199,9 @@ The response contains details of all the routes defined in the gateway. The foll |=== === Retrieving information about a particular route -To retrieve information about a single route, make a `GET` request to `/actuator/gateway/routes/{id}` (e.g., `/actuator/gateway/routes/first_route`). The resulting response is similar to the following: + +To retrieve information about a single route, make a `GET` request to `/actuator/gateway/routes/{id}` (e.g., `/actuator/gateway/routes/first_route`). +The resulting response is similar to the following: ---- { @@ -1993,12 +2245,15 @@ The following table describes the structure of the response. |=== === Creating and deleting a particular route + To create a route, make a `POST` request to `/gateway/routes/{id_route_to_create}` with a JSON body that specifies the fields of the route (see the previous subsection). To delete a route, make a `DELETE` request to `/gateway/routes/{id_route_to_delete}`. === Recap: list of all endpoints -The table below summarises the Spring Cloud Gateway actuator endpoints. Note that each endpoint has `/actuator/gateway` as the base-path. + +The table below summarises the Spring Cloud Gateway actuator endpoints. +Note that each endpoint has `/actuator/gateway` as the base-path. [cols="2,2,5"] |=== @@ -2050,10 +2305,9 @@ Below are some useful loggers that contain valuable trouble shooting infomration === Wiretap -The Reactor Netty `HttpClient` and `HttpServer` can have wiretap enabled. When combined -with setting the `reactor.netty` log level to `DEBUG` or `TRACE` will enable logging of -information such as headers and bodies sent and received across the wire. To enable this, -set `spring.cloud.gateway.httpserver.wiretap=true` and/or +The Reactor Netty `HttpClient` and `HttpServer` can have wiretap enabled. +When combined with setting the `reactor.netty` log level to `DEBUG` or `TRACE` will enable logging of information such as headers and bodies sent and received across the wire. +To enable this, set `spring.cloud.gateway.httpserver.wiretap=true` and/or `spring.cloud.gateway.httpclient.wiretap=true` for the `HttpServer` and `HttpClient` respectively. @@ -2067,7 +2321,8 @@ TODO: document writing Custom Route Predicate Factories === Writing Custom GatewayFilter Factories -In order to write a GatewayFilter you will need to implement `GatewayFilterFactory`. There is an abstract class called `AbstractGatewayFilterFactory` which you can extend. +In order to write a GatewayFilter you will need to implement `GatewayFilterFactory`. +There is an abstract class called `AbstractGatewayFilterFactory` which you can extend. .PreGatewayFilterFactory.java [source,java] @@ -2126,7 +2381,8 @@ public class PostGatewayFilterFactory extends AbstractGatewayFilterFactory proxyPath(ProxyExchange proxy) throws Exception } ``` -All the features of Spring MVC or Webflux are available to Gateway handler methods. So you can inject request headers and query parameters, for instance, and you can constrain the incoming requests with declarations in the mapping annotation. See the documentation for `@RequestMapping` in Spring MVC for more details of those features. +All the features of Spring MVC or Webflux are available to Gateway handler methods. +So you can inject request headers and query parameters, for instance, and you can constrain the incoming requests with declarations in the mapping annotation. +See the documentation for `@RequestMapping` in Spring MVC for more details of those features. Headers can be added to the downstream response using the `header()` methods on `ProxyExchange`. -You can also manipulate response headers (and anything else you like in the response) by adding a mapper to the `get()` etc. method. The mapper is a `Function` that takes the incoming `ResponseEntity` and converts it to an outgoing one. +You can also manipulate response headers (and anything else you like in the response) by adding a mapper to the `get()` etc. method. +The mapper is a `Function` that takes the incoming `ResponseEntity` and converts it to an outgoing one. First class support is provided for "sensitive" headers ("cookie" and "authorization" by default) which are not passed downstream, and for "proxy" headers (`x-forwarded-*`). From b2c004665a8c14324b88db2711f39cc7509761c8 Mon Sep 17 00:00:00 2001 From: HappyTobi Date: Sun, 15 Dec 2019 22:23:22 +0100 Subject: [PATCH 4/7] Move filters back to filters package because of backward compatibility --- .../cloud/gateway/config/GatewayAutoConfiguration.java | 8 ++++---- .../gateway/config/GatewayRedisAutoConfiguration.java | 4 ++-- .../cloud/gateway/filter/{redis => }/KeyResolver.java | 2 +- .../filter/{redis => }/PrincipalNameKeyResolver.java | 2 +- .../filter/factory/RequestQuotaGatewayFilterFactory.java | 4 ++-- .../factory/RequestRateLimiterGatewayFilterFactory.java | 4 ++-- .../filter/{redis => }/quota/AbstractQuotaLimiter.java | 2 +- .../gateway/filter/{redis => }/quota/QuotaFilter.java | 2 +- .../filter/{redis => }/quota/RedisQuotaFilter.java | 4 ++-- .../filter/{redis => }/ratelimit/AbstractRateLimiter.java | 2 +- .../gateway/filter/{redis => }/ratelimit/RateLimiter.java | 2 +- .../filter/{redis => }/ratelimit/RedisRateLimiter.java | 2 +- .../cloud/gateway/route/builder/GatewayFilterSpec.java | 4 ++-- .../RequestRateLimiterGatewayFilterFactoryTests.java | 6 +++--- .../quota/PrincipalNameKeyResolverIntegrationTests.java | 2 +- .../{redis => }/quota/RedisQuotaFilterConfigTests.java | 2 +- .../quota/RedisQuotaFilterDefaultFilterConfigTests.java | 2 +- .../filter/{redis => }/quota/RedisQuotaFilterTests.java | 4 ++-- .../PrincipalNameKeyResolverIntegrationTests.java | 2 +- .../ratelimit/RedisRateLimiterConfigTests.java | 2 +- .../RedisRateLimiterDefaultFilterConfigTests.java | 2 +- .../{redis => }/ratelimit/RedisRateLimiterTests.java | 4 ++-- .../cloud/gateway/test/AdhocTestSuite.java | 6 +++--- 23 files changed, 37 insertions(+), 37 deletions(-) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{redis => }/KeyResolver.java (93%) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{redis => }/PrincipalNameKeyResolver.java (95%) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{redis => }/quota/AbstractQuotaLimiter.java (97%) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{redis => }/quota/QuotaFilter.java (96%) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{redis => }/quota/RedisQuotaFilter.java (98%) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{redis => }/ratelimit/AbstractRateLimiter.java (98%) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{redis => }/ratelimit/RateLimiter.java (96%) rename spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/{redis => }/ratelimit/RedisRateLimiter.java (99%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{redis => }/quota/PrincipalNameKeyResolverIntegrationTests.java (98%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{redis => }/quota/RedisQuotaFilterConfigTests.java (98%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{redis => }/quota/RedisQuotaFilterDefaultFilterConfigTests.java (97%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{redis => }/quota/RedisQuotaFilterTests.java (97%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{redis => }/ratelimit/PrincipalNameKeyResolverIntegrationTests.java (98%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{redis => }/ratelimit/RedisRateLimiterConfigTests.java (98%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{redis => }/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java (97%) rename spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/{redis => }/ratelimit/RedisRateLimiterTests.java (96%) diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java index cf2ea2698d..7216abb77d 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java @@ -56,8 +56,10 @@ import org.springframework.cloud.gateway.filter.ForwardPathFilter; import org.springframework.cloud.gateway.filter.ForwardRoutingFilter; import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.cloud.gateway.filter.KeyResolver; import org.springframework.cloud.gateway.filter.NettyRoutingFilter; import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter; +import org.springframework.cloud.gateway.filter.PrincipalNameKeyResolver; import org.springframework.cloud.gateway.filter.RemoveCachedBodyFilter; import org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter; import org.springframework.cloud.gateway.filter.WebsocketRoutingFilter; @@ -99,10 +101,8 @@ import org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter; import org.springframework.cloud.gateway.filter.headers.RemoveHopByHopHeadersFilter; import org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter; -import org.springframework.cloud.gateway.filter.redis.KeyResolver; -import org.springframework.cloud.gateway.filter.redis.PrincipalNameKeyResolver; -import org.springframework.cloud.gateway.filter.redis.quota.QuotaFilter; -import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter; +import org.springframework.cloud.gateway.filter.quota.QuotaFilter; +import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; import org.springframework.cloud.gateway.handler.FilteringWebHandler; import org.springframework.cloud.gateway.handler.RoutePredicateHandlerMapping; import org.springframework.cloud.gateway.handler.predicate.AfterRoutePredicateFactory; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayRedisAutoConfiguration.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayRedisAutoConfiguration.java index e1663080c6..4b85bda9d8 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayRedisAutoConfiguration.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/config/GatewayRedisAutoConfiguration.java @@ -25,8 +25,8 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration; -import org.springframework.cloud.gateway.filter.redis.quota.RedisQuotaFilter; -import org.springframework.cloud.gateway.filter.redis.ratelimit.RedisRateLimiter; +import org.springframework.cloud.gateway.filter.quota.RedisQuotaFilter; +import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; import org.springframework.cloud.gateway.support.ConfigurationService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/KeyResolver.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/KeyResolver.java similarity index 93% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/KeyResolver.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/KeyResolver.java index d524aaf23f..e1431d68bb 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/KeyResolver.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/KeyResolver.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis; +package org.springframework.cloud.gateway.filter; import reactor.core.publisher.Mono; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/PrincipalNameKeyResolver.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/PrincipalNameKeyResolver.java similarity index 95% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/PrincipalNameKeyResolver.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/PrincipalNameKeyResolver.java index 02f2f276e6..42eb0b462d 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/PrincipalNameKeyResolver.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/PrincipalNameKeyResolver.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis; +package org.springframework.cloud.gateway.filter; import java.security.Principal; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestQuotaGatewayFilterFactory.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestQuotaGatewayFilterFactory.java index bfbeebdfbf..5cae97c041 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestQuotaGatewayFilterFactory.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestQuotaGatewayFilterFactory.java @@ -20,8 +20,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.gateway.filter.GatewayFilter; -import org.springframework.cloud.gateway.filter.redis.KeyResolver; -import org.springframework.cloud.gateway.filter.redis.quota.QuotaFilter; +import org.springframework.cloud.gateway.filter.KeyResolver; +import org.springframework.cloud.gateway.filter.quota.QuotaFilter; import org.springframework.cloud.gateway.route.Route; import org.springframework.cloud.gateway.support.HasRouteId; import org.springframework.cloud.gateway.support.HttpStatusHolder; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactory.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactory.java index 88ff79c25b..d1990ac4a2 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactory.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactory.java @@ -20,8 +20,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.gateway.filter.GatewayFilter; -import org.springframework.cloud.gateway.filter.redis.KeyResolver; -import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter; +import org.springframework.cloud.gateway.filter.KeyResolver; +import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; import org.springframework.cloud.gateway.route.Route; import org.springframework.cloud.gateway.support.HasRouteId; import org.springframework.cloud.gateway.support.HttpStatusHolder; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/AbstractQuotaLimiter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/AbstractQuotaLimiter.java similarity index 97% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/AbstractQuotaLimiter.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/AbstractQuotaLimiter.java index 21da6182c9..97b46c6942 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/AbstractQuotaLimiter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/AbstractQuotaLimiter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.quota; +package org.springframework.cloud.gateway.filter.quota; import java.util.Map; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/QuotaFilter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/QuotaFilter.java similarity index 96% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/QuotaFilter.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/QuotaFilter.java index 52e348d5db..77db12b48c 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/QuotaFilter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/QuotaFilter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.quota; +package org.springframework.cloud.gateway.filter.quota; import java.util.Collections; import java.util.Map; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java similarity index 98% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilter.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java index 9dc3b3dc0e..711221d8b7 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.quota; +package org.springframework.cloud.gateway.filter.quota; import java.util.ArrayList; import java.util.Arrays; @@ -194,7 +194,7 @@ public void setApplicationContext(ApplicationContext context) throws BeansExcept */ @Override @SuppressWarnings("unchecked") - public Mono isAllowed(String routeId, String id) { + public Mono isAllowed(String routeId, String id) { if (!this.initialized.get()) { throw new IllegalStateException("RedisRateLimiter is not initialized"); } diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/AbstractRateLimiter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/AbstractRateLimiter.java similarity index 98% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/AbstractRateLimiter.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/AbstractRateLimiter.java index 454bcf726b..ca48a979f2 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/AbstractRateLimiter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/AbstractRateLimiter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.ratelimit; +package org.springframework.cloud.gateway.filter.ratelimit; import java.util.Map; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RateLimiter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RateLimiter.java similarity index 96% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RateLimiter.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RateLimiter.java index ea2697e257..a15c1e74d7 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RateLimiter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RateLimiter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.ratelimit; +package org.springframework.cloud.gateway.filter.ratelimit; import java.util.Collections; import java.util.Map; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiter.java similarity index 99% rename from spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiter.java rename to spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiter.java index 955720d819..522f70edc6 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.ratelimit; +package org.springframework.cloud.gateway.filter.ratelimit; import java.time.Instant; import java.util.ArrayList; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/route/builder/GatewayFilterSpec.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/route/builder/GatewayFilterSpec.java index c30f51dec0..3cbca780e5 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/route/builder/GatewayFilterSpec.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/route/builder/GatewayFilterSpec.java @@ -71,8 +71,8 @@ import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction; -import org.springframework.cloud.gateway.filter.redis.quota.QuotaFilter; -import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter; +import org.springframework.cloud.gateway.filter.quota.QuotaFilter; +import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; import org.springframework.cloud.gateway.route.Route; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactoryTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactoryTests.java index b03a6d2ce6..75197ee929 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactoryTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactoryTests.java @@ -31,9 +31,9 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; -import org.springframework.cloud.gateway.filter.redis.KeyResolver; -import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter; -import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter.Response; +import org.springframework.cloud.gateway.filter.KeyResolver; +import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; +import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter.Response; import org.springframework.cloud.gateway.route.Route; import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; import org.springframework.cloud.gateway.test.BaseWebClientTests; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/PrincipalNameKeyResolverIntegrationTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/PrincipalNameKeyResolverIntegrationTests.java similarity index 98% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/PrincipalNameKeyResolverIntegrationTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/PrincipalNameKeyResolverIntegrationTests.java index 572e2a5bfa..aa47a040cd 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/PrincipalNameKeyResolverIntegrationTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/PrincipalNameKeyResolverIntegrationTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.quota; +package org.springframework.cloud.gateway.filter.quota; import java.security.Principal; import java.util.Collections; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterConfigTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterConfigTests.java similarity index 98% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterConfigTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterConfigTests.java index 1cadfc75e5..37b6d2d6eb 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterConfigTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterConfigTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.quota; +package org.springframework.cloud.gateway.filter.quota; import org.junit.Before; import org.junit.Test; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterDefaultFilterConfigTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterDefaultFilterConfigTests.java similarity index 97% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterDefaultFilterConfigTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterDefaultFilterConfigTests.java index 2ec482460b..27a2c3f32e 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterDefaultFilterConfigTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterDefaultFilterConfigTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.quota; +package org.springframework.cloud.gateway.filter.quota; import org.junit.Before; import org.junit.Test; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterTests.java similarity index 97% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterTests.java index 1796690cd7..4df8ab76d2 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/quota/RedisQuotaFilterTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.quota; +package org.springframework.cloud.gateway.filter.quota; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -38,7 +38,7 @@ import static org.hamcrest.Matchers.nullValue; import static org.junit.Assume.assumeThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; -import static org.springframework.cloud.gateway.filter.redis.quota.QuotaFilter.Response; +import static org.springframework.cloud.gateway.filter.quota.QuotaFilter.Response; /** * @author Tobias Schug diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/PrincipalNameKeyResolverIntegrationTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/PrincipalNameKeyResolverIntegrationTests.java similarity index 98% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/PrincipalNameKeyResolverIntegrationTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/PrincipalNameKeyResolverIntegrationTests.java index 9991cea33c..4db24df700 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/PrincipalNameKeyResolverIntegrationTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/PrincipalNameKeyResolverIntegrationTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.ratelimit; +package org.springframework.cloud.gateway.filter.ratelimit; import java.security.Principal; import java.util.Collections; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterConfigTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterConfigTests.java similarity index 98% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterConfigTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterConfigTests.java index 8951f29d53..a76780c539 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterConfigTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterConfigTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.ratelimit; +package org.springframework.cloud.gateway.filter.ratelimit; import org.junit.Before; import org.junit.Test; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java similarity index 97% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java index 3d663b43b8..e1e90a7d0b 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterDefaultFilterConfigTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.ratelimit; +package org.springframework.cloud.gateway.filter.ratelimit; import org.junit.Before; import org.junit.Test; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterTests.java similarity index 96% rename from spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterTests.java rename to spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterTests.java index 46add34c58..425e9a2cba 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/redis/ratelimit/RedisRateLimiterTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiterTests.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.gateway.filter.redis.ratelimit; +package org.springframework.cloud.gateway.filter.ratelimit; import java.util.UUID; @@ -26,7 +26,7 @@ import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.gateway.filter.redis.ratelimit.RateLimiter.Response; +import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter.Response; import org.springframework.cloud.gateway.test.BaseWebClientTests; import org.springframework.cloud.gateway.test.support.redis.RedisRule; import org.springframework.context.annotation.Import; diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/test/AdhocTestSuite.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/test/AdhocTestSuite.java index 0d3daa6088..69df004448 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/test/AdhocTestSuite.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/test/AdhocTestSuite.java @@ -93,9 +93,9 @@ org.springframework.cloud.gateway.filter.headers.NonStandardHeadersInResponseTests.class, org.springframework.cloud.gateway.filter.headers.RemoveHopByHopHeadersFilterTests.class, org.springframework.cloud.gateway.filter.WebsocketRoutingFilterTests.class, - org.springframework.cloud.gateway.filter.redis.ratelimit.PrincipalNameKeyResolverIntegrationTests.class, - org.springframework.cloud.gateway.filter.redis.ratelimit.RedisRateLimiterConfigTests.class, - org.springframework.cloud.gateway.filter.redis.ratelimit.RedisRateLimiterTests.class, + org.springframework.cloud.gateway.filter.ratelimit.PrincipalNameKeyResolverIntegrationTests.class, + org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiterConfigTests.class, + org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiterTests.class, org.springframework.cloud.gateway.filter.LoadBalancerClientFilterTests.class, org.springframework.cloud.gateway.filter.NettyRoutingFilterIntegrationTests.class, GatewayMetricsFilterTests.class, From 2b8aef0d2211eeec4838575f67e683ff2d0af763 Mon Sep 17 00:00:00 2001 From: HappyTobi Date: Tue, 24 Dec 2019 14:35:08 +0100 Subject: [PATCH 5/7] Add quotafilter documentation --- .../main/asciidoc/spring-cloud-gateway.adoc | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/docs/src/main/asciidoc/spring-cloud-gateway.adoc b/docs/src/main/asciidoc/spring-cloud-gateway.adoc index ac3884cbf3..406c3f5ba1 100644 --- a/docs/src/main/asciidoc/spring-cloud-gateway.adoc +++ b/docs/src/main/asciidoc/spring-cloud-gateway.adoc @@ -1016,6 +1016,105 @@ spring: ---- ==== + +---- + +=== RequestQuotaFilter GatewayFilter Factory + +The RequestQuotaFilter GatewayFilter Factory is uses a `QuotaFilter` implementation to determine if the current request is allowed to proceed. +If it is not, a status of `HTTP 429 - Too Many Requests` (by default) is returned. + +This filter takes an optional `keyResolver` parameter and parameters specific to the quota filter (see RequestRateLimiter above). + +By default, if the `KeyResolver` does not find a key, requests will be denied. +This behavior can be adjusted with the `spring.cloud.gateway.filter.request-quota-filter.deny-empty-key` (true or false) and `spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code` properties. + +NOTE: The RequestQuotaFilter is not configurable via the "shortcut" notation. + +==== Redis QuotaFilter + +The redis quota filter requires the use of the `spring-boot-starter-data-redis-reactive` Spring Boot starter. + +The `redis-quota-filter.limit` is how many requests a user is allowed to do, without any dropped requests. + +The `redis-quota-filter.period` is the period how long the limit will exist. +The allowed units are: +`SECONDS, DAYS, HOURS, DAYS or ABS` +The implementation can be found in the `RedisQuotaFilter.QuotaPeriods.class`. +The `ABS` filter period will never expire, so the the limit will be not volatile as the other periods. + +.application.yml +[source,yaml] +---- +spring: + cloud: + gateway: + routes: + - id: request_quota_filter_route + uri: https://example.org + filters: + - name: RequestQuota + args: + redis-quota-filter.limit: 10 + redis-quota-filter.period: DAYS + +---- + +This defines a request quota limit of 10 requests per day. + +You can use a custom `KeyResolver` where you can specify patterns or request parameter matches where the quota filter will look for. + +.Config.java +[source,java] +---- +@Bean +KeyResolver customAuth() { + return exchange -> Mono.just(exchange.getRequest().getHeaders().getFirst("X-Authentication")); +} +---- + +The `KeyResolver` is a simple one that gets the first custom header in the request `X-Authentication`. + +The defined `KeyResolver` can be uses with the quota filter like: +.application.yml + +[source,yaml] +---- +spring: + cloud: + gateway: + routes: + - id: request_quota_filter_route + uri: https://example.org + filters: + - name: RequestQuota + args: + redis-quota-filter.limit: 10 + redis-quota-filter.period: DAYS + key-resolver: customAuth + +---- + +A quota filter can also be defined as a bean implementing the `QuotaFilter` interface. +In configuration, reference the bean by name using SpEL. `#{@myQuotaFilter}` is a SpEL expression referencing a bean with the name `myQuotaFilter`. + +.application.yml +[source,yaml] +---- +spring: + cloud: + gateway: + routes: + - id: requestratelimiter_route + uri: https://example.org + filters: + - name: RequestQuota + args: + quota-filter: "#{@myQuotaFilter}" + key-resolver: "#{@userKeyResolver}" + +---- + === The `RedirectTo` `GatewayFilter` Factory The `RedirectTo` `GatewayFilter` factory takes two parameters, `status` and `url`. From 6fa79ec6f19c7b758e135eb7ad3577b866830ac0 Mon Sep 17 00:00:00 2001 From: HappyTobi Date: Fri, 31 Jan 2020 09:54:50 +0100 Subject: [PATCH 6/7] UPDATE change check and return value for remain token values. --- .../cloud/gateway/filter/quota/RedisQuotaFilter.java | 5 +++-- .../cloud/gateway/filter/quota/RedisQuotaFilterTests.java | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java index 711221d8b7..e95364cc8d 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java @@ -225,8 +225,9 @@ public Mono isAllowed(String routeId, String id) { longs.addAll(l); return longs; }).map(results -> { - Long tokensRemaining = results.get(0); - boolean allowed = tokensRemaining >= 0L; + final Long resultsTokenRemain = results.get(0); + boolean allowed = resultsTokenRemain >= 0L; + Long tokensRemaining = resultsTokenRemain >= 0 ? resultsTokenRemain : 0L; //never return a value lower than 0 QuotaFilter.Response response = new QuotaFilter.Response(allowed, getHeaders(routeConfig, tokensRemaining)); diff --git a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterTests.java b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterTests.java index 4df8ab76d2..8f74c7141d 100644 --- a/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterTests.java +++ b/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilterTests.java @@ -90,6 +90,7 @@ public void redisQuotaFilterWorks() throws Exception { Response response = quotaFilter.isAllowed(routeId, id).block(); assertThat(response.isAllowed()).as("Quota filter has exceeded").isFalse(); + assertThat(response.getHeaders().get(RedisQuotaFilter.REMAINING_HEADER)).isEqualTo(String.valueOf(0)); } @Test From 10a1d91cbcd088b809591d5c1c009158bbe7223a Mon Sep 17 00:00:00 2001 From: HappyTobi Date: Fri, 31 Jan 2020 11:59:36 +0100 Subject: [PATCH 7/7] UPDATE change import for NotNull annotation --- .../cloud/gateway/filter/quota/RedisQuotaFilter.java | 2 +- .../cloud/gateway/filter/ratelimit/RedisRateLimiter.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java index e95364cc8d..f4c3ce0549 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/quota/RedisQuotaFilter.java @@ -27,10 +27,10 @@ import java.util.concurrent.atomic.AtomicBoolean; import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.jetbrains.annotations.NotNull; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiter.java b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiter.java index 522f70edc6..6952ef522d 100644 --- a/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiter.java +++ b/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/ratelimit/RedisRateLimiter.java @@ -25,10 +25,10 @@ import java.util.concurrent.atomic.AtomicBoolean; import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.jetbrains.annotations.NotNull; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;