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

Add loadConfig S3 based on AWS_PROFILE ~/.aws/credentials #5680

Conversation

alban-stourbe-wmx
Copy link
Contributor

@alban-stourbe-wmx alban-stourbe-wmx commented Oct 1, 2024

Proposed changes

To retrieve a S3 bucket based on a loacConfid, i have added a feature allowing to use AWS_PROFILE from ~/.aws/credentials file.

The aim is to be able to use the profile option from aws cli like
aws s3 ls --profile my-profile

Checklist

  • Pull request is created against the dev branch
  • All checks passed (lint, unit/integration/regression tests etc.) with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Summary by CodeRabbit

  • New Features
    • Added support for configuring AWS credentials via an AWS profile (using the AWS_PROFILE environment variable) for S3 operations.
    • Improved validation of AWS settings to offer clearer error messages when required credentials or configurations are missing.
    • Enhanced the S3 client initialization to accept an AWS profile parameter for more flexible credential management.

@auto-assign auto-assign bot requested a review from dogancanbakir October 1, 2024 09:47
@GeorginaReeder
Copy link

Thanks for your contribution @alban-stourbe-wmx ! :)

@dogancanbakir
Copy link
Member

Could you please merge the dev branch into this one to verify if all tests are passing? Thank you!

@alban-stourbe-wmx alban-stourbe-wmx force-pushed the feature/add-aws-profile-from-aws-credentials branch from 1649ff5 to e35c604 Compare March 24, 2025 16:17
Copy link
Contributor

coderabbitai bot commented Mar 24, 2025

Walkthrough

The changes enhance AWS S3 credential handling across the application. The validation logic now first checks if the AWS profile is provided before verifying the access key, secret key, and region. An environment variable is read for the AWS profile, and the S3 client creation now supports using a specified profile when loading the configuration. Additionally, the Options struct has been extended to include the AWS profile information.

Changes

File(s) Change Summary
internal/runner/options.go Refactored validateMissingS3Options to first check if AwsProfile is empty before validating AwsAccessKey, AwsSecretKey, and AwsRegion. Added reading of AWS_PROFILE in readEnvInputVars.
pkg/external/customtemplates/s3.go Updated getS3Client to accept a new profile parameter. The function now loads AWS configuration based on the presence of a profile, or falls back to using credentials and region. Updated NewS3Providers accordingly.
pkg/types/types.go Added a new field AwsProfile string to the Options struct, enabling AWS profile configuration for S3 template downloads.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant S3Client as getS3Client
    participant AWSConfig

    Caller->>S3Client: call getS3Client(ctx, accessKey, secretKey, region, profile)
    alt Profile Provided
        S3Client->>AWSConfig: load configuration using profile
    else Profile Empty
        alt Credentials Provided
            S3Client->>AWSConfig: load configuration using accessKey, secretKey and region
        else No Credentials
            S3Client->>AWSConfig: load default configuration
        end
    end
    S3Client-->>Caller: Return S3 client or error
Loading
sequenceDiagram
    participant Caller
    participant Validator as validateMissingS3Options

    Caller->>Validator: call with AWS options
    alt AwsProfile is empty
        Validator->>Validator: Check AwsAccessKey, AwsSecretKey, AwsRegion
        alt Individual Field Missing
            Validator->>Validator: Append respective error message(s)
        end
        alt All Fields Missing
            Validator->>Validator: Append error message for AWS_PROFILE
        end
    else
        Validator->>Validator: Skip credential error for provided AwsProfile
    end
    Validator-->>Caller: Return errors (if any)
Loading

Poem

I'm a little rabbit hopping in the code,
Finding new paths in every node.
AWS profiles now lead the way,
Guiding S3 calls without delay.
I nibble bugs with flair and cheer,
Celebrating changes—oh so dear!
🐇💻 Hoppy coding to all, far and near!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between e35c604 and 3280136.

📒 Files selected for processing (1)
  • internal/runner/options.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Tests (macOS-latest)
  • GitHub Check: Tests (windows-latest)
  • GitHub Check: Tests (ubuntu-latest)
🔇 Additional comments (2)
internal/runner/options.go (2)

238-255: Refactor the validation logic to improve clarity.

The implementation correctly enables using either AWS_PROFILE or individual AWS credentials. However, the logic could be made clearer by restructuring how AWS_PROFILE is added to the missing list.

Consider this alternative implementation that would make the validation logic more intuitive:

if options.AwsProfile == "" {
    var missingCreds []string
    if options.AwsAccessKey == "" {
        missingCreds = append(missingCreds, "AWS_ACCESS_KEY")
    }
    if options.AwsSecretKey == "" {
        missingCreds = append(missingCreds, "AWS_SECRET_KEY")
    }
    if options.AwsRegion == "" {
        missingCreds = append(missingCreds, "AWS_REGION")
    }

    missing = append(missing, missingCreds...)

-    if len(missingCreds) > 0 {
-        missing = append(missing, "AWS_PROFILE")
+    // If any credential is missing, suggest using AWS_PROFILE as an alternative
+    if len(missingCreds) > 0 && !sliceContains(missing, "AWS_PROFILE") {
+        missing = append(missing, "AWS_PROFILE")
    }
}

The original PR author should also consider implementing the suggestion from the previous review to move this under the first condition.


462-462: LGTM: AWS_PROFILE environment variable is now properly supported.

This change correctly reads the AWS_PROFILE environment variable, which allows users to use AWS profiles from ~/.aws/credentials as requested in the PR.


🪧 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

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)
pkg/external/customtemplates/s3.go (1)

107-125: Consider documenting credential precedence

The implementation correctly checks for different authentication methods in order of precedence (profile first, then access/secret keys, then default config). Consider adding a brief comment to clarify this order for future maintenance.

 func getS3Client(ctx context.Context, accessKey string, secretKey string, region string, profile string) (*s3.Client, error) {
+	// Authentication precedence:
+	// 1. AWS Profile (if provided)
+	// 2. Static credentials (if access key and secret key are provided)
+	// 3. Default AWS credential chain
 	var cfg aws.Config
 	var err error
 	if profile != "" {
internal/runner/options.go (1)

238-251: Consider improving validation clarity

The validation logic correctly checks for either the AWS profile or the combination of other AWS credentials, but the error messaging could be improved for clarity.

 	if options.AwsProfile == "" {
 		if options.AwsAccessKey == "" {
 			missing = append(missing, "AWS_ACCESS_KEY")
 		}
 		if options.AwsSecretKey == "" {
 			missing = append(missing, "AWS_SECRET_KEY")
 		}
 		if options.AwsRegion == "" {
 			missing = append(missing, "AWS_REGION")
 		}
 	}
-	if (options.AwsAccessKey == "" || options.AwsSecretKey == "" || options.AwsRegion == "") && options.AwsProfile == "" {
-		missing = append(missing, "AWS_PROFILE")
+	// If we have neither valid profile nor complete credentials, suggest both options
+	if options.AwsProfile == "" && (options.AwsAccessKey == "" || options.AwsSecretKey == "" || options.AwsRegion == "") {
+		missing = append(missing, "Either AWS_PROFILE or complete AWS credentials (AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_REGION)")
 	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 04a6c82 and e35c604.

📒 Files selected for processing (3)
  • internal/runner/options.go (2 hunks)
  • pkg/external/customtemplates/s3.go (2 hunks)
  • pkg/types/types.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Tests (macOS-latest)
  • GitHub Check: Tests (windows-latest)
  • GitHub Check: Tests (ubuntu-latest)
🔇 Additional comments (3)
pkg/types/types.go (1)

348-349: LGTM: New AWS profile field added correctly

The added AwsProfile field with proper documentation allows users to leverage AWS profiles stored in ~/.aws/credentials, which is a standard pattern for AWS authentication.

pkg/external/customtemplates/s3.go (1)

65-65: LGTM: Correctly passing the new AwsProfile parameter

The call to getS3Client has been updated to include the new profile parameter.

internal/runner/options.go (1)

458-458: LGTM: Environment variable correctly read

The code properly reads the AWS_PROFILE environment variable.

@alban-stourbe-wmx
Copy link
Contributor Author

@dogancanbakir i have merge into dev can u approve it please ? If it is okay for u

@dogancanbakir dogancanbakir merged commit b833bc9 into projectdiscovery:dev Mar 25, 2025
20 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.

4 participants