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

MFA v1 - TOTP #2830

Draft
wants to merge 21 commits into
base: develop
Choose a base branch
from
Draft

Conversation

yash-learner
Copy link
Member

@yash-learner yash-learner commented Feb 12, 2025

Proposed Changes

This pull request introduces a new feature for Two-Factor Authentication (2FA) using Time-based One-Time Password (TOTP). The changes include updates to various files to support TOTP setup, verification, and login processes.

New TOTP Feature Implementation:

Configuration and Dependencies:

  • .env.example: Added TOTP_SECRET_ENCRYPTION_KEY to the environment variables.
  • Pipfile: Added the pyotp library as a dependency for TOTP functionality.
  • config/settings/base.py: Added TOTP_SECRET_ENCRYPTION_KEY to the settings.
  • docker/.local.env: Added TOTP_SECRET_ENCRYPTION_KEY to the local environment variables.
  • docker/.prebuilt.env: Added TOTP_SECRET_ENCRYPTION_KEY to the prebuilt environment variables.

Authentication Updates:

  • config/auth_views.py: Updated the TokenObtainPairSerializer and TokenRefreshSerializer to handle temporary tokens for TOTP verification during login. [1] [2] [3]

Associated Issue


TOTP Feature Implementation:

User Model and Migration:

Encryption Utilities:

Configuration and Environment Variables:

  • .env.example, docker/.local.env, docker/.prebuilt.env, config/settings/base.py: Added TOTP_SECRET_ENCRYPTION_KEY to environment variables and settings. [1] [2] [3] [4]

API Router and Authentication:

Dependency Updates:

  • Pipfile: Added pyotp dependency for TOTP functionality.

Merge Checklist

  • Tests added/fixed
  • Update docs in /docs
  • Linting Complete
  • Any other necessary step

Only PR's with test cases included and passing lint and test pipelines will be reviewed

@ohcnetwork/care-backend-maintainers @ohcnetwork/care-backend-admins

Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Feb 12, 2025

Codecov Report

Attention: Patch coverage is 41.66667% with 112 lines in your changes missing coverage. Please review.

Project coverage is 56.01%. Comparing base (41877f1) to head (c027542).
Report is 9 commits behind head on develop.

Files with missing lines Patch % Lines
care/emr/api/viewsets/totp.py 40.25% 92 Missing ⚠️
care/emr/tasks/totp.py 47.36% 10 Missing ⚠️
config/auth_views.py 11.11% 8 Missing ⚠️
care/utils/encryption.py 71.42% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2830      +/-   ##
===========================================
- Coverage    56.24%   56.01%   -0.23%     
===========================================
  Files          215      218       +3     
  Lines        10231    10404     +173     
  Branches      1038     1052      +14     
===========================================
+ Hits          5754     5828      +74     
- Misses        4461     4560      +99     
  Partials        16       16              

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

care/emr/api/viewsets/totp.py Show resolved Hide resolved
@@ -18,3 +18,5 @@ BUCKET_ENDPOINT=http://localhost:4566
BUCKET_EXTERNAL_ENDPOINT=http://localhost:4566
FILE_UPLOAD_BUCKET=patient-bucket
FACILITY_S3_BUCKET=facility-bucket

TOTP_SECRET_ENCRYPTION_KEY=your-encryption-key-here
Copy link
Member

Choose a reason for hiding this comment

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

We already have a secret key, lets reuse that.

Copy link
Member Author

Choose a reason for hiding this comment

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

I can't find one in this https://github.com/ohcnetwork/care/blob/develop/.env.example, by any chance is it django_secret_key ?

return Response({"backup_codes": backup_codes})

@staticmethod
def _check_totp_enabled(mfa_settings: dict):
Copy link
Member

Choose a reason for hiding this comment

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

This function should return either true or false and let the implementer write the exception.

Copy link
Member Author

Choose a reason for hiding this comment

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

This function should return either true or false and let the implementer write the exception.

Yeah, I thought this was the expected way when writting this method but wrote the exception inside the_check_totp_enabled as the exception is same for all three methods which are calling this so trying to not repeat the code made me write this way and also this will make understanding the code little tough and also misleading with its method name.

Will fix it 👍

)

secret = random_base32()
encrypted_secret = encrypt_string(secret)
Copy link
Member

Choose a reason for hiding this comment

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

I didn't really understand how encrypting this string has a security advantage, for someone to hack around this, they need access to the database and not the application, but if you have access to the database then we have already lost right?
And the backup codes are not encrypted, that already undoes all this work.

Copy link
Member Author

Choose a reason for hiding this comment

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

And the backup codes are not encrypted, that already undoes all this work.

Backup codes are hashed and stored

"code": make_password(code),

So even some get's access to DB. they can't use 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.

but if you have access to the database then we have already lost right?

Yes

but

If it is plain text they can generate the TOTP codes and if it is encrypted, one cannot generate, and also it will save during accidental exposure

🤔

user = request.user

if not user.totp_secret:
return Response(
Copy link
Member

Choose a reason for hiding this comment

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

raise a validation error

def login(self, request):
request_data = TOTPLoginRequest(**request.data)

token = RefreshToken(request_data.temp_token)
Copy link
Member

Choose a reason for hiding this comment

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

Need exception handling around this, if an invalid token is given it will raise an error

if totp.verify(request_data.code):
refresh = RefreshToken.for_user(user)

try:
Copy link
Member

Choose a reason for hiding this comment

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

No need to blacklist, you can let this token exist, this token can only be used with an MFA option.

user = User.objects.get(external_id=token["user_id"])
totp = TOTP(decrypt_string(user.totp_secret))

if totp.verify(request_data.code):
Copy link
Member

Choose a reason for hiding this comment

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

How is the backup code used here? the backup codes are maintained by us or the package?

Copy link
Member Author

Choose a reason for hiding this comment

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

By us, pyotp does not provide out of the box

permission_classes=[],
authentication_classes=[],
)
def backup_login(self, request):
Copy link
Member

Choose a reason for hiding this comment

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

Why cant we just use the same endpoint and check the backup codes if the others dont match?

Copy link
Member Author

Choose a reason for hiding this comment

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

We can, but pyotp does not provide out of the box backup_codes support, and it is implemented by us, so keeping both in one endpoint will make the method bulkier 😁 and having separate endpoint provides clear separation

but a lot of shared code between two login and backup_login will think whether I can reduce some duplicity of code and will think what will it look like both in single endpoint

Do you have reasons to make it in a single endpoint ?

permission_classes=[],
authentication_classes=[],
)
def login(self, request):
Copy link
Member

Choose a reason for hiding this comment

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

We need ratelimiting, the token should expire within 5 mins as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants