Skip to content

Add JWT token authentication #717

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Add JWT token authentication #717

wants to merge 1 commit into from

Conversation

amotl
Copy link
Member

@amotl amotl commented May 24, 2025

CrateDB 5.7.0 introduced JWT token authentication. Let's also implement it on the client sides.

/cc @matriv, @kneth

Copy link

coderabbitai bot commented May 24, 2025

Walkthrough

JWT token authentication support was added to the CrateDB Python client. This includes updates to the connection and HTTP client classes to accept and pass JWT tokens, documentation and changelog updates, and new tests to verify JWT authentication behavior. Existing authentication mechanisms remain unchanged.

Changes

File(s) Change Summary
CHANGES.rst Updated changelog to mention the new JWT token authentication feature.
docs/connect.rst Added documentation and example for JWT token authentication in the connection setup.
src/crate/client/connection.py Extended Connection.__init__ to accept and document a jwt_token parameter.
src/crate/client/http.py Added jwt_token parameter to Client and Server for JWT authentication; sets Authorization header.
tests/client/test_http.py Enhanced test handler for "Bearer" JWT tokens; added/updated tests for JWT token authentication.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Connection
    participant Client
    participant Server

    User->>Connection: connect(jwt_token=...)
    Connection->>Client: __init__(jwt_token=...)
    Client->>Server: request(..., jwt_token=...)
    Server->>Server: Add Authorization: Bearer <jwt_token> header (if not set)
    Server-->>Client: Response
    Client-->>Connection: Response
    Connection-->>User: Connection established
Loading

Poem

In fields of code, a token hops—
JWT in paw, it never stops.
Now clients greet with bearer flair,
Securely bounding here and there.
The docs are plump, the tests are keen,
This rabbit’s code is fresh and clean!
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5a9f518 and 8f06f22.

📒 Files selected for processing (5)
  • CHANGES.rst (1 hunks)
  • docs/connect.rst (1 hunks)
  • src/crate/client/connection.py (3 hunks)
  • src/crate/client/http.py (5 hunks)
  • tests/client/test_http.py (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/client/test_http.py (6)
tests/client/layer.py (1)
  • tearDown (216-218)
src/crate/testing/layer.py (1)
  • tearDown (372-373)
src/crate/client/connection.py (1)
  • close (180-185)
src/crate/client/cursor.py (1)
  • close (151-156)
src/crate/client/http.py (3)
  • close (210-211)
  • close (489-491)
  • sql (506-518)
src/crate/testing/util.py (2)
  • close (43-44)
  • sql (31-32)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run link checker
  • GitHub Check: Python: 3.13 on macos-latest
  • GitHub Check: Python: 3.12 on macos-latest
  • GitHub Check: Python: 3.11 on macos-latest
  • GitHub Check: Python: 3.13 on ubuntu-22.04
  • GitHub Check: Python: 3.12 on ubuntu-22.04
  • GitHub Check: Python: 3.11 on ubuntu-22.04
  • GitHub Check: Python: 3.10 on ubuntu-22.04
  • GitHub Check: Python: 3.9 on ubuntu-22.04
  • GitHub Check: Python: 3.8 on ubuntu-22.04
  • GitHub Check: Python: 3.7 on ubuntu-22.04
🔇 Additional comments (15)
CHANGES.rst (1)

7-7: Clear and appropriate changelog entry.

The changelog entry accurately describes the new JWT token authentication feature and follows the established format.

docs/connect.rst (1)

249-254: Well-documented JWT token authentication.

The documentation clearly explains how to use JWT token authentication and follows the established documentation patterns. The placement after traditional authentication methods is logical.

src/crate/client/connection.py (3)

45-45: Parameter addition follows established pattern.

The jwt_token parameter is correctly added to the constructor signature with an appropriate default value.


85-86: Clear parameter documentation.

The JWT token parameter is properly documented in the docstring, following the same format as other authentication parameters.


154-154:

✅ Verification successful

Verify authentication method precedence.

The JWT token is correctly passed to the Client constructor. However, consider validating that conflicting authentication methods (JWT vs username/password) are handled appropriately in the underlying implementation.


🏁 Script executed:

#!/bin/bash
# Search for authentication validation logic in the HTTP client
rg -A 10 -B 5 "username.*password|jwt_token" --type py

Length of output: 12799


Authentication Precedence Confirmed

The HTTP client first injects a Bearer token when jwt_token is set, then only falls back to Basic auth if no Authorization header is present. This enforces JWT-over-username/password precedence as intended.

No changes required.

tests/client/test_http.py (5)

574-590: Robust authentication header handling.

The implementation correctly handles both Basic and Bearer authentication schemes. The logic properly extracts JWT tokens from Bearer headers and maintains backward compatibility with Basic authentication.


615-615: Appropriate test state initialization.

The JWT token is correctly added to the shared test state with proper initialization.


701-703: Test client setup follows established pattern.

The JWT token test client is properly configured with a test token value, following the same pattern as other authentication test clients.


711-711: Proper test cleanup.

The tearDown method correctly includes cleanup for the new JWT token client to prevent resource leaks.


736-742: Comprehensive JWT token testing.

The test method verifies both negative (no token) and positive (token present) cases, ensuring the JWT token is correctly transmitted from client to server.

src/crate/client/http.py (5)

161-161: LGTM: JWT token parameter added correctly.

The jwt_token=None parameter is properly added to the method signature, maintaining backward compatibility.


177-179: LGTM: JWT Bearer token authentication implemented correctly.

The implementation properly:

  • Checks for existing Authorization header to avoid overwriting
  • Uses correct Bearer token format
  • Positions JWT authentication before Basic authentication, establishing proper precedence

426-426: LGTM: JWT token parameter added to Client constructor.

The parameter is consistently added with proper default value for backward compatibility.


482-482: LGTM: JWT token stored as instance attribute.

The JWT token is properly stored for later use in requests. The token is stored as a plain attribute, which is acceptable for this use case as JWT tokens are typically handled by the application layer.


599-599: LGTM: JWT token passed correctly to Server.request.

The stored JWT token is properly passed through the request call chain, completing the authentication implementation.

✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

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

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@amotl amotl requested review from seut and surister May 24, 2025 00:09
@amotl amotl marked this pull request as ready for review May 24, 2025 00:15
Copy link
Member

@seut seut left a comment

Choose a reason for hiding this comment

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

👍
Maybe adding a sanity check to give a good error if token and user/password auth is used in conjunction would be useful. Afaik, the user/password args would be used then instead (it will just override the Authorization header afaik) which may not be clear to a user.

@kneth
Copy link

kneth commented Jun 2, 2025

Thank you for providing support for JWT!

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.

3 participants