Skip to content
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

fix(clp-package): Add support for loading credentials from boto3 session. #681

Closed
wants to merge 1 commit into from

Conversation

haiqi96
Copy link
Contributor

@haiqi96 haiqi96 commented Jan 20, 2025

Description

Validation performed

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a new function to retrieve frozen AWS credentials
    • Enhanced credential management for S3 access across multiple components
  • Improvements

    • Improved error handling for AWS credential retrieval
    • Added more robust session credential loading mechanism
    • Updated command generation processes to handle missing credentials gracefully
  • Bug Fixes

    • Resolved potential issues with AWS authentication in various tasks
    • Added fallback mechanisms for credential retrieval

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Walkthrough

This pull request introduces enhancements to AWS credential management across multiple components of the job orchestration system. The changes focus on improving the handling of S3 credentials by adding a new function s3_get_frozen_credentials() in the S3 utilities module and implementing a new load_session_credentials() function in the executor utils. The modifications provide more robust error handling and dynamic credential retrieval mechanisms for S3 operations across different tasks like compression, stream extraction, and file system search.

Changes

File Change Summary
components/clp-py-utils/clp_py_utils/s3_utils.py Added s3_get_frozen_credentials() function to retrieve frozen AWS credentials
components/job-orchestration/job_orchestration/executor/compress/compression_task.py Updated credential handling in make_clp_s_command_and_env(), modified return type to support optional command generation
components/job-orchestration/job_orchestration/executor/query/extract_stream_task.py Added imports for credential-related functions, enhanced AWS credential retrieval
components/job-orchestration/job_orchestration/executor/query/fs_search_task.py Added load_session_credentials import, improved AWS credential loading logic
components/job-orchestration/job_orchestration/executor/utils.py Introduced load_session_credentials() function for dynamic credential retrieval

Sequence Diagram

sequenceDiagram
    participant Task as Execution Task
    participant Utils as load_session_credentials()
    participant S3Utils as s3_get_frozen_credentials()
    
    Task->>Utils: Request AWS credentials
    Utils->>S3Utils: Attempt to retrieve credentials
    alt Credentials Found
        S3Utils-->>Utils: Return Credentials
        Utils-->>Task: Provide Credentials
    else No Credentials
        S3Utils-->>Utils: Return None
        Utils-->>Task: Return None
    end
Loading

Possibly Related PRs

Suggested Reviewers

  • kirkrodrigues
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

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. (Beta)
  • @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.

@haiqi96 haiqi96 changed the title temp fix(clp-package): Add support for loading credentials from boto3 session. Jan 20, 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: 5

🧹 Nitpick comments (2)
components/job-orchestration/job_orchestration/executor/utils.py (2)

30-30: Improve error message clarity without exposing sensitive information.

The current error messages could be more descriptive while maintaining security. Consider including troubleshooting guidance.

Apply this diff:

-        logger.error("Failed to get s3 credentials from local session")
+        logger.error("Unable to load AWS credentials. Verify AWS configuration is properly set up.")
-        logger.error("Not supporting session token at the moment")
+        logger.error("Temporary session credentials are not supported. Use long-term credentials instead.")

Also applies to: 33-33


27-35: Consider adding retry mechanism for transient failures.

The function could benefit from retrying the credential fetch operation in case of temporary AWS connectivity issues.

Consider implementing an exponential backoff retry mechanism using the tenacity library. Would you like me to provide an example implementation?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ba63a76 and f8d5aea.

📒 Files selected for processing (5)
  • components/clp-py-utils/clp_py_utils/s3_utils.py (2 hunks)
  • components/job-orchestration/job_orchestration/executor/compress/compression_task.py (4 hunks)
  • components/job-orchestration/job_orchestration/executor/query/extract_stream_task.py (2 hunks)
  • components/job-orchestration/job_orchestration/executor/query/fs_search_task.py (2 hunks)
  • components/job-orchestration/job_orchestration/executor/utils.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: lint-check (ubuntu-latest)
🔇 Additional comments (2)
components/job-orchestration/job_orchestration/executor/compress/compression_task.py (1)

287-291: LGTM!

The added error handling for the compression command is consistent with the function's error handling pattern.

components/job-orchestration/job_orchestration/executor/utils.py (1)

3-3: LGTM! Import statements are well-organized.

The new imports are properly organized and necessary for the added functionality.

Also applies to: 7-7

Comment on lines +65 to +71
def s3_get_frozen_credentials() -> Optional[ReadOnlyCredentials]:
session = boto3.Session()
credentials = session.get_credentials()
if credentials is None:
return None
frozen_credentials = credentials.get_frozen_credentials()
return frozen_credentials
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling and logging.

The function should handle potential boto3 exceptions and log appropriate messages when credentials are not found.

Apply this diff to improve error handling:

 def s3_get_frozen_credentials() -> Optional[ReadOnlyCredentials]:
+    try:
         session = boto3.Session()
         credentials = session.get_credentials()
         if credentials is None:
+            logger.warning("No AWS credentials found in the session")
             return None
         frozen_credentials = credentials.get_frozen_credentials()
         return frozen_credentials
