-
Notifications
You must be signed in to change notification settings - Fork 206
[SYNCOPE-1976] Add configurable REST rate limiting #1420
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
0a587fb
[SYNCOPE-1976] Add configurable REST rate limiting
massx1 91cc84d
[SYNCOPE-1976] Move REST rate limit cache setup to Spring context
massx1 cad8332
[SYNCOPE-1976] Adjust REST rate limit test imports
massx1 8459463
Merge branch 'master' into pull-1420
ilgrosso 30d6598
Cleanup
ilgrosso a6d4295
Fixing imports
ilgrosso 89603e1
[SYNCOPE-1976] Document REST rate limit address configuration
massx1 b28a6cc
Merge branch 'security-rate-limiting-cxf' of github.com:massx1/syncop…
ilgrosso b696c01
Reflow
ilgrosso File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
158 changes: 158 additions & 0 deletions
158
core/idrepo/rest-cxf/src/main/java/org/apache/syncope/core/rest/cxf/RateLimitFilter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.