Skip to content

Conversation

@Subhra264
Copy link
Contributor

@Subhra264 Subhra264 commented Jun 27, 2024

Summary by CodeRabbit

  • New Features
    • Enhanced authentication and authorization handling for user requests with more efficient token validation.
  • Bug Fixes
    • Improved error handling and response based on user permissions and authorization status.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 27, 2024

Walkthrough

The refactor involves enhancing token validation by restructuring authentication and authorization logic for efficiency, particularly when handling HTTP POST requests and setting headers. Key updates include a conditional authorization block based on user permissions and improved error handling. Additionally, passing the org_id parameter in the list_objects function to ensure the organization context is maintained.

Changes

File Path Change Summary
src/handler/http/auth/token.rs Refactored token_validator function for efficient authentication and authorization, with updated header setting and error handling. Added conditional authorization check based on user permissions.
src/handler/http/auth/validator.rs Added org_id parameter to list_objects and updated list_objects_for_user to include this parameter.

Sequence Diagrams

Token Validation and Authorization Flow

sequenceDiagram
    participant Client
    participant Server
    participant Authenticator
    participant Authorizer
    
    Client->>Server: POST /validate-token
    Server->>Authenticator: Validate Token
    Authenticator-->>Server: Token Valid
    Server->>Authorizer: Check User Permissions
    Authorizer-->>Server: Permissions Granted
    Server->>Client: 200 OK (Token Valid)
    
    Note over Server: if token invalid or permissions denied:
    Server->>Client: 401 Unauthorized
Loading

Object Listing with Organization Context

sequenceDiagram
    participant Client
    participant Server
    participant DataStore
    
    Client->>Server: GET /list-objects
    Server->>DataStore: Fetch Objects(org_id)
    DataStore-->>Server: Object List
    Server->>Client: 200 OK (Object List)
    
    Note over Server: includes org_id in DataStore request
Loading

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@github-actions github-actions bot added the ☢️ Bug Something isn't working label Jun 27, 2024
@Subhra264 Subhra264 marked this pull request as ready for review June 27, 2024 11:26
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8c7f686 and a60e0c3.

Files selected for processing (1)
  • src/handler/http/auth/validator.rs (2 hunks)
Additional context used
Path-based instructions (1)
src/handler/http/auth/validator.rs (1)

Pattern **/*.rs: You are a smart rustlang pull request reviewer.
You are going to review all the rustlang files.
Be concise, and add a brief explanation to your suggestions

Make sure the responses are not too verbose and keep the suggestions to the point i.e. actionable.

Additional comments not posted (2)
src/handler/http/auth/validator.rs (2)

730-736: Approved: Incorporation of org_id in list_objects.

The addition of org_id to the function signature correctly extends the RBAC capabilities as intended by the PR. Ensure that all calls to this function have been updated to pass the new parameter.

Verification successful

Verified: All calls to list_objects and list_objects_for_user include the org_id parameter.

The search results confirm that all instances of list_objects and list_objects_for_user across the codebase have been updated to include the new org_id parameter, ensuring consistency and alignment with the updated function signature.

  • src/handler/http/auth/validator.rs
  • src/handler/http/request/dashboards/folders.rs
  • src/handler/http/request/stream/mod.rs
  • src/handler/http/request/dashboards/reports.rs
  • src/handler/http/request/functions/mod.rs
  • src/handler/http/request/pipelines.rs
  • src/handler/http/request/authz/fga.rs
  • src/handler/http/request/alerts/mod.rs
  • src/handler/http/request/alerts/templates.rs
  • src/handler/http/request/alerts/destinations.rs
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `list_objects` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type rust $'list_objects'

Length of output: 1556



Script:

#!/bin/bash
# Description: Verify that all calls to `list_objects` match the new signature.

# Extract lines around the matches to check the function call signature.
rg --type rust -A 3 -B 3 'list_objects' src/handler/http/auth/validator.rs

Length of output: 772



Script:

#!/bin/bash
# Description: Verify that all calls to `list_objects_for_user` match the updated signature.

# Extract lines around the matches to check the function call signature.
rg --type rust -A 3 -B 3 'list_objects_for_user'

Length of output: 6017


Line range hint 743-758: Approved: Updated list_objects_for_user to include org_id.

The function now correctly includes org_id to enhance role-based access control. This should help in fine-graining the access permissions based on organizational context.

@Subhra264 Subhra264 force-pushed the fix/resource_same_name_rbac branch from cdae9a7 to 88af905 Compare June 28, 2024 10:14
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a60e0c3 and 88af905.

Files selected for processing (1)
  • src/handler/http/auth/validator.rs (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/handler/http/auth/validator.rs

@Subhra264 Subhra264 force-pushed the fix/resource_same_name_rbac branch from 88af905 to f327e03 Compare June 28, 2024 11:46
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 88af905 and f327e03.

Files selected for processing (1)
  • src/handler/http/auth/validator.rs (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/handler/http/auth/validator.rs

@Subhra264 Subhra264 force-pushed the fix/resource_same_name_rbac branch from f327e03 to d80c816 Compare July 1, 2024 05:20
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f327e03 and d80c816.

Files selected for processing (1)
  • src/handler/http/auth/validator.rs (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/handler/http/auth/validator.rs

@Subhra264 Subhra264 force-pushed the fix/resource_same_name_rbac branch from d80c816 to d519b39 Compare July 2, 2024 07:52
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d80c816 and d519b39.

Files selected for processing (1)
  • src/handler/http/auth/validator.rs (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/handler/http/auth/validator.rs

@Subhra264 Subhra264 force-pushed the fix/resource_same_name_rbac branch from d519b39 to debb44b Compare July 2, 2024 11:03
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: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d519b39 and debb44b.

Files selected for processing (2)
  • src/handler/http/auth/token.rs (1 hunks)
  • src/handler/http/auth/validator.rs (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/handler/http/auth/validator.rs
Additional context used
Path-based instructions (1)
src/handler/http/auth/token.rs (1)

Pattern **/*.rs: You are a smart rustlang pull request reviewer.
You are going to review all the rustlang files.
Be concise, and add a brief explanation to your suggestions

Make sure the responses are not too verbose and keep the suggestions to the point i.e. actionable.

Additional comments not posted (3)
src/handler/http/auth/token.rs (3)

86-87: Improve code readability by renaming the variable.

Consider renaming the variable user to authenticated_user to improve code readability and make it clear that this variable represents an authenticated user.

- let user;
+ let authenticated_user;

88-88: Remove unnecessary comment.

The comment // / Hack for prometheus, need support POST and check the header is unclear and seems unnecessary. If it's important, consider rephrasing it for clarity.

- // / Hack for prometheus, need support POST and check the header
+ // Support for Prometheus: Ensure POST requests have the correct content type header

105-111: Improve authorization error handling.

The error message "Unauthorized Access" can be more descriptive to help with debugging and logging.

- Err((ErrorForbidden("Unauthorized Access"), req))
+ Err((ErrorForbidden("User does not have the required permissions"), req))

Comment on lines +102 to +103
header::HeaderName::from_static("user_id"),
header::HeaderValue::from_str(&res.0.user_email).unwrap(),
Copy link
Contributor

Choose a reason for hiding this comment

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

Handle potential errors when parsing the email.

The call to unwrap() can cause a panic if parsing the email fails. Consider using map_err to handle potential errors gracefully.

- header::HeaderValue::from_str(&res.0.user_email).unwrap(),
+ header::HeaderValue::from_str(&res.0.user_email).map_err(|e| {
+     log::error!("Failed to parse user email: {}", e);
+     ErrorUnauthorized("Invalid user email")
+ })?,
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
header::HeaderName::from_static("user_id"),
header::HeaderValue::from_str(&res.0.user_email).unwrap(),
header::HeaderName::from_static("user_id"),
header::HeaderValue::from_str(&res.0.user_email).map_err(|e| {
log::error!("Failed to parse user email: {}", e);
ErrorUnauthorized("Invalid user email")
})?,

@Subhra264 Subhra264 force-pushed the fix/resource_same_name_rbac branch from debb44b to f497d51 Compare July 2, 2024 11:15
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: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between debb44b and f497d51.

Files selected for processing (2)
  • src/handler/http/auth/token.rs (1 hunks)
  • src/handler/http/auth/validator.rs (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/handler/http/auth/validator.rs
Additional context used
Path-based instructions (1)
src/handler/http/auth/token.rs (1)

Pattern **/*.rs: You are a smart rustlang pull request reviewer.
You are going to review all the rustlang files.
Be concise, and add a brief explanation to your suggestions

Make sure the responses are not too verbose and keep the suggestions to the point i.e. actionable.

Additional comments not posted (2)
src/handler/http/auth/token.rs (2)

Line range hint 115-127: LGTM! Ensure proper error handling and security checks.

The function correctly retrieves the user's email from the token. Ensure that error handling and security checks are in place.


Line range hint 129-135: LGTM!

The function correctly handles the non-enterprise case by returning a "Not Supported" error.

Comment on lines +91 to +100
if req.method().eq(&Method::POST)
&& !req.headers().contains_key("content-type")
{
req.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(
"application/x-www-form-urlencoded",
),
);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Simplify header insertion logic.

The logic for inserting the content-type header can be simplified to improve readability.

- if req.method().eq(&Method::POST)
-     && !req.headers().contains_key("content-type")
- {
-     req.headers_mut().insert(
-         header::CONTENT_TYPE,
-         header::HeaderValue::from_static(
-             "application/x-www-form-urlencoded",
-         ),
-     );
- }
+ if req.method() == Method::POST && !req.headers().contains_key("content-type") {
+     req.headers_mut().insert(
+         header::CONTENT_TYPE,
+         header::HeaderValue::from_static("application/x-www-form-urlencoded"),
+     );
+ }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if req.method().eq(&Method::POST)
&& !req.headers().contains_key("content-type")
{
req.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(
"application/x-www-form-urlencoded",
),
);
}
if req.method() == Method::POST && !req.headers().contains_key("content-type") {
req.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/x-www-form-urlencoded"),
);
}

Comment on lines +86 to +113
match user {
Some(user) => {
// / Hack for prometheus, need support POST and check the header
let mut req = req;

if req.method().eq(&Method::POST) && !req.headers().contains_key("content-type")
{
if req.method().eq(&Method::POST)
&& !req.headers().contains_key("content-type")
{
req.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(
"application/x-www-form-urlencoded",
),
);
}
req.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/x-www-form-urlencoded"),
header::HeaderName::from_static("user_id"),
header::HeaderValue::from_str(&res.0.user_email).unwrap(),
);
if auth_info.bypass_check
|| check_permissions(user_id, auth_info, Some(user.role)).await
{
Ok(req)
} else {
Err((ErrorForbidden("Unauthorized Access"), req))
}
}
req.headers_mut().insert(
header::HeaderName::from_static("user_id"),
header::HeaderValue::from_str(&res.0.user_email).unwrap(),
);
// send user role as None as it applies only to internal users
if auth_info.bypass_check || check_permissions(user_id, auth_info, None).await {
Ok(req)
} else {
Err((ErrorForbidden("Unauthorized Access"), req))
}
} else {
Err((ErrorForbidden("Unauthorized Access"), req))
_ => Err((ErrorForbidden("Unauthorized Access"), req)),
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for user retrieval.

The unwrap() call on line 103 can cause a panic if parsing the email fails. Consider using map_err to handle potential errors gracefully.

- header::HeaderValue::from_str(&res.0.user_email).unwrap(),
+ header::HeaderValue::from_str(&res.0.user_email).map_err(|e| {
+     log::error!("Failed to parse user email: {}", e);
+     ErrorUnauthorized("Invalid user email")
+ })?,
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
match user {
Some(user) => {
// / Hack for prometheus, need support POST and check the header
let mut req = req;
if req.method().eq(&Method::POST) && !req.headers().contains_key("content-type")
{
if req.method().eq(&Method::POST)
&& !req.headers().contains_key("content-type")
{
req.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(
"application/x-www-form-urlencoded",
),
);
}
req.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/x-www-form-urlencoded"),
header::HeaderName::from_static("user_id"),
header::HeaderValue::from_str(&res.0.user_email).unwrap(),
);
if auth_info.bypass_check
|| check_permissions(user_id, auth_info, Some(user.role)).await
{
Ok(req)
} else {
Err((ErrorForbidden("Unauthorized Access"), req))
}
}
req.headers_mut().insert(
header::HeaderName::from_static("user_id"),
header::HeaderValue::from_str(&res.0.user_email).unwrap(),
);
// send user role as None as it applies only to internal users
if auth_info.bypass_check || check_permissions(user_id, auth_info, None).await {
Ok(req)
} else {
Err((ErrorForbidden("Unauthorized Access"), req))
}
} else {
Err((ErrorForbidden("Unauthorized Access"), req))
_ => Err((ErrorForbidden("Unauthorized Access"), req)),
match user {
Some(user) => {
// / Hack for prometheus, need support POST and check the header
let mut req = req;
if req.method().eq(&Method::POST)
&& !req.headers().contains_key("content-type")
{
req.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static(
"application/x-www-form-urlencoded",
),
);
}
req.headers_mut().insert(
header::HeaderName::from_static("user_id"),
header::HeaderValue::from_str(&res.0.user_email).map_err(|e| {
log::error!("Failed to parse user email: {}", e);
ErrorUnauthorized("Invalid user email")
})?,
);
if auth_info.bypass_check
|| check_permissions(user_id, auth_info, Some(user.role)).await
{
Ok(req)
} else {
Err((ErrorForbidden("Unauthorized Access"), req))
}
}
_ => Err((ErrorForbidden("Unauthorized Access"), req)),

@Subhra264 Subhra264 force-pushed the fix/resource_same_name_rbac branch from f497d51 to c6f3b23 Compare July 3, 2024 05:46
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f497d51 and c6f3b23.

Files selected for processing (2)
  • src/handler/http/auth/token.rs (1 hunks)
  • src/handler/http/auth/validator.rs (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • src/handler/http/auth/token.rs
  • src/handler/http/auth/validator.rs

@Subhra264 Subhra264 force-pushed the fix/resource_same_name_rbac branch from c6f3b23 to 097da7e Compare July 4, 2024 05:14
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c6f3b23 and 097da7e.

Files selected for processing (2)
  • src/handler/http/auth/token.rs (1 hunks)
  • src/handler/http/auth/validator.rs (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • src/handler/http/auth/token.rs
  • src/handler/http/auth/validator.rs

@Subhra264 Subhra264 force-pushed the fix/resource_same_name_rbac branch from 097da7e to 0478f8b Compare July 4, 2024 06:57
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 097da7e and 0478f8b.

Files selected for processing (2)
  • src/handler/http/auth/token.rs (1 hunks)
  • src/handler/http/auth/validator.rs (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • src/handler/http/auth/token.rs
  • src/handler/http/auth/validator.rs

@Subhra264 Subhra264 merged commit 974a61b into main Jul 4, 2024
@Subhra264 Subhra264 deleted the fix/resource_same_name_rbac branch July 4, 2024 07:16
taimingl pushed a commit that referenced this pull request Jul 12, 2024
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Enhanced authentication and authorization handling for user requests
with more efficient token validation.
- **Bug Fixes**
- Improved error handling and response based on user permissions and
authorization status.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@coderabbitai coderabbitai bot mentioned this pull request Nov 4, 2024
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