[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-05-03 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1184526447


##
java/org/apache/catalina/util/TimeBucketCounter.java:
##
@@ -0,0 +1,217 @@
+/*
+ * 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.catalina.util;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * this class maintains a thread safe hash map that has timestamp-based buckets
+ * followed by a string for a key, and a counter for a value. each time the
+ * increment() method is called it adds the key if it does not exist, 
increments
+ * its value and returns it.
+ *
+ * a maintenance thread cleans up keys that are prefixed by previous timestamp
+ * buckets.
+ */
+public class TimeBucketCounter {
+
+/**
+ * Map to hold the buckets
+ */
+private final ConcurrentHashMap map = new 
ConcurrentHashMap<>();
+
+/**
+ * Milliseconds bucket size as a Power of 2 for bit shift math, e.g.
+ * 16 for 65_536ms which is about 1:05 minute
+ */
+private final int numBits;
+
+/**
+ * ratio of actual duration to config duration
+ */
+private final double ratio;
+
+/**
+ * flag for the maintenance thread
+ */
+volatile boolean isRunning = false;
+
+/**
+ *
+ * @param bucketDuration duration in seconds, e.g. for 1 minute pass 60
+ */
+public TimeBucketCounter(int bucketDuration) {
+
+int durationMillis = bucketDuration * 1000;
+
+int bits = 0;
+int pof2 = nextPowerOf2(durationMillis);
+int bitCheck = pof2;
+while (bitCheck > 1) {
+bitCheck = pof2 >> ++bits;
+}
+
+this.numBits = bits;
+
+this.ratio = ratioToPowerOf2(durationMillis);
+
+int cleanupsPerBucketDuration = (durationMillis >= 60_000) ? 6 : 3;
+Thread mt = new MaintenanceThread(durationMillis / 
cleanupsPerBucketDuration);
+mt.start();
+}
+
+/**
+ * increments the counter for the passed identifier in the current time
+ * bucket and returns the new value
+ *
+ * @param identifier an identifier for which we want to maintain count, 
e.g. IP Address
+ * @return the count within the current time bucket
+ */
+public final int increment(String identifier) {
+String key = getCurrentBucketPrefix() + "-" + identifier;
+AtomicInteger ai = map.computeIfAbsent(key, v -> new AtomicInteger());
+return ai.incrementAndGet();

Review Comment:
   To exceed Integer.MAX_VALUE (2,147,483,647) in a day, for example, one would 
need to hit the server at the rate of almost 25,000 Requests per Second.  
Handling configurations that would allow 25,000 Requests per Second in a time 
window of a full day is not a use case for this filter, and such configuration 
should be strongly discouraged.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


-
To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org
For additional commands, e-mail: dev-h...@tomcat.apache.org



[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-05-03 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1184526447


##
java/org/apache/catalina/util/TimeBucketCounter.java:
##
@@ -0,0 +1,217 @@
+/*
+ * 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.catalina.util;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * this class maintains a thread safe hash map that has timestamp-based buckets
+ * followed by a string for a key, and a counter for a value. each time the
+ * increment() method is called it adds the key if it does not exist, 
increments
+ * its value and returns it.
+ *
+ * a maintenance thread cleans up keys that are prefixed by previous timestamp
+ * buckets.
+ */
+public class TimeBucketCounter {
+
+/**
+ * Map to hold the buckets
+ */
+private final ConcurrentHashMap map = new 
ConcurrentHashMap<>();
+
+/**
+ * Milliseconds bucket size as a Power of 2 for bit shift math, e.g.
+ * 16 for 65_536ms which is about 1:05 minute
+ */
+private final int numBits;
+
+/**
+ * ratio of actual duration to config duration
+ */
+private final double ratio;
+
+/**
+ * flag for the maintenance thread
+ */
+volatile boolean isRunning = false;
+
+/**
+ *
+ * @param bucketDuration duration in seconds, e.g. for 1 minute pass 60
+ */
+public TimeBucketCounter(int bucketDuration) {
+
+int durationMillis = bucketDuration * 1000;
+
+int bits = 0;
+int pof2 = nextPowerOf2(durationMillis);
+int bitCheck = pof2;
+while (bitCheck > 1) {
+bitCheck = pof2 >> ++bits;
+}
+
+this.numBits = bits;
+
+this.ratio = ratioToPowerOf2(durationMillis);
+
+int cleanupsPerBucketDuration = (durationMillis >= 60_000) ? 6 : 3;
+Thread mt = new MaintenanceThread(durationMillis / 
cleanupsPerBucketDuration);
+mt.start();
+}
+
+/**
+ * increments the counter for the passed identifier in the current time
+ * bucket and returns the new value
+ *
+ * @param identifier an identifier for which we want to maintain count, 
e.g. IP Address
+ * @return the count within the current time bucket
+ */
+public final int increment(String identifier) {
+String key = getCurrentBucketPrefix() + "-" + identifier;
+AtomicInteger ai = map.computeIfAbsent(key, v -> new AtomicInteger());
+return ai.incrementAndGet();

Review Comment:
   To exceed Integer.MAX_VALUE (2,147,483,647) in a day, for example, one would 
need to hit the server at the rate of almost 25,000 Requests per Second.  
Handling cases like that are not a use case for this filter.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


-
To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org
For additional commands, e-mail: dev-h...@tomcat.apache.org



[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-04-09 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1161309823


##
java/org/apache/catalina/util/TimeBucketCounter.java:
##
@@ -0,0 +1,217 @@
+/*
+ * 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.catalina.util;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * this class maintains a thread safe hash map that has timestamp-based buckets
+ * followed by a string for a key, and a counter for a value. each time the
+ * increment() method is called it adds the key if it does not exist, 
increments
+ * its value and returns it.
+ *
+ * a maintenance thread cleans up keys that are prefixed by previous timestamp
+ * buckets.
+ */
+public class TimeBucketCounter {
+
+/**
+ * Map to hold the buckets
+ */
+private final ConcurrentHashMap map = new 
ConcurrentHashMap<>();
+
+/**
+ * Milliseconds bucket size as a Power of 2 for bit shift math, e.g.
+ * 16 for 65_536ms which is about 1:05 minute
+ */
+private final int numBits;
+
+/**
+ * ratio of actual duration to config duration
+ */
+private final double ratio;
+
+/**
+ * flag for the maintenance thread
+ */
+volatile boolean isRunning = false;
+
+/**
+ *
+ * @param bucketDuration duration in seconds, e.g. for 1 minute pass 60
+ */
+public TimeBucketCounter(int bucketDuration) {
+
+int durationMillis = bucketDuration * 1000;
+
+int bits = 0;
+int pof2 = nextPowerOf2(durationMillis);
+int bitCheck = pof2;
+while (bitCheck > 1) {
+bitCheck = pof2 >> ++bits;
+}
+
+this.numBits = bits;
+
+this.ratio = ratioToPowerOf2(durationMillis);
+
+int cleanupsPerBucketDuration = (durationMillis >= 60_000) ? 6 : 3;
+Thread mt = new MaintenanceThread(durationMillis / 
cleanupsPerBucketDuration);
+mt.start();
+}
+
+/**
+ * increments the counter for the passed identifier in the current time
+ * bucket and returns the new value
+ *
+ * @param identifier an identifier for which we want to maintain count, 
e.g. IP Address
+ * @return the count within the current time bucket
+ */
+public final int increment(String identifier) {
+String key = getCurrentBucketPrefix() + "-" + identifier;
+AtomicInteger ai = map.computeIfAbsent(key, v -> new AtomicInteger());
+return ai.incrementAndGet();

Review Comment:
   @rmannibucau But you still didn't explain how that would be better than the 
current code and didn't post any references.  We should always push better code 
when possible, but can you explain what problem that change would solve and 
how?  Thank you.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


-
To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org
For additional commands, e-mail: dev-h...@tomcat.apache.org



[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-03-31 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1154883838


##
java/org/apache/catalina/util/TimeBucketCounter.java:
##
@@ -0,0 +1,217 @@
+/*
+ * 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.catalina.util;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * this class maintains a thread safe hash map that has timestamp-based buckets
+ * followed by a string for a key, and a counter for a value. each time the
+ * increment() method is called it adds the key if it does not exist, 
increments
+ * its value and returns it.
+ *
+ * a maintenance thread cleans up keys that are prefixed by previous timestamp
+ * buckets.
+ */
+public class TimeBucketCounter {
+
+/**
+ * Map to hold the buckets
+ */
+private final ConcurrentHashMap map = new 
ConcurrentHashMap<>();
+
+/**
+ * Milliseconds bucket size as a Power of 2 for bit shift math, e.g.
+ * 16 for 65_536ms which is about 1:05 minute
+ */
+private final int numBits;
+
+/**
+ * ratio of actual duration to config duration
+ */
+private final double ratio;
+
+/**
+ * flag for the maintenance thread
+ */
+volatile boolean isRunning = false;
+
+/**
+ *
+ * @param bucketDuration duration in seconds, e.g. for 1 minute pass 60
+ */
+public TimeBucketCounter(int bucketDuration) {
+
+int durationMillis = bucketDuration * 1000;
+
+int bits = 0;
+int pof2 = nextPowerOf2(durationMillis);
+int bitCheck = pof2;
+while (bitCheck > 1) {
+bitCheck = pof2 >> ++bits;
+}
+
+this.numBits = bits;
+
+this.ratio = ratioToPowerOf2(durationMillis);
+
+int cleanupsPerBucketDuration = (durationMillis >= 60_000) ? 6 : 3;
+Thread mt = new MaintenanceThread(durationMillis / 
cleanupsPerBucketDuration);
+mt.start();
+}
+
+/**
+ * increments the counter for the passed identifier in the current time
+ * bucket and returns the new value
+ *
+ * @param identifier an identifier for which we want to maintain count, 
e.g. IP Address
+ * @return the count within the current time bucket
+ */
+public final int increment(String identifier) {
+String key = getCurrentBucketPrefix() + "-" + identifier;
+AtomicInteger ai = map.computeIfAbsent(key, v -> new AtomicInteger());
+return ai.incrementAndGet();

Review Comment:
   @rmannibucau Perhaps I'm missing something.  Can you please explain how 
`updateAndGet()` is better than `incrementAndGet()`?  
   
   Looking at the implementation of both they look very similar other than the 
fact that `updateAndGet()` would have to call `updateFunction.applyAsInt()` 
which would add unnecessary overhead.  Both implementations call 
`weakCompareAndSetInt()`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


-
To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org
For additional commands, e-mail: dev-h...@tomcat.apache.org



[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-03-31 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1154792436


##
java/org/apache/catalina/util/TimeBucketCounter.java:
##
@@ -0,0 +1,217 @@
+/*
+ * 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.catalina.util;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * this class maintains a thread safe hash map that has timestamp-based buckets
+ * followed by a string for a key, and a counter for a value. each time the
+ * increment() method is called it adds the key if it does not exist, 
increments
+ * its value and returns it.
+ *
+ * a maintenance thread cleans up keys that are prefixed by previous timestamp
+ * buckets.
+ */
+public class TimeBucketCounter {
+
+/**
+ * Map to hold the buckets
+ */
+private final ConcurrentHashMap map = new 
ConcurrentHashMap<>();
+
+/**
+ * Milliseconds bucket size as a Power of 2 for bit shift math, e.g.
+ * 16 for 65_536ms which is about 1:05 minute
+ */
+private final int numBits;
+
+/**
+ * ratio of actual duration to config duration
+ */
+private final double ratio;
+
+/**
+ * flag for the maintenance thread
+ */
+volatile boolean isRunning = false;
+
+/**
+ *
+ * @param bucketDuration duration in seconds, e.g. for 1 minute pass 60
+ */
+public TimeBucketCounter(int bucketDuration) {
+
+int durationMillis = bucketDuration * 1000;
+
+int bits = 0;
+int pof2 = nextPowerOf2(durationMillis);
+int bitCheck = pof2;
+while (bitCheck > 1) {
+bitCheck = pof2 >> ++bits;
+}
+
+this.numBits = bits;
+
+this.ratio = ratioToPowerOf2(durationMillis);
+
+int cleanupsPerBucketDuration = (durationMillis >= 60_000) ? 6 : 3;
+Thread mt = new MaintenanceThread(durationMillis / 
cleanupsPerBucketDuration);
+mt.start();
+}
+
+/**
+ * increments the counter for the passed identifier in the current time
+ * bucket and returns the new value
+ *
+ * @param identifier an identifier for which we want to maintain count, 
e.g. IP Address
+ * @return the count within the current time bucket
+ */
+public final int increment(String identifier) {
+String key = getCurrentBucketPrefix() + "-" + identifier;
+AtomicInteger ai = map.computeIfAbsent(key, v -> new AtomicInteger());
+return ai.incrementAndGet();

Review Comment:
   One idea that I had was to allow to configure certain paths with a different 
"weight", rather than configure a different Filter for different path, e.g. 
while requests to the homepage are counted as 1, a request for a login page 
might count as 10.
   
   That way, you can configure the Filter for 300 requests per minute, for 
example, which will allow for 300 requests to most of the site, but only 30 
requests to the login page, mitigating brute force attacks that try to guess a 
password.
   
   If we do that then `updateAndGet()` might be more applicable, but again, I 
want to introduce this filter and get some feedback before adding more features 
to it.
   
   Also, we have another thread on the PR about back porting this feature, and 
if we decide to go all the way back to Tomcat 8.5 then this would be another 
one of the things that needs to be rewritten to run on Java 7.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


-
To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org
For additional commands, e-mail: dev-h...@tomcat.apache.org



[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-03-31 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1154785188


##
java/org/apache/catalina/util/TimeBucketCounter.java:
##
@@ -0,0 +1,217 @@
+/*
+ * 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.catalina.util;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * this class maintains a thread safe hash map that has timestamp-based buckets
+ * followed by a string for a key, and a counter for a value. each time the
+ * increment() method is called it adds the key if it does not exist, 
increments
+ * its value and returns it.
+ *
+ * a maintenance thread cleans up keys that are prefixed by previous timestamp
+ * buckets.
+ */
+public class TimeBucketCounter {
+
+/**
+ * Map to hold the buckets
+ */
+private final ConcurrentHashMap map = new 
ConcurrentHashMap<>();
+
+/**
+ * Milliseconds bucket size as a Power of 2 for bit shift math, e.g.
+ * 16 for 65_536ms which is about 1:05 minute
+ */
+private final int numBits;
+
+/**
+ * ratio of actual duration to config duration
+ */
+private final double ratio;
+
+/**
+ * flag for the maintenance thread
+ */
+volatile boolean isRunning = false;
+
+/**
+ *
+ * @param bucketDuration duration in seconds, e.g. for 1 minute pass 60
+ */
+public TimeBucketCounter(int bucketDuration) {
+
+int durationMillis = bucketDuration * 1000;
+
+int bits = 0;
+int pof2 = nextPowerOf2(durationMillis);
+int bitCheck = pof2;
+while (bitCheck > 1) {
+bitCheck = pof2 >> ++bits;
+}
+
+this.numBits = bits;
+
+this.ratio = ratioToPowerOf2(durationMillis);
+
+int cleanupsPerBucketDuration = (durationMillis >= 60_000) ? 6 : 3;
+Thread mt = new MaintenanceThread(durationMillis / 
cleanupsPerBucketDuration);

Review Comment:
   I will look into that, thanks!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


-
To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org
For additional commands, e-mail: dev-h...@tomcat.apache.org



[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-03-31 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1154784584


##
java/org/apache/catalina/util/TimeBucketCounter.java:
##
@@ -0,0 +1,217 @@
+/*
+ * 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.catalina.util;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * this class maintains a thread safe hash map that has timestamp-based buckets
+ * followed by a string for a key, and a counter for a value. each time the
+ * increment() method is called it adds the key if it does not exist, 
increments
+ * its value and returns it.
+ *
+ * a maintenance thread cleans up keys that are prefixed by previous timestamp
+ * buckets.
+ */
+public class TimeBucketCounter {

Review Comment:
   I also considered that one and that's the reason I added it to the utils 
package instead of an inner class of the RateLimitFilter, but I think that it 
would make more sense to extract an interface once we have a good idea for 
other implementations.
   
   The problem with APIs is that once they are published it's very hard to 
change or get rid of them, so I think that after some time in the wild we will 
have a better idea of what it can or should be.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


-
To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org
For additional commands, e-mail: dev-h...@tomcat.apache.org



[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-03-31 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1154782761


##
java/org/apache/catalina/filters/RateLimitFilter.java:
##
@@ -0,0 +1,230 @@
+/*
+ * 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.catalina.filters;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.FilterConfig;
+import jakarta.servlet.GenericFilter;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletResponse;
+import org.apache.catalina.util.TimeBucketCounter;
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.res.StringManager;
+
+import java.io.IOException;
+
+public class RateLimitFilter extends GenericFilter {
+
+/**
+ * default duration in seconds
+ */
+public static final int DEFAULT_BUCKET_DURATION = 60;
+
+/**
+ * default number of requests per duration
+ */
+public static final int DEFAULT_BUCKET_REQUESTS = 300;
+
+/**
+ * default value for enforce
+ */
+public static final boolean DEFAULT_ENFORCE = true;
+
+/**
+ * default status code to return if requests per duration exceeded
+ */
+public static final int DEFAULT_STATUS_CODE = 429;
+
+/**
+ * default status message to return if requests per duration exceeded
+ */
+public static final String DEFAULT_STATUS_MESSAGE = "Too many requests";
+
+/**
+ * request attribute that will contain the number of requests per duration
+ */
+public static final String RATE_LIMIT_ATTRIBUTE_COUNT = 
"org.apache.catalina.filters.RateLimitFilter.Count";
+
+/**
+ * filter init-param to set the bucket duration in seconds
+ */
+public static final String PARAM_BUCKET_DURATION = 
"ratelimit.bucket.duration";
+
+/**
+ * filter init-param to set the bucket number of requests
+ */
+public static final String PARAM_BUCKET_REQUESTS = 
"ratelimit.bucket.requests";
+
+/**
+ * filter init-param to set the enforce flag
+ */
+public static final String PARAM_ENFORCE = "ratelimit.enforce";
+
+/**
+ * filter init-param to set a custom status code if requests per duration 
exceeded
+ */
+public static final String PARAM_STATUS_CODE = "ratelimit.status.code";
+
+/**
+ * filter init-param to set a custom status message if requests per 
duration exceeded
+ */
+public static final String PARAM_STATUS_MESSAGE = 
"ratelimit.status.message";
+
+TimeBucketCounter bucketCounter;
+
+private int actualRequests;
+
+private int bucketRequests = DEFAULT_BUCKET_REQUESTS;
+
+private int bucketDuration = DEFAULT_BUCKET_DURATION;
+
+private boolean enforce = DEFAULT_ENFORCE;
+private int statusCode = DEFAULT_STATUS_CODE;
+
+private String statusMessage = DEFAULT_STATUS_MESSAGE;
+
+private transient Log log = LogFactory.getLog(RateLimitFilter.class);
+
+private static final StringManager sm = 
StringManager.getManager(RateLimitFilter.class);
+
+/**
+ * @return the actual maximum allowed requests per time bucket
+ */
+public int getActualRequests() {
+return actualRequests;
+}
+
+/**
+ * @return the actual duration of a time bucket in milliseconds
+ */
+public int getActualDurationInSeconds() {
+return bucketCounter.getActualDuration() / 1000;
+}
+
+@Override
+public void init() throws ServletException {
+
+FilterConfig config = getFilterConfig();
+
+String param;
+param = config.getInitParameter(PARAM_BUCKET_DURATION);
+if (param != null)
+bucketDuration = Integer.parseInt(param);
+
+param = config.getInitParameter(PARAM_BUCKET_REQUESTS);
+if (param != null)
+bucketRequests = Integer.parseInt(param);
+
+param = config.getInitParameter(PARAM_ENFORCE);
+if (param != null)
+enforce = Boolean.parseBoolean(param);
+
+param = config.getInitParameter(PARAM_STATUS_CODE);
+if (param != null)
+statusCode = Integer.parseInt(param);
+

[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-03-31 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1154702239


##
java/org/apache/catalina/filters/RateLimitFilter.java:
##
@@ -0,0 +1,230 @@
+/*
+ * 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.catalina.filters;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.FilterConfig;
+import jakarta.servlet.GenericFilter;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletResponse;
+import org.apache.catalina.util.TimeBucketCounter;
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.res.StringManager;
+
+import java.io.IOException;
+
+public class RateLimitFilter extends GenericFilter {
+
+/**
+ * default duration in seconds
+ */
+public static final int DEFAULT_BUCKET_DURATION = 60;
+
+/**
+ * default number of requests per duration
+ */
+public static final int DEFAULT_BUCKET_REQUESTS = 300;
+
+/**
+ * default value for enforce
+ */
+public static final boolean DEFAULT_ENFORCE = true;
+
+/**
+ * default status code to return if requests per duration exceeded
+ */
+public static final int DEFAULT_STATUS_CODE = 429;
+
+/**
+ * default status message to return if requests per duration exceeded
+ */
+public static final String DEFAULT_STATUS_MESSAGE = "Too many requests";
+
+/**
+ * request attribute that will contain the number of requests per duration
+ */
+public static final String RATE_LIMIT_ATTRIBUTE_COUNT = 
"org.apache.catalina.filters.RateLimitFilter.Count";
+
+/**
+ * filter init-param to set the bucket duration in seconds
+ */
+public static final String PARAM_BUCKET_DURATION = 
"ratelimit.bucket.duration";
+
+/**
+ * filter init-param to set the bucket number of requests
+ */
+public static final String PARAM_BUCKET_REQUESTS = 
"ratelimit.bucket.requests";
+
+/**
+ * filter init-param to set the enforce flag
+ */
+public static final String PARAM_ENFORCE = "ratelimit.enforce";
+
+/**
+ * filter init-param to set a custom status code if requests per duration 
exceeded
+ */
+public static final String PARAM_STATUS_CODE = "ratelimit.status.code";
+
+/**
+ * filter init-param to set a custom status message if requests per 
duration exceeded
+ */
+public static final String PARAM_STATUS_MESSAGE = 
"ratelimit.status.message";
+
+TimeBucketCounter bucketCounter;
+
+private int actualRequests;
+
+private int bucketRequests = DEFAULT_BUCKET_REQUESTS;
+
+private int bucketDuration = DEFAULT_BUCKET_DURATION;
+
+private boolean enforce = DEFAULT_ENFORCE;
+private int statusCode = DEFAULT_STATUS_CODE;
+
+private String statusMessage = DEFAULT_STATUS_MESSAGE;
+
+private transient Log log = LogFactory.getLog(RateLimitFilter.class);
+
+private static final StringManager sm = 
StringManager.getManager(RateLimitFilter.class);
+
+/**
+ * @return the actual maximum allowed requests per time bucket
+ */
+public int getActualRequests() {
+return actualRequests;
+}
+
+/**
+ * @return the actual duration of a time bucket in milliseconds
+ */
+public int getActualDurationInSeconds() {
+return bucketCounter.getActualDuration() / 1000;
+}
+
+@Override
+public void init() throws ServletException {
+
+FilterConfig config = getFilterConfig();
+
+String param;
+param = config.getInitParameter(PARAM_BUCKET_DURATION);
+if (param != null)
+bucketDuration = Integer.parseInt(param);
+
+param = config.getInitParameter(PARAM_BUCKET_REQUESTS);
+if (param != null)
+bucketRequests = Integer.parseInt(param);
+
+param = config.getInitParameter(PARAM_ENFORCE);
+if (param != null)
+enforce = Boolean.parseBoolean(param);
+
+param = config.getInitParameter(PARAM_STATUS_CODE);
+if (param != null)
+statusCode = Integer.parseInt(param);
+

[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-03-31 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1154701109


##
java/org/apache/catalina/util/TimeBucketCounter.java:
##
@@ -0,0 +1,217 @@
+/*
+ * 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.catalina.util;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * this class maintains a thread safe hash map that has timestamp-based buckets
+ * followed by a string for a key, and a counter for a value. each time the
+ * increment() method is called it adds the key if it does not exist, 
increments
+ * its value and returns it.
+ *
+ * a maintenance thread cleans up keys that are prefixed by previous timestamp
+ * buckets.
+ */
+public class TimeBucketCounter {
+
+/**
+ * Map to hold the buckets
+ */
+private final ConcurrentHashMap map = new 
ConcurrentHashMap<>();
+
+/**
+ * Milliseconds bucket size as a Power of 2 for bit shift math, e.g.
+ * 16 for 65_536ms which is about 1:05 minute
+ */
+private final int numBits;
+
+/**
+ * ratio of actual duration to config duration
+ */
+private final double ratio;
+
+/**
+ * flag for the maintenance thread
+ */
+volatile boolean isRunning = false;
+
+/**
+ *
+ * @param bucketDuration duration in seconds, e.g. for 1 minute pass 60
+ */
+public TimeBucketCounter(int bucketDuration) {
+
+int durationMillis = bucketDuration * 1000;
+
+int bits = 0;
+int pof2 = nextPowerOf2(durationMillis);
+int bitCheck = pof2;
+while (bitCheck > 1) {
+bitCheck = pof2 >> ++bits;
+}
+
+this.numBits = bits;
+
+this.ratio = ratioToPowerOf2(durationMillis);
+
+int cleanupsPerBucketDuration = (durationMillis >= 60_000) ? 6 : 3;
+Thread mt = new MaintenanceThread(durationMillis / 
cleanupsPerBucketDuration);
+mt.start();
+}
+
+/**
+ * increments the counter for the passed identifier in the current time
+ * bucket and returns the new value
+ *
+ * @param identifier an identifier for which we want to maintain count, 
e.g. IP Address
+ * @return the count within the current time bucket
+ */
+public final int increment(String identifier) {
+String key = getCurrentBucketPrefix() + "-" + identifier;
+AtomicInteger ai = map.computeIfAbsent(key, v -> new AtomicInteger());
+return ai.incrementAndGet();
+}
+
+/**
+ * calculates the current time bucket prefix by shifting bits for fast
+ * division, e.g. shift 16 bits is the same as dividing by 65,536 which is
+ * about 1:05m
+ */
+public final int getCurrentBucketPrefix() {
+return (int) (System.currentTimeMillis() >> this.numBits);
+}
+
+/**
+ *
+ * @return
+ */
+public int getNumBits() {
+return numBits;
+}
+
+/**
+ * the actual duration may differ from the configured duration because
+ * it is set to the next power of 2 value in order to perform very fast
+ * bit shift arithmetic
+ *
+ * @return the actual bucket duration in milliseconds
+ */
+public int getActualDuration() {
+return (int) Math.pow(2, getNumBits());
+}
+
+/**
+ * returns the ratio between the configured duration param and the
+ * actual duration which will be set to the next power of 2.  we then
+ * multiply the configured requests param by the same ratio in order
+ * to compensate for the added time, if any
+ *
+ * @return the ratio, e.g. 1.092 if the actual duration is 65_536 for
+ * the configured duration of 60_000
+ */
+public double getRatio() {
+return ratio;
+}
+
+/**
+ * returns the ratio to the next power of 2 so that we can adjust the value
+ *
+ * @param value
+ * @return
+ */
+static double ratioToPowerOf2(int value) {
+double nextPO2 = nextPowerOf2(value);
+return Math.round((1000 * nextPO2 / value)) / 1000d;
+}
+
+/**
+ * returns the next power of 2 given a value, e.g. 256 for 250,
+ * or 1024, for 

[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-03-30 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1153771643


##
java/org/apache/catalina/util/TimeBucketCounter.java:
##
@@ -0,0 +1,217 @@
+/*
+ * 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.catalina.util;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * this class maintains a thread safe hash map that has timestamp-based buckets
+ * followed by a string for a key, and a counter for a value. each time the
+ * increment() method is called it adds the key if it does not exist, 
increments
+ * its value and returns it.
+ *
+ * a maintenance thread cleans up keys that are prefixed by previous timestamp
+ * buckets.
+ */
+public class TimeBucketCounter {
+
+/**
+ * Map to hold the buckets
+ */
+private final ConcurrentHashMap map = new 
ConcurrentHashMap<>();
+
+/**
+ * Milliseconds bucket size as a Power of 2 for bit shift math, e.g.
+ * 16 for 65_536ms which is about 1:05 minute
+ */
+private final int numBits;
+
+/**
+ * ratio of actual duration to config duration
+ */
+private final double ratio;
+
+/**
+ * flag for the maintenance thread
+ */
+volatile boolean isRunning = false;
+
+/**
+ *
+ * @param bucketDuration duration in seconds, e.g. for 1 minute pass 60
+ */
+public TimeBucketCounter(int bucketDuration) {
+
+int durationMillis = bucketDuration * 1000;
+
+int bits = 0;
+int pof2 = nextPowerOf2(durationMillis);
+int bitCheck = pof2;
+while (bitCheck > 1) {
+bitCheck = pof2 >> ++bits;
+}
+
+this.numBits = bits;
+
+this.ratio = ratioToPowerOf2(durationMillis);
+
+int cleanupsPerBucketDuration = (durationMillis >= 60_000) ? 6 : 3;
+Thread mt = new MaintenanceThread(durationMillis / 
cleanupsPerBucketDuration);
+mt.start();
+}
+
+/**
+ * increments the counter for the passed identifier in the current time
+ * bucket and returns the new value
+ *
+ * @param identifier an identifier for which we want to maintain count, 
e.g. IP Address
+ * @return the count within the current time bucket
+ */
+public final int increment(String identifier) {
+String key = getCurrentBucketPrefix() + "-" + identifier;
+AtomicInteger ai = map.computeIfAbsent(key, v -> new AtomicInteger());
+return ai.incrementAndGet();
+}
+
+/**
+ * calculates the current time bucket prefix by shifting bits for fast
+ * division, e.g. shift 16 bits is the same as dividing by 65,536 which is
+ * about 1:05m
+ */
+public final int getCurrentBucketPrefix() {
+return (int) (System.currentTimeMillis() >> this.numBits);
+}
+
+/**
+ *
+ * @return
+ */
+public int getNumBits() {
+return numBits;
+}
+
+/**
+ * the actual duration may differ from the configured duration because
+ * it is set to the next power of 2 value in order to perform very fast
+ * bit shift arithmetic
+ *
+ * @return the actual bucket duration in milliseconds
+ */
+public int getActualDuration() {
+return (int) Math.pow(2, getNumBits());
+}
+
+/**
+ * returns the ratio between the configured duration param and the
+ * actual duration which will be set to the next power of 2.  we then
+ * multiply the configured requests param by the same ratio in order
+ * to compensate for the added time, if any
+ *
+ * @return the ratio, e.g. 1.092 if the actual duration is 65_536 for
+ * the configured duration of 60_000
+ */
+public double getRatio() {
+return ratio;
+}
+
+/**
+ * returns the ratio to the next power of 2 so that we can adjust the value
+ *
+ * @param value
+ * @return
+ */
+static double ratioToPowerOf2(int value) {
+double nextPO2 = nextPowerOf2(value);
+return Math.round((1000 * nextPO2 / value)) / 1000d;
+}
+
+/**
+ * returns the next power of 2 given a value, e.g. 256 for 250,
+ * or 1024, for 

[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-03-30 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1153762530


##
java/org/apache/catalina/filters/RateLimitFilter.java:
##
@@ -0,0 +1,230 @@
+/*
+ * 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.catalina.filters;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.FilterConfig;
+import jakarta.servlet.GenericFilter;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletResponse;
+import org.apache.catalina.util.TimeBucketCounter;
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.res.StringManager;
+
+import java.io.IOException;
+
+public class RateLimitFilter extends GenericFilter {
+
+/**
+ * default duration in seconds
+ */
+public static final int DEFAULT_BUCKET_DURATION = 60;
+
+/**
+ * default number of requests per duration
+ */
+public static final int DEFAULT_BUCKET_REQUESTS = 300;
+
+/**
+ * default value for enforce
+ */
+public static final boolean DEFAULT_ENFORCE = true;
+
+/**
+ * default status code to return if requests per duration exceeded
+ */
+public static final int DEFAULT_STATUS_CODE = 429;
+
+/**
+ * default status message to return if requests per duration exceeded
+ */
+public static final String DEFAULT_STATUS_MESSAGE = "Too many requests";
+
+/**
+ * request attribute that will contain the number of requests per duration
+ */
+public static final String RATE_LIMIT_ATTRIBUTE_COUNT = 
"org.apache.catalina.filters.RateLimitFilter.Count";
+
+/**
+ * filter init-param to set the bucket duration in seconds
+ */
+public static final String PARAM_BUCKET_DURATION = 
"ratelimit.bucket.duration";
+
+/**
+ * filter init-param to set the bucket number of requests
+ */
+public static final String PARAM_BUCKET_REQUESTS = 
"ratelimit.bucket.requests";
+
+/**
+ * filter init-param to set the enforce flag
+ */
+public static final String PARAM_ENFORCE = "ratelimit.enforce";
+
+/**
+ * filter init-param to set a custom status code if requests per duration 
exceeded
+ */
+public static final String PARAM_STATUS_CODE = "ratelimit.status.code";
+
+/**
+ * filter init-param to set a custom status message if requests per 
duration exceeded
+ */
+public static final String PARAM_STATUS_MESSAGE = 
"ratelimit.status.message";
+
+TimeBucketCounter bucketCounter;
+
+private int actualRequests;
+
+private int bucketRequests = DEFAULT_BUCKET_REQUESTS;
+
+private int bucketDuration = DEFAULT_BUCKET_DURATION;
+
+private boolean enforce = DEFAULT_ENFORCE;
+private int statusCode = DEFAULT_STATUS_CODE;
+
+private String statusMessage = DEFAULT_STATUS_MESSAGE;
+
+private transient Log log = LogFactory.getLog(RateLimitFilter.class);
+
+private static final StringManager sm = 
StringManager.getManager(RateLimitFilter.class);
+
+/**
+ * @return the actual maximum allowed requests per time bucket
+ */
+public int getActualRequests() {
+return actualRequests;
+}
+
+/**
+ * @return the actual duration of a time bucket in milliseconds
+ */
+public int getActualDurationInSeconds() {
+return bucketCounter.getActualDuration() / 1000;
+}
+
+@Override
+public void init() throws ServletException {
+
+FilterConfig config = getFilterConfig();
+
+String param;
+param = config.getInitParameter(PARAM_BUCKET_DURATION);
+if (param != null)
+bucketDuration = Integer.parseInt(param);
+
+param = config.getInitParameter(PARAM_BUCKET_REQUESTS);
+if (param != null)
+bucketRequests = Integer.parseInt(param);
+
+param = config.getInitParameter(PARAM_ENFORCE);
+if (param != null)
+enforce = Boolean.parseBoolean(param);
+
+param = config.getInitParameter(PARAM_STATUS_CODE);
+if (param != null)
+statusCode = Integer.parseInt(param);
+

[GitHub] [tomcat] isapir commented on a diff in pull request #607: Added RateLimitFilter

2023-03-29 Thread via GitHub


isapir commented on code in PR #607:
URL: https://github.com/apache/tomcat/pull/607#discussion_r1152128204


##
java/org/apache/catalina/filters/RateLimitFilter.java:
##
@@ -0,0 +1,230 @@
+/*
+ * 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.catalina.filters;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.FilterConfig;
+import jakarta.servlet.GenericFilter;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletResponse;
+import org.apache.catalina.util.TimeBucketCounter;
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.res.StringManager;
+
+import java.io.IOException;
+
+public class RateLimitFilter extends GenericFilter {
+
+/**
+ * default duration in seconds
+ */
+public static final int DEFAULT_BUCKET_DURATION = 60;
+
+/**
+ * default number of requests per duration
+ */
+public static final int DEFAULT_BUCKET_REQUESTS = 300;
+
+/**
+ * default value for enforce
+ */
+public static final boolean DEFAULT_ENFORCE = true;
+
+/**
+ * default status code to return if requests per duration exceeded
+ */
+public static final int DEFAULT_STATUS_CODE = 429;
+
+/**
+ * default status message to return if requests per duration exceeded
+ */
+public static final String DEFAULT_STATUS_MESSAGE = "Too many requests";
+
+/**
+ * request attribute that will contain the number of requests per duration
+ */
+public static final String RATE_LIMIT_ATTRIBUTE_COUNT = 
"org.apache.catalina.filters.RateLimitFilter.Count";
+
+/**
+ * filter init-param to set the bucket duration in seconds
+ */
+public static final String PARAM_BUCKET_DURATION = 
"ratelimit.bucket.duration";
+
+/**
+ * filter init-param to set the bucket number of requests
+ */
+public static final String PARAM_BUCKET_REQUESTS = 
"ratelimit.bucket.requests";
+
+/**
+ * filter init-param to set the enforce flag
+ */
+public static final String PARAM_ENFORCE = "ratelimit.enforce";
+
+/**
+ * filter init-param to set a custom status code if requests per duration 
exceeded
+ */
+public static final String PARAM_STATUS_CODE = "ratelimit.status.code";
+
+/**
+ * filter init-param to set a custom status message if requests per 
duration exceeded
+ */
+public static final String PARAM_STATUS_MESSAGE = 
"ratelimit.status.message";
+
+TimeBucketCounter bucketCounter;
+
+private int actualRequests;
+
+private int bucketRequests = DEFAULT_BUCKET_REQUESTS;
+
+private int bucketDuration = DEFAULT_BUCKET_DURATION;
+
+private boolean enforce = DEFAULT_ENFORCE;
+private int statusCode = DEFAULT_STATUS_CODE;
+
+private String statusMessage = DEFAULT_STATUS_MESSAGE;
+
+private transient Log log = LogFactory.getLog(RateLimitFilter.class);
+
+private static final StringManager sm = 
StringManager.getManager(RateLimitFilter.class);
+
+/**
+ * @return the actual maximum allowed requests per time bucket
+ */
+public int getActualRequests() {
+return actualRequests;
+}
+
+/**
+ * @return the actual duration of a time bucket in milliseconds
+ */
+public int getActualDurationInSeconds() {
+return bucketCounter.getActualDuration() / 1000;
+}
+
+@Override
+public void init() throws ServletException {
+
+FilterConfig config = getFilterConfig();
+
+String param;
+param = config.getInitParameter(PARAM_BUCKET_DURATION);
+if (param != null)
+bucketDuration = Integer.parseInt(param);
+
+param = config.getInitParameter(PARAM_BUCKET_REQUESTS);
+if (param != null)
+bucketRequests = Integer.parseInt(param);
+
+param = config.getInitParameter(PARAM_ENFORCE);
+if (param != null)
+enforce = Boolean.parseBoolean(param);
+
+param = config.getInitParameter(PARAM_STATUS_CODE);
+if (param != null)
+statusCode = Integer.parseInt(param);
+