Skip to content

Conversation

@piyush-jaiswal
Copy link
Owner

@piyush-jaiswal piyush-jaiswal commented Aug 20, 2025

Summary by CodeRabbit

  • Tests
    • Strengthened authentication tests with comprehensive JWT validation: verifies token structure, key claims (subject, type, issued/expiry, ID, freshness) and expected lifetimes for access and refresh tokens.
    • Replaced simple presence checks with payload- and time-based assertions (small tolerance) to catch expiry/regression issues.
    • No user-facing behavior changes; improves reliability and security coverage.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

Walkthrough

Added JWT structural validation to auth tests: constants for token lifetimes, helpers to decode tokens and assert payload structure, and updated login/refresh tests to verify claims (sub,type,iat,exp,jti,fresh) and expiry deltas instead of simple presence checks.

Changes

Cohort / File(s) Summary of changes
Auth tests (JWT structural validation)
tests/test_auth.py
Added ACCESS_TOKEN_DELTA = 10800 and REFRESH_TOKEN_DELTA = 259200; imported math and decode_token; introduced _decode_token(self, token) and _assert_jwt_structure(self, token, expected_sub, expected_type, fresh=False) helpers; replaced non-empty token assertions with payload-level checks in test_login_success and test_refresh_token, validating sub, type, iat, exp, jti, fresh, and expiry deltas (using math.isclose with ~2s tolerance).

Sequence Diagram(s)

No sequence diagram necessary for these test-only structural assertions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A curious rabbit checks each JWT bright,
Counting iat and exp by moonlight.
Fresh hops for access, refresh nests tight,
Three-dot tokens dancing in soft twilight.
🐇🔐

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 242d4ed and eaff7aa.

📒 Files selected for processing (1)
  • tests/test_auth.py (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/test_auth.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/improve_jwt_tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (2)
tests/test_auth.py (2)

13-14: Avoid hardcoding token lifetimes; derive from app config to prevent drift

Hardcoding 3h/3d will make tests brittle if config changes (e.g., shorter TTLs for CI). Read from Flask config with safe fallbacks.

Apply this diff to stop hardcoding at declaration:

-    ACCESS_TOKEN_DELTA = 10800      # 3 hours in seconds
-    REFRESH_TOKEN_DELTA = 259200    # 3 days in seconds
+    # Set from app config at runtime (fallbacks applied in setup)
+    ACCESS_TOKEN_DELTA = None
+    REFRESH_TOKEN_DELTA = None

Add this helper and initialize in setup (outside the selected lines):

from datetime import timedelta

def _seconds(self, val, default):
    if isinstance(val, timedelta):
        return int(val.total_seconds())
    try:
        return int(val)
    except Exception:
        return default

# In setup(), after setting self.client:
with self.client.application.app_context():
    cfg = self.client.application.config
    self.ACCESS_TOKEN_DELTA = self._seconds(
        cfg.get("JWT_ACCESS_TOKEN_EXPIRES", 10800), 10800
    )
    self.REFRESH_TOKEN_DELTA = self._seconds(
        cfg.get("JWT_REFRESH_TOKEN_EXPIRES", 259200), 259200
    )

Verification: Please confirm your test settings set JWT_ACCESS_TOKEN_EXPIRES ≈ 3h and JWT_REFRESH_TOKEN_EXPIRES ≈ 3d, or the above fallback values will be used.


62-75: Use elif to avoid accidental override; keep expiry-delta intent clear

Small logic/readability fix; the second if shouldn’t run when type == "access".

Apply this diff:

-        expected_delta = None
-        if expected_type == "access":
-            expected_delta = self.ACCESS_TOKEN_DELTA
-        if expected_type == "refresh":
-            expected_delta = self.REFRESH_TOKEN_DELTA
+        expected_delta = None
+        if expected_type == "access":
+            expected_delta = self.ACCESS_TOKEN_DELTA
+        elif expected_type == "refresh":
+            expected_delta = self.REFRESH_TOKEN_DELTA

Optional: After adopting config-driven TTLs (see Lines 13-14), this section will remain robust to future config changes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4c4f815 and fec2a31.

📒 Files selected for processing (1)
  • tests/test_auth.py (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/test_auth.py (1)
tests/test_category.py (3)
  • test_update_category_expired_token (144-163)
  • TestCategory (7-241)
  • test_create_category_expired_token (121-128)
🔇 Additional comments (2)
tests/test_auth.py (2)

1-2: LGTM on math import usage

Import is necessary for the isclose tolerance check below.


7-7: LGTM on decode_token import

Correct import for payload validation.

piyush-jaiswal and others added 3 commits August 21, 2025 00:02
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@piyush-jaiswal piyush-jaiswal merged commit 9adc854 into master Aug 20, 2025
3 checks passed
@piyush-jaiswal piyush-jaiswal deleted the feature/improve_jwt_tests branch August 20, 2025 18:53
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