Skip to content

Baip 316/do not allow api key and jwt simultaneously#33

Open
jiristrouhal wants to merge 4 commits intomasterfrom
BAIP-316/do-not-allow-api-key-and-jwt-simultaneously
Open

Baip 316/do not allow api key and jwt simultaneously#33
jiristrouhal wants to merge 4 commits intomasterfrom
BAIP-316/do-not-allow-api-key-and-jwt-simultaneously

Conversation

@jiristrouhal
Copy link
Contributor

@jiristrouhal jiristrouhal commented May 9, 2025

During authentication, the API now checks, if multiple authentication schemes are used in the same request and if so, 401 response is returned.

Summary by CodeRabbit

  • New Features
    • The system now enforces that API key and JWT token authentication methods cannot be used simultaneously. Requests attempting to use both will receive a 401 Unauthorized error with a clear message.
  • Bug Fixes
    • Improved error message clarity when tenant extraction fails.
  • Tests
    • Added tests to verify that combining API key and JWT token authentication results in a 401 error.
    • Updated existing tests for authentication behaviors.
  • Chores
    • Incremented API version to 4.1.2 in documentation and configuration files.
    • Minor documentation and formatting improvements for readability.

@jiristrouhal jiristrouhal requested a review from koudis May 9, 2025 13:05
@jiristrouhal jiristrouhal self-assigned this May 9, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 9, 2025

Walkthrough

This update enforces mutual exclusivity between JWT token and API key authentication methods, raising a 401 error if both are used simultaneously. It introduces a new test to verify this behavior, updates error message strings, and increments the project and OpenAPI specification version to 4.1.2. Minor formatting improvements are also included.

Changes

File(s) Change Summary
fleet_management_api/controllers/security_controller.py Added _raise_for_simultaneous_jwt_and_api_key() to detect and reject requests using both JWT and API key authentication; integrated this check into relevant authentication functions.
tests/security/test_combining_auth_schemes.py Added new test class and method to verify that simultaneous use of JWT token and API key results in a 401 Unauthorized error with an appropriate message.
tests/controllers/car/test_car_state_controller.py Modified an existing test to remove the use of the api_key query parameter when a JWT token is present, aligning with the new exclusivity enforcement.
fleet_management_api/api_impl/controller_decorators.py Updated error message title from "No tenants" to "Cannot extract tenants" for tenant extraction failure responses.
fleet_management_api/api_impl/tenants.py Minor formatting changes: removed a redundant blank line in a docstring and added a blank line after a raised exception for readability.
fleet_management_api/openapi/openapi.yaml, openapi/openapi.yaml, pyproject.toml Incremented API and project version from 4.1.1 to 4.1.2.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant SecurityController
    participant AuthSystem

    Client->>SecurityController: Request with JWT token and/or API key
    SecurityController->>SecurityController: _raise_for_simultaneous_jwt_and_api_key()
    alt Both JWT and API key present
        SecurityController-->>Client: 401 Unauthorized (error message)
    else Only one authentication method present
        SecurityController->>AuthSystem: Validate credentials
        AuthSystem-->>SecurityController: Auth result
        SecurityController-->>Client: Success or failure response
    end
Loading

Possibly related PRs

Suggested reviewers

  • MarioIvancik

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ 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:

  • 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.

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.

@sonarqubecloud
Copy link

sonarqubecloud bot commented May 9, 2025

@jiristrouhal jiristrouhal added the bug Something isn't working label May 9, 2025
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: 0

🧹 Nitpick comments (2)
fleet_management_api/controllers/security_controller.py (1)

74-85: Implementation correctly enforces mutual exclusivity between authentication methods.

The implementation properly detects when both authentication methods are present and raises a 401 error with a clear message. The approach of checking the raw query string for the API key parameter is robust.

Small performance optimization: You could consider caching the result of request.query_string.decode() in a variable since this operation is performed twice.

-    api_key_used = "api_key" in request.query_string.decode()
+    query_string = request.query_string.decode()
+    api_key_used = "api_key" in query_string
tests/security/test_combining_auth_schemes.py (1)

