Skip to content

Conversation

@MihailoPlavsic34
Copy link

@MihailoPlavsic34 MihailoPlavsic34 commented Nov 27, 2025

Description

Fixes #4979.

TODOs

Read the Gruntwork contribution guidelines.

  • I authored this code entirely myself
  • I am submitting code based on open source software (e.g. MIT, MPL-2.0, Apache)]
  • Run the relevant tests successfully, including pre-commit checks.

Release Notes (draft)

Updated aws-creds-helper logic to return pre v0.85.1 behavior.

Summary by CodeRabbit

  • Bug Fixes

    • Adjusted AWS credential resolution so role/STS-based credentials take precedence when a Role ARN is configured; environment credentials are used only when no Role ARN is present.
  • Tests

    • Added tests verifying credential selection: role/STS preference when Role ARN exists, and env credentials used when it does not.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Nov 27, 2025

Someone is attempting to deploy a commit to the Gruntwork Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 27, 2025

Warning

Rate limit exceeded

@MihailoPlavsic34 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 10 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between e099148 and 1c54901.

📒 Files selected for processing (2)
  • internal/awshelper/config.go (1 hunks)
  • internal/awshelper/config_test.go (1 hunks)
📝 Walkthrough

Walkthrough

Move the early environment-credentials short-circuit in CreateAwsConfig so IAM role assumption and web-identity credential assembly occur before returning env-based credentials; env creds are only returned immediately when no RoleARN is present and env creds exist.

Changes

Cohort / File(s) Summary
Credential precedence logic
internal/awshelper/config.go
Reordered credential resolution: removed unconditional early return for environment credentials; assemble IAM role/STS and web-identity options first, then conditionally return env creds only when no RoleARN is configured and env creds exist.
Test coverage
internal/awshelper/config_test.go
Added tests TestAwsConfigRoleArnTakesPrecedenceOverEnvCredentials and TestAwsConfigUsesEnvCredentialsWhenNoRoleArn to verify precedence between RoleARN-based assumption and environment credentials.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Files needing extra attention:
    • internal/awshelper/config.go — verify control-flow changes correctly preserve STS/web-identity credential assembly and that conditionals for RoleARN/env detection are correct.
    • internal/awshelper/config_test.go — ensure the new tests reliably assert precedence and are deterministic across environments (mocking/isolating env vars).

Suggested reviewers

  • denis256
  • yhakbar

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'fix: Addresses bug #4979' is vague and generic, using 'Addresses bug' which doesn't convey the specific nature of the fix related to AWS credential precedence. Revise the title to be more specific about what bug is being fixed, such as 'fix: Restore environment credentials precedence in AWS config when no RoleARN is present' to better convey the actual change.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The description covers key sections with issue reference, authorship confirmations, and test execution checkmarks, but lacks specific explanation of the technical changes introduced.
Linked Issues check ✅ Passed The code changes properly restore credential precedence logic to fix issue #4979, where environment credentials should be used when no RoleARN is present, matching the expected behavior described in the linked issue.
Out of Scope Changes check ✅ Passed All changes in config.go and config_test.go are directly related to fixing the credential resolution order issue described in #4979; no out-of-scope modifications were detected.

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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)
internal/awshelper/config_test.go (1)

153-182: Test coverage gap: bug #4979 scenario not directly tested.

Bug #4979 involves the backend's assume_role.role_arn (passed via awsCfg.RoleArn in AwsSessionConfig) not being used when env credentials exist. This test sets opts.IAMRoleOptions.RoleARN, which tests a different code path in getMergedIAMRoleOptions.

Consider adding a complementary test that passes the RoleARN via AwsSessionConfig.RoleArn to validate the exact scenario from the bug report.

func TestAwsConfigBackendRoleArnTakesPrecedenceOverEnvCredentials(t *testing.T) {
	t.Parallel()

	l := logger.CreateLogger()
	ctx := context.Background()

	opts := &options.TerragruntOptions{
		Env: map[string]string{
			"AWS_ACCESS_KEY_ID":     "test-access-key",
			"AWS_SECRET_ACCESS_KEY": "test-secret-key",
		},
	}

	// Simulate backend assume_role config (bug #4979 scenario)
	awsCfg := &awshelper.AwsSessionConfig{
		RoleArn: "arn:aws:iam::123456789012:role/backend-role",
	}

	cfg, err := awshelper.CreateAwsConfig(ctx, l, awsCfg, opts)
	require.NoError(t, err)
	assert.NotNil(t, cfg.Credentials)

	_, err = cfg.Credentials.Retrieve(ctx)
	assert.Error(t, err) // Role doesn't exist, proving assumption was attempted
}
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3f8b187 and 9602547.

📒 Files selected for processing (2)
  • internal/awshelper/config.go (1 hunks)
  • internal/awshelper/config_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

⚙️ CodeRabbit configuration file

Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

Files:

  • internal/awshelper/config_test.go
  • internal/awshelper/config.go
🧬 Code graph analysis (1)
internal/awshelper/config_test.go (2)
test/helpers/logger/logger.go (1)
  • CreateLogger (9-14)
internal/awshelper/config.go (1)
  • CreateAwsConfig (86-148)
🔇 Additional comments (1)
internal/awshelper/config_test.go (1)

186-210: LGTM!

The test correctly validates that environment credentials are used directly when no RoleARN is specified, and verifies the exact credential values match the environment input.

@MihailoPlavsic34 MihailoPlavsic34 force-pushed the bug/credential-return-order-aws-helper-4979 branch from 9602547 to 5507d83 Compare November 27, 2025 16:48
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

♻️ Duplicate comments (1)
internal/awshelper/config.go (1)

145-147: Dead code: conditional check has no effect.

This is the same issue flagged in the previous review. Both branches return cfg, nil with identical STS credentials already set at line 142. The createCredentialsFromEnv(opts) check does not alter the returned configuration.

As suggested in the previous review, remove the no-op conditional:

 	l.Debugf("Assuming role %s", iamRoleOptions.RoleARN)
 	cfg.Credentials = getSTSCredentialsFromIAMRoleOptions(cfg, iamRoleOptions, getExternalID(awsCfg))
 
-	if createCredentialsFromEnv(opts) != nil {
-		return cfg, nil
-	}
-
 	return cfg, nil
🧹 Nitpick comments (1)
internal/awshelper/config.go (1)

140-143: Remove redundant condition.

The check if iamRoleOptions.RoleARN != "" at line 140 is redundant because lines 129-131 already return early when RoleARN is empty. By the time execution reaches line 140, RoleARN is guaranteed to be non-empty.

Apply this diff to remove the unnecessary nesting:

-	if iamRoleOptions.RoleARN != "" {
-		l.Debugf("Assuming role %s", iamRoleOptions.RoleARN)
-		cfg.Credentials = getSTSCredentialsFromIAMRoleOptions(cfg, iamRoleOptions, getExternalID(awsCfg))
-	}
+	l.Debugf("Assuming role %s", iamRoleOptions.RoleARN)
+	cfg.Credentials = getSTSCredentialsFromIAMRoleOptions(cfg, iamRoleOptions, getExternalID(awsCfg))
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9602547 and 5507d83.

📒 Files selected for processing (2)
  • internal/awshelper/config.go (1 hunks)
  • internal/awshelper/config_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

⚙️ CodeRabbit configuration file

Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

Files:

  • internal/awshelper/config_test.go
  • internal/awshelper/config.go
🧬 Code graph analysis (2)
internal/awshelper/config_test.go (2)
internal/awshelper/config.go (1)
  • CreateAwsConfig (86-150)
internal/runner/run/creds/providers/provider.go (1)
  • Credentials (16-19)
internal/awshelper/config.go (2)
pkg/log/log.go (1)
  • Debugf (72-74)
internal/runner/run/creds/providers/provider.go (1)
  • Credentials (16-19)
