Skip to content
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

fix(password-reset): rate limit password reset emails #2619

Merged
merged 5 commits into from
Aug 15, 2023

Conversation

gagantrivedi
Copy link
Member

@gagantrivedi gagantrivedi commented Aug 10, 2023

Thanks for submitting a PR! Please check the boxes below:

  • I have run pre-commit to check linting
  • I have filled in the "Changes" section below?
  • I have filled in the "How did you test this code" section below?
  • I have used a Conventional Commit title for this Pull Request

Changes

Rate limit password reset emails

New environment variables:


# Define the cooldown duration, in seconds, for password reset emails
PASSWORD_RESET_EMAIL_COOLDOWN = env.int("PASSWORD_RESET_EMAIL_COOLDOWN", 60 * 60 * 24)

# Limit the count of password reset emails that can be dispatched within the `PASSWORD_RESET_EMAIL_COOLDOWN` timeframe.
MAX_PASSWORD_RESET_EMAILS = env.int("MAX_PASSWORD_RESET_EMAILS", 5)

How did you test this code?

Covered by unit tests

@vercel
Copy link

vercel bot commented Aug 10, 2023

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 15, 2023 10:14am
flagsmith-frontend-preview ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 15, 2023 10:14am
flagsmith-frontend-staging ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 15, 2023 10:14am

@github-actions
Copy link
Contributor

github-actions bot commented Aug 10, 2023

Uffizzi Preview deployment-33098 was deleted.

@codecov-commenter
Copy link

codecov-commenter commented Aug 10, 2023

Codecov Report

Patch coverage: 97.29% and no project coverage change.

Comparison is base (cb42f9d) 95.43% compared to head (42d3233) 95.44%.
Report is 20 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2619   +/-   ##
=======================================
  Coverage   95.43%   95.44%           
=======================================
  Files         975      977    +2     
  Lines       27245    27325   +80     
=======================================
+ Hits        26002    26080   +78     
- Misses       1243     1245    +2     
Files Changed Coverage Δ
api/users/models.py 94.11% <80.00%> (-0.73%) ⬇️
api/app/settings/common.py 87.71% <100.00%> (+0.08%) ⬆️
api/custom_auth/migrations/0001_initial.py 100.00% <100.00%> (ø)
api/custom_auth/models.py 100.00% <100.00%> (ø)
api/custom_auth/views.py 100.00% <100.00%> (ø)
api/tests/unit/users/test_unit_users_views.py 100.00% <100.00%> (ø)

... and 3 files with indirect coverage changes

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@matthewelwell matthewelwell left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm... this feels like a bit overkill to me? I think we can just store the last password reset request time (although I'd argue we'd be better off storing this in a separate table than directly on the user model, as it will give us more flexibility), and then just define an interval between resets of, say, 30 or 60 seconds?

@gagantrivedi
Copy link
Member Author

Hmm... this feels like a bit overkill to me? I think we can just store the last password reset request time (although I'd argue we'd be better off storing this in a separate table than directly on the user model, as it will give us more flexibility), and then just define an interval between resets of, say, 30 or 60 seconds?

I just wanted to completely get rid of this issue - emails generated per 30 sec or 1 min are still a lot of emails?

Comment on lines 171 to 183
@property
def can_send_password_reset_email(self) -> bool:
with suppress(TypeError):
if self.last_password_reset_email_at < timezone.now() - timezone.timedelta(
seconds=settings.PASSWORD_RESET_EMAIL_COOLDOWN
):
return True
return (
self.num_of_password_reset_emails_sent
< settings.MAX_PASSWORD_RESET_EMAILS
)

return True
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In response to the main thread on the PR, I tend to agree that we should do slightly more to prevent it but I do think that if we use a separate model this logic will become slightly cleaner / more flexible?

Something like:

class UserPasswordResetRequest(models.Model):
    user = models.ForeignKey("users.FFAdminUser", related_name="password_reset_requests")
    requested_at = models.DateTimeField(auto_now_add=True)

Then the code above becomes something like:

def can_send_password_reset_email(self) -> bool:
    limit = timezone.now() - timezone.timedelta(
        seconds=settings.PASSWORD_RESET_EMAIL_COOLDOWN
    )
    return (
        self.password_reset_requests.filter(requested_at__gte=limit).count() 
        > settings.MAX_PASSWORD_RESET_EMAILS
    )

Then on a successful password reset, we just clear the table for that user.

(sidenote: as per my comment on another PR, I'd rather not query the database in properties if we can avoid it)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, good point. Done

@@ -903,3 +903,9 @@
DOMAIN_OVERRIDE = env.str("FLAGSMITH_DOMAIN", "")
# Used when no Django site is specified.
DEFAULT_DOMAIN = "app.flagsmith.com"

# Define the cooldown duration, in seconds, for password reset emails
PASSWORD_RESET_EMAIL_COOLDOWN = env.int("PASSWORD_RESET_EMAIL_COOLDOWN", 60 * 60 * 24)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess there's now a question whether we should add a recurring task to delete all UserPasswordResetRequest entities older than this time frame. Probably one we can worry about in the future but we will end up with stale data in there that likely never gets deleted / used.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, likely. I will create an issue for it once this is merged, sounds good?

api/users/models.py Outdated Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api Issue related to the REST API
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants