docbrown/app/labor/rate_limit_checker.rb
Omar Bahareth dca66bd6a8 Rate limit daily user follows to 500 (#4647) [deploy]
* Rate limit daily user follows to 500 per day
Return an error in `POST /follows` JSON response when a user tries to follow more than 500 accounts in a single day.

Other Changes:
- Add a spec for follows#create.

* Turn daily account follow limit into an env var

* Avoid executing today follow count query when possible
user.following_users_count is a counter cache on how many users the person is already following, so if it's less than the limit we don't need to run the query and can just return it instead.

* Simplify today follow count query
Stop needlessly checking into the future, only check from the beginning of the day until now.

* Raise account follow limit error if followable_id count is over limit
Other changes:
- Always return JSON, the `respond_to` block from before was unnecessary since this endpoint always returns JSON.
- Rescue `DailyFollowAccountLimitReached` on the method and remove begin block, since the error can be raised from two places in the same method.

* Index created_at on users table

* Make adding created_at index on users table happen concurrently

* Rename DAILY_ACCOUNT_FOLLOW_LIMIT to RATE_LIMIT_FOLLOW_COUNT_DAILY

* Add RATE_LIMIT_FOLLOW_COUNT_DAILY to Envfile

* Move RATE_LIMIT_FOLLOW_COUNT_DAILY from env var to ApplicationConfig
2019-11-06 16:24:43 -05:00

60 lines
1.7 KiB
Ruby

class RateLimitChecker
attr_reader :user, :action
def self.daily_account_follow_limit
ApplicationConfig["RATE_LIMIT_FOLLOW_COUNT_DAILY"]
end
def initialize(user = nil)
@user = user
end
class UploadRateLimitReached < StandardError; end
class DailyFollowAccountLimitReached < StandardError; end
def limit_by_action(action)
result = case action
when "comment_creation"
user.comments.where("created_at > ?", 30.seconds.ago).size > 9
when "published_article_creation"
user.articles.published.where("created_at > ?", 30.seconds.ago).size > 9
when "image_upload"
Rails.cache.read("#{user.id}_image_upload").to_i > 9
when "follow_account"
user_today_follow_count > self.class.daily_account_follow_limit
else
false
end
if result
@action = action
ping_admins
end
result
end
def track_image_uploads
count = Rails.cache.read("#{@user.id}_image_upload").to_i
count += 1
Rails.cache.write("#{@user.id}_image_upload", count, expires_in: 30.seconds)
end
def limit_by_email_recipient_address(address)
# This is related to the recipient, not the "user" initiator, like in action.
EmailMessage.where(to: address).
where("sent_at > ?", 2.minutes.ago).size > 5
end
def ping_admins
RateLimitCheckerJob.perform_later(user.id, action)
end
private
def user_today_follow_count
following_users_count = user.following_users_count
return following_users_count if following_users_count < self.class.daily_account_follow_limit
now = Time.zone.now
user.follows.where(created_at: (now.beginning_of_day..now)).size
end
end