+    except Exception as ex:
+        logger.error(f"Failed to get AWS credentials: {ex}")
+        return None

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +76 to +79
aws_access_key_id, aws_access_key_id = load_session_credentials(logger)
if aws_access_key_id is None or aws_secret_access_key is None:
return None, None

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the credential variable assignment bug.

There is a bug in the variable assignment where both variables are assigned the access key ID.

Apply this diff to fix the variable assignment:

-            aws_access_key_id, aws_access_key_id = load_session_credentials(logger)
+            aws_access_key_id, aws_secret_access_key = load_session_credentials(logger)
📝 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
aws_access_key_id, aws_access_key_id = load_session_credentials(logger)
if aws_access_key_id is None or aws_secret_access_key is None:
return None, None
aws_access_key_id, aws_secret_access_key = load_session_credentials(logger)
if aws_access_key_id is None or aws_secret_access_key is None:
return None, None

Comment on lines +110 to +113
aws_access_key_id, aws_access_key_id = load_session_credentials(logger)
if aws_access_key_id is None or aws_secret_access_key is None:
return None, None

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the credential variable assignment bug.

There is a bug in the variable assignment where both variables are assigned the access key ID.

Apply this diff to fix the variable assignment:

-            aws_access_key_id, aws_access_key_id = load_session_credentials(logger)
+            aws_access_key_id, aws_secret_access_key = load_session_credentials(logger)
📝 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
aws_access_key_id, aws_access_key_id = load_session_credentials(logger)
if aws_access_key_id is None or aws_secret_access_key is None:
return None, None
aws_access_key_id, aws_secret_access_key = load_session_credentials(logger)
if aws_access_key_id is None or aws_secret_access_key is None:
return None, None

Comment on lines +189 to +195
aws_access_key_id = clp_config.input.aws_access_key_id
aws_secret_access_key = clp_config.input.aws_secret_access_key
if aws_access_key_id is None or aws_secret_access_key is None:
aws_access_key_id, aws_access_key_id = load_session_credentials(logger)
if aws_access_key_id is None or aws_secret_access_key is None:
return None, None

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the credential variable assignment bug.

There is a bug in the variable assignment where both variables are assigned the access key ID.

Apply this diff to fix the variable assignment:

-            aws_access_key_id, aws_access_key_id = load_session_credentials(logger)
+            aws_access_key_id, aws_secret_access_key = load_session_credentials(logger)
📝 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
aws_access_key_id = clp_config.input.aws_access_key_id
aws_secret_access_key = clp_config.input.aws_secret_access_key
if aws_access_key_id is None or aws_secret_access_key is None:
aws_access_key_id, aws_access_key_id = load_session_credentials(logger)
if aws_access_key_id is None or aws_secret_access_key is None:
return None, None
aws_access_key_id = clp_config.input.aws_access_key_id
aws_secret_access_key = clp_config.input.aws_secret_access_key
if aws_access_key_id is None or aws_secret_access_key is None:
aws_access_key_id, aws_secret_access_key = load_session_credentials(logger)
if aws_access_key_id is None or aws_secret_access_key is None:
return None, None

Comment on lines +27 to +35
def load_session_credentials(logger: Logger) -> Tuple[Optional[str], Optional[str]]:
s3_frozen_credentials = s3_get_frozen_credentials()
if s3_frozen_credentials is None:
logger.error("Failed to get s3 credentials from local session")
return None, None
if s3_frozen_credentials.token is not None:
logger.error("Not supporting session token at the moment")
return None, None
return s3_frozen_credentials.access_key, s3_frozen_credentials.secret_key
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add comprehensive docstring with type hints.

The function lacks documentation explaining its purpose, parameters, return values, and possible error conditions.

Add a docstring following this pattern:

 def load_session_credentials(logger: Logger) -> Tuple[Optional[str], Optional[str]]:
+    """
+    Load AWS credentials from the current session.
+    
+    Args:
+        logger: Logger instance for error reporting
+    
+    Returns:
+        Tuple[Optional[str], Optional[str]]: A tuple containing (access_key, secret_key).
+        Both values will be None if credentials cannot be loaded or contain unsupported features.
+    """
📝 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
def load_session_credentials(logger: Logger) -> Tuple[Optional[str], Optional[str]]:
s3_frozen_credentials = s3_get_frozen_credentials()
if s3_frozen_credentials is None:
logger.error("Failed to get s3 credentials from local session")
return None, None
if s3_frozen_credentials.token is not None:
logger.error("Not supporting session token at the moment")
return None, None
return s3_frozen_credentials.access_key, s3_frozen_credentials.secret_key
def load_session_credentials(logger: Logger) -> Tuple[Optional[str], Optional[str]]:
"""
Load AWS credentials from the current session.
Args:
logger: Logger instance for error reporting
Returns:
Tuple[Optional[str], Optional[str]]: A tuple containing (access_key, secret_key).
Both values will be None if credentials cannot be loaded or contain unsupported features.
"""
s3_frozen_credentials = s3_get_frozen_credentials()
if s3_frozen_credentials is None:
logger.error("Failed to get s3 credentials from local session")
return None, None
if s3_frozen_credentials.token is not None:
logger.error("Not supporting session token at the moment")
return None, None
return s3_frozen_credentials.access_key, s3_frozen_credentials.secret_key

@haiqi96 haiqi96 closed this Jan 20, 2025
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