🔇 Additional comments (2)
internal/awshelper/config_test.go (2)

153-182: Test appropriately validates RoleARN precedence.

This test correctly validates the fix for issue #4979 by ensuring that when both environment credentials and a RoleARN are present, the RoleARN configuration takes precedence. The expectation of an error from Retrieve (because the test role doesn't exist) demonstrates that role assumption was attempted rather than falling back to environment credentials.


186-210: Test correctly validates environment credential fallback.

This test appropriately verifies that environment credentials are used directly when no RoleARN is specified, confirming the expected fallback behavior.

@MihailoPlavsic34 MihailoPlavsic34 force-pushed the bug/credential-return-order-aws-helper-4979 branch from 5507d83 to e099148 Compare November 27, 2025 16: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

🧹 Nitpick comments (1)
internal/awshelper/config.go (1)

130-132: Redundant conditional - both branches return the same result.

Lines 130-132 check for env credentials, but both the if branch (line 131) and the fallthrough (line 133) return cfg, nil with identical state. At this point, cfg already contains env credentials from line 123 (loaded via config.LoadDefaultConfig with env credentials added to configOptions at line 99). The check has no side effects and doesn't alter behavior.

Apply this diff to simplify:

 	iamRoleOptions := getMergedIAMRoleOptions(awsCfg, opts)
 	if iamRoleOptions.RoleARN == "" {
-		if createCredentialsFromEnv(opts) != nil {
-			return cfg, nil
-		}
 		return cfg, nil
 	}
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5507d83 and e099148.

📒 Files selected for processing (2)
  • internal/awshelper/config.go (1 hunks)
  • internal/awshelper/config_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

⚙️ CodeRabbit configuration file

Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

Files:

  • internal/awshelper/config_test.go
  • internal/awshelper/config.go
🧬 Code graph analysis (1)
internal/awshelper/config_test.go (3)
test/helpers/logger/logger.go (1)
  • CreateLogger (9-14)
options/options.go (2)
  • TerragruntOptions (99-329)
  • IAMRoleOptions (349-354)
internal/awshelper/config.go (1)
  • CreateAwsConfig (86-147)
🔇 Additional comments (3)
internal/awshelper/config.go (1)

129-147: Fix correctly addresses issue #4979 - RoleARN now takes precedence over env credentials.

The repositioning of the env-credentials check inside the RoleARN == "" block ensures that when a backend role is configured (e.g., ROLE_B in the issue), it takes precedence and is used for state fetching, even when environment credentials are present. Previously, env credentials would short-circuit before role assumption logic, causing the backend role to be ignored.

The flow is now:

  • RoleARN set: skip lines 130-133, proceed to STS/WebIdentity role assumption (lines 136-146) using env creds as initial credentials
  • RoleARN empty: return cfg with env creds (already configured at line 123)

This restores the expected behavior where backend role configuration is honored.

internal/awshelper/config_test.go (2)

151-182: Test correctly validates RoleARN precedence over env credentials.

The test verifies that when both env credentials and a RoleARN are present, the role assumption path is taken (not static env credentials). The error from Retrieve() confirms an STS AssumeRole call was attempted, which would fail for the non-existent test role. If env credentials were used directly, no error would occur.

Note: This test makes a real AWS STS API call (due to the //go:build aws tag), which is consistent with the integration test pattern in this file but may require AWS connectivity in CI.


184-210: Test correctly validates env credentials are used when no RoleARN is specified.

The test confirms that when only env credentials are present (no RoleARN), the static credentials provider is used and returns the expected access key and secret key values without making external API calls. This validates the complementary behavior to the precedence test.

@MihailoPlavsic34 MihailoPlavsic34 force-pushed the bug/credential-return-order-aws-helper-4979 branch from e099148 to 1c54901 Compare November 27, 2025 17:08
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.

TG_DEPENDENCY_FETCH_OUTPUT_FROM_STATE does not use backend role to fetch state

1 participant