Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions core/idrepo/rest-cxf/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ under the License.
<artifactId>jakarta.persistence-api</artifactId>
</dependency>

<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>

<dependency>
<groupId>tools.jackson.jakarta.rs</groupId>
<artifactId>jackson-jakarta-rs-json-provider</artifactId>
Expand Down Expand Up @@ -128,6 +133,11 @@ under the License.
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>jcache</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,17 @@

import io.swagger.v3.oas.models.security.SecurityScheme;
import jakarta.validation.Validator;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.TouchedExpiryPolicy;
import org.apache.cxf.Bus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.feature.Feature;
Expand Down Expand Up @@ -227,6 +234,35 @@ public AddETagFilter addETagFilter() {
return new AddETagFilter();
}

@ConditionalOnMissingBean
@Bean
public RateLimitFilter rateLimitFilter(
final RESTProperties props,
@Qualifier(RateLimitFilter.CACHE)
final Cache<String, RateLimitFilter.ClientWindow> cxfRateLimitCache) {

return new RateLimitFilter(props, cxfRateLimitCache);
}

@ConditionalOnMissingBean(name = RateLimitFilter.CACHE)
@Bean(name = RateLimitFilter.CACHE)
public Cache<String, RateLimitFilter.ClientWindow> rateLimitCache(
final CacheManager cacheManager,
final RESTProperties restProperties) {

long windowMillis = Optional.ofNullable(restProperties.getRateLimit().getWindow()).
orElse(Duration.ofMinutes(1)).toMillis();
long lockMillis = Optional.ofNullable(restProperties.getRateLimit().getLock()).
orElse(Duration.ofMinutes(1)).toMillis();
long expiry = Math.max(1L, Math.max(windowMillis, lockMillis));

return cacheManager.createCache(RateLimitFilter.CACHE,
new MutableConfiguration<String, RateLimitFilter.ClientWindow>().
setTypes(String.class, RateLimitFilter.ClientWindow.class).
setExpiryPolicyFactory(TouchedExpiryPolicy.factoryOf(
new javax.cache.expiry.Duration(TimeUnit.MILLISECONDS, expiry))));
}

@ConditionalOnMissingBean(name = { "openApiCustomizer", "syncopeOpenApiCustomizer" })
@Bean
public OpenApiCustomizer openApiCustomizer(final DomainHolder<?> domainHolder, final Environment env) {
Expand Down Expand Up @@ -278,6 +314,7 @@ public Server restContainer(
final List<JAXRSService> services,
final AddETagFilter addETagFilter,
final AddDomainFilter addDomainFilter,
final RateLimitFilter rateLimitFilter,
final ContextProvider<SearchContext> searchContextProvider,
final JacksonJsonProvider jsonProvider,
final DateParamConverterProvider dateParamConverterProvider,
Expand Down Expand Up @@ -308,6 +345,7 @@ public Server restContainer(
jsonProvider,
restServiceExceptionMapper,
searchContextProvider,
rateLimitFilter,
addDomainFilter,
addETagFilter));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,92 @@
*/
package org.apache.syncope.core.rest.cxf;

import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
import org.apache.syncope.core.provisioning.java.ExecutorProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;

@ConfigurationProperties("rest")
public class RESTProperties {

public static class RateLimitProperties {

private boolean enabled;

private int maxRequests = 300;

private Duration window = Duration.ofMinutes(1);

private Duration lock = Duration.ofMinutes(1);

private String forwardedForHeader = "X-Forwarded-For";

private final Set<String> excludedAddresses = new HashSet<>();

private final Set<String> trustedProxies = new HashSet<>();

public boolean isEnabled() {
return enabled;
}

public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}

public int getMaxRequests() {
return maxRequests;
}

public void setMaxRequests(final int maxRequests) {
this.maxRequests = maxRequests;
}

public Duration getWindow() {
return window;
}

public void setWindow(final Duration window) {
this.window = window;
}

public Duration getLock() {
return lock;
}

public void setLock(final Duration lock) {
this.lock = lock;
}

public String getForwardedForHeader() {
return forwardedForHeader;
}

public void setForwardedForHeader(final String forwardedForHeader) {
this.forwardedForHeader = forwardedForHeader;
}

public Set<String> getExcludedAddresses() {
Comment thread
ilgrosso marked this conversation as resolved.
Dismissed
return excludedAddresses;
}

public Set<String> getTrustedProxies() {
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Comment thread
ilgrosso marked this conversation as resolved.
Dismissed
return trustedProxies;
}
}

@NestedConfigurationProperty
private final ExecutorProperties batchExecutor = new ExecutorProperties();

@NestedConfigurationProperty
private final RateLimitProperties rateLimitProperties = new RateLimitProperties();

public ExecutorProperties getBatchExecutor() {
return batchExecutor;
}

public RateLimitProperties getRateLimit() {
return rateLimitProperties;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.core.rest.cxf;

import jakarta.annotation.Priority;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;
import java.io.Serializable;
import java.time.Duration;
import java.util.Arrays;
import java.util.Optional;
import javax.cache.Cache;
import org.apache.commons.lang3.StringUtils;

@Provider
@PreMatching
@Priority(Priorities.AUTHENTICATION - 100)
public class RateLimitFilter implements ContainerRequestFilter {

public static final String CACHE = "RateLimitFilterCache";

protected record RateLimitDecision(boolean allowed, long retryAfterSeconds) {

}

public record ClientWindow(long windowStartMillis, int count, long lockedUntilMillis) implements Serializable {

private static final long serialVersionUID = -473897805205955157L;

}

protected final RESTProperties.RateLimitProperties props;

protected final Cache<String, ClientWindow> clients;

@Context
protected HttpServletRequest request;

public RateLimitFilter(final RESTProperties props, final Cache<String, ClientWindow> clients) {
this.props = props.getRateLimit();
this.clients = clients;
}

@Override
public void filter(final ContainerRequestContext requestContext) {
if (!props.isEnabled() || props.getMaxRequests() <= 0) {
return;
}

if (isExcluded()) {
return;
}

String key = clientAddress();
RateLimitDecision decision = allow(key, System.currentTimeMillis());
if (!decision.allowed()) {
requestContext.abortWith(Response.status(429).
header(HttpHeaders.RETRY_AFTER, decision.retryAfterSeconds()).
build());
}
}

protected RateLimitDecision allow(final String key, final long now) {
return clients.invoke(key, (entry, args) -> {
ClientWindow client = entry.exists()
? entry.getValue()
: new ClientWindow(now, 0, 0);

if (now < client.lockedUntilMillis()) {
return new RateLimitDecision(false, retryAfterSeconds(client.lockedUntilMillis() - now));
}

long windowStartMillis = client.windowStartMillis();
int count = client.count();
if (now - windowStartMillis >= toMillis(props.getWindow())) {
windowStartMillis = now;
count = 0;
}

count++;
if (count > props.getMaxRequests()) {
entry.setValue(new ClientWindow(windowStartMillis, count, now + toMillis(props.getLock())));
return new RateLimitDecision(false, retryAfterSeconds(toMillis(props.getLock())));
}

entry.setValue(new ClientWindow(windowStartMillis, count, client.lockedUntilMillis()));
return new RateLimitDecision(true, 0);
});
}

protected String clientAddress() {
String remoteAddress = remoteAddress();

if (props.getTrustedProxies().contains(remoteAddress)) {
String forwardedFor = Optional.ofNullable(request).
map(req -> req.getHeader(props.getForwardedForHeader())).
flatMap(RateLimitFilter::firstForwardedFor).
orElse(null);
if (StringUtils.isNotBlank(forwardedFor)) {
return forwardedFor;
}
}

return remoteAddress;
}

protected boolean isExcluded() {
return props.getExcludedAddresses().contains(remoteAddress());
}

protected String remoteAddress() {
return requestRemoteAddress().
filter(StringUtils::isNotBlank).
orElse("unknown");
}

protected Optional<String> requestRemoteAddress() {
return Optional.ofNullable(request).map(HttpServletRequest::getRemoteAddr);
}

protected static Optional<String> firstForwardedFor(final String header) {
return Arrays.stream(StringUtils.split(header, ',')).
map(String::trim).
filter(StringUtils::isNotBlank).
findFirst();
}

protected static long toMillis(final Duration duration) {
return Math.max(1L, Optional.ofNullable(duration).orElse(Duration.ofMinutes(1)).toMillis());
}

protected static long retryAfterSeconds(final long millis) {
return Math.max(1L, (long) Math.ceil(millis / 1000.0d));
}
}
Loading
Loading