Skip to content

Baip 315/jwt token does not contain any accessible tenants#32

Merged
jiristrouhal merged 5 commits intomasterfrom
BAIP-315/jwt-token-does-not-contain-any-accessible-tenants
May 9, 2025
Merged

Baip 315/jwt token does not contain any accessible tenants#32
jiristrouhal merged 5 commits intomasterfrom
BAIP-315/jwt-token-does-not-contain-any-accessible-tenants

Conversation

@jiristrouhal
Copy link
Contributor

@jiristrouhal jiristrouhal commented May 9, 2025

Fix the tenant extraction from the JWT token.

THe previous version expected the extracted payload to contain item 'payload' - this is not the case, that decoded object contains directly the 'group' item.

Summary by CodeRabbit

  • New Features

    • Updated the API version to 4.1.1 in documentation and project metadata.
  • Bug Fixes

    • Improved error messages for missing tenant information in JWT tokens.
  • Refactor

    • Simplified JWT payload handling for tenant extraction.
    • Streamlined the structure and naming of constants related to tenant information.
    • Removed redundant JWT utility functions and unused imports.
    • Cleaned up and organized import statements in test files.

jiri.strouhal added 5 commits May 9, 2025 07:20
THe previous version expected the extracted payload to contain item 'payload' - this is not the case, that decoded object contains directly the 'group' item.
@jiristrouhal jiristrouhal self-assigned this May 9, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 9, 2025

Walkthrough

This update refactors JWT payload handling for tenant information in the Fleet Management API. It replaces JSON string parsing with direct dictionary access, updates the payload structure, and removes related utility functions. The constants are revised, and unused imports are cleaned up. The API version is incremented to 4.1.1 in relevant metadata files.

Changes

File(s) Change Summary
fleet_management_api/api_impl/constants.py Added a module docstring; replaced PAYLOAD_FIELD_NAME (string) with TENANT_PAYLOAD_ITEM (tuple with "group"); clarified usage with comments.
fleet_management_api/api_impl/tenants.py Removed JSON parsing and custom JWT decode/encode utilities; now accesses "group" key directly in JWT payload; improved error handling and messages; removed unused imports and utility functions.
fleet_management_api/app.py Stopped importing PAYLOAD_FIELD_NAME; JWT payload now uses "group" key with a list of tenant paths, adds "iss" and "aud" fields; corrected logging message typo.
fleet_management_api/openapi/openapi.yaml, openapi/openapi.yaml, pyproject.toml Incremented API/project version from 4.1.0 to 4.1.1 in OpenAPI specs and project metadata.
tests/controllers/car/test_car_controller.py Cleaned up and consolidated imports; removed unused imports (decode_jwt_token, get_public_key, duplicate TenantFromTokenMock). No changes to test logic.
tests/security/test_tenants_from_jwt.py Removed unused imports (fleet_management_api.database.db_access, TenantDB). No changes to test logic.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant JWT

    Client->>API: Request with JWT token
    API->>JWT: Decode JWT token
    JWT-->>API: Return payload (dict with "group" key)
    API->>API: Check for "group" in payload
    alt "group" key present
        API->>API: Extract tenant names from "group" list
        API-->>Client: Return accessible tenants
    else "group" key missing
        API-->>Client: Return error (NoAccessibleTenants)
    end
Loading
sequenceDiagram
    participant API
    participant JWT

    API->>API: Prepare tenant list as list of strings
    API->>JWT: Encode JWT with payload {"group": [...], "iss": "test", "aud": "account"}
    JWT-->>API: Return JWT token
Loading

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

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

🧹 Nitpick comments (1)
fleet_management_api/app.py (1)

48-48: Typo in error message.

There's a typo in the error message: "JWsT" instead of "JWT".

- _log_error(f"Failed to encode JWsT token: {str(e)}")
+ _log_error(f"Failed to encode JWT token: {str(e)}")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 673cda7 and 1dfb757.

📒 Files selected for processing (8)
  • fleet_management_api/api_impl/constants.py (1 hunks)
  • fleet_management_api/api_impl/tenants.py (2 hunks)
  • fleet_management_api/app.py (2 hunks)
  • fleet_management_api/openapi/openapi.yaml (1 hunks)
  • openapi/openapi.yaml (1 hunks)
  • pyproject.toml (1 hunks)
  • tests/controllers/car/test_car_controller.py (2 hunks)
  • tests/security/test_tenants_from_jwt.py (0 hunks)
💤 Files with no reviewable changes (1)
  • tests/security/test_tenants_from_jwt.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/controllers/car/test_car_controller.py (1)
tests/_utils/setup_utils.py (4)
  • create_stops (35-50)
  • create_platform_hws (21-32)
  • create_route (53-63)
  • TenantFromTokenMock (9-18)
🔇 Additional comments (11)
pyproject.toml (1)

3-3: Version bump is consistent
The version has been updated from 4.1.0 to 4.1.1 to align with API changes.

openapi/openapi.yaml (1)

5-5: OpenAPI version updated
The info.version field has been incremented to 4.1.1, matching the project version in pyproject.toml.

fleet_management_api/openapi/openapi.yaml (1)

12-12: OpenAPI version updated
The info.version field has been bumped to 4.1.1, ensuring consistency across OpenAPI specs.

fleet_management_api/api_impl/constants.py (1)

1-1: Add module docstring
The module-level docstring clarifies the purpose of these constants for tenant-related logic.

tests/controllers/car/test_car_controller.py (2)

2-2: Blank line inserted for readability; no action needed.


16-21: Consolidate imports from tests._utils.setup_utils
Grouping create_stops, create_platform_hws, create_route, and TenantFromTokenMock under one import improves organization and reflects updated utilities.

fleet_management_api/app.py (2)

35-35: Improved tenant path handling.

The change to create a list of tenant paths using a list comprehension is a good improvement that makes the code more explicit and aligns with the expected JWT payload structure.


37-39: JWT payload structure correctly updated.

The payload structure now correctly includes the group field containing tenant paths, along with standard JWT fields (iss and aud). This aligns with the updated tenant extraction logic in tenants.py.

fleet_management_api/api_impl/tenants.py (3)

171-175: Improved error handling with detailed messages.

Adding the specific error message from the exception provides better context for debugging when tenant extraction fails.


233-237: Core fix: Direct JWT payload handling.

This is the key change that addresses the issue described in the PR. Instead of assuming a nested structure with a 'payload' field, the code now correctly:

  1. Directly uses the decoded JWT payload returned by jwt.decode
  2. Checks for the presence of the 'group' key
  3. Extracts the tenant information directly from the payload

This change simplifies the code and fixes the tenant extraction issue.


240-240: Clearer error message.

The updated error message more clearly explains the issue when no tenants are found in the token.

@jiristrouhal jiristrouhal requested a review from MarioIvancik May 9, 2025 11:03
@jiristrouhal jiristrouhal merged commit 0bed9b9 into master May 9, 2025
3 checks passed
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.

1 participant