1-37: Well-structured test case to verify the new authentication enforcement.

This test effectively verifies that using both JWT token and API key authentication simultaneously returns a 401 error with an appropriate message.

-from connexion.exceptions import Unauthorized

There's an unused import of Unauthorized from connexion.exceptions that can be removed.

🧰 Tools
🪛 Ruff (0.8.2)

3-3: connexion.exceptions.Unauthorized imported but unused

Remove unused import: connexion.exceptions.Unauthorized

(F401)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0bed9b9 and 74dc711.

📒 Files selected for processing (8)
  • fleet_management_api/api_impl/controller_decorators.py (1 hunks)
  • fleet_management_api/api_impl/tenants.py (1 hunks)
  • fleet_management_api/controllers/security_controller.py (3 hunks)
  • fleet_management_api/openapi/openapi.yaml (1 hunks)
  • openapi/openapi.yaml (1 hunks)
  • pyproject.toml (1 hunks)
  • tests/controllers/car/test_car_state_controller.py (1 hunks)
  • tests/security/test_combining_auth_schemes.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
fleet_management_api/controllers/security_controller.py (4)
fleet_management_api/api_impl/load_request.py (1)
  • api_key (50-51)
fleet_management_api/models/car.py (2)
  • name (121-128)
  • name (131-141)
fleet_management_api/models/stop.py (2)
  • name (88-95)
  • name (98-108)
fleet_management_api/models/route.py (2)
  • name (74-81)
  • name (84-94)
🪛 Ruff (0.8.2)
tests/security/test_combining_auth_schemes.py

3-3: connexion.exceptions.Unauthorized imported but unused

Remove unused import: connexion.exceptions.Unauthorized

(F401)

🔇 Additional comments (9)
openapi/openapi.yaml (1)

5-5: Version increment appropriately reflects the new security validation feature.

The version update from 4.1.1 to 4.1.2 aligns with the implementation of the new security validation that prevents simultaneous use of API key and JWT authentication.

pyproject.toml (1)

3-3: Version update maintains consistency with OpenAPI specification.

The project version update from 4.1.1 to 4.1.2 aligns with the corresponding OpenAPI specification version change, ensuring consistency across the project.

fleet_management_api/openapi/openapi.yaml (1)

12-12: Version update maintains consistency with main OpenAPI specification.

This version increment from 4.1.1 to 4.1.2 ensures that the OpenAPI specification bundled with the Python package matches the main specification file.

fleet_management_api/api_impl/controller_decorators.py (1)

66-66: Improved error message clarity for tenant extraction failures.

The error title change from "No tenants" to "Cannot extract tenants" provides clearer context about what went wrong during the tenant extraction process, which enhances troubleshooting and error reporting.

fleet_management_api/api_impl/tenants.py (1)

227-227: Improved code readability with consistent spacing.

The addition of a blank line after the exception provides better visual separation between code blocks, enhancing readability while maintaining the same functionality.

tests/controllers/car/test_car_state_controller.py (1)

558-559: LGTM! URL updated to align with new authentication enforcement.

The URL has been correctly updated to remove the api_key parameter, ensuring this test now uses only JWT token authentication via the Authorization header. This change aligns with the new enforcement where API key and JWT token cannot be used simultaneously.

fleet_management_api/controllers/security_controller.py (3)

2-2: LGTM! Added necessary import for Request access.

The connexion import is required to access the request object and exceptions for the new authentication validation.


24-24: Good addition of mutual exclusivity check.

Adding the check at the beginning of the OAuth handler ensures requests with both authentication methods will be rejected early.


66-66: Good addition of mutual exclusivity check.

Adding the check at the beginning of the API key handler ensures requests with both authentication methods will be rejected early.

@jiristrouhal jiristrouhal requested review from MarioIvancik and removed request for koudis July 2, 2025 12:27
@MarioIvancik
Copy link
Member

Version tag has to be incremented further

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants