Skip to content

chore: fix golanglint findings - #96

Open
RoseSecurity wants to merge 7 commits into
mainfrom
fix-golanglint-findings
Open

RoseSecurity wants to merge 7 commits into
mainfrom
fix-golanglint-findings

Conversation

@RoseSecurity

Copy link
Copy Markdown
Member

what

This PR resolves all actionable golangci-lint findings across the provider, reducing issues from 633 to 77 (the remaining 77 are unused findings that were intentionally excluded from scope). Fixes span whitespace, godot, errcheck, err113, staticcheck, revive, gocritic, gosec, tparallel, forbidigo, and gofumpt categories. Error handling was modernized to use sentinel errors with %w wrapping, deprecated Terraform Plugin SDK calls (ImportStatePassthrough, WaitForState, resource.Retry) were migrated to their context-aware equivalents, and math/rand.Seed usage was replaced with rand.New(rand.NewSource(...)). The .golangci.yml config was also tuned to set realistic thresholds for a Terraform provider (funlen, cyclop, gocognit, nestif, revive cyclomatic/cognitive-complexity) and to drop the os.Getenv forbid rule that was inappropriately copied from an atmos config targeting viper.

why

The repository had accumulated a large backlog of lint findings that made it difficult to spot new issues and signaled inconsistent code quality. Addressing them produces a clean baseline so future PRs start from zero noise, surfaces real issues (deprecated APIs, dynamic errors, missing context propagation) rather than letting them rot, and brings the codebase in line with modern Go and Terraform Plugin SDK v2 conventions. Relaxing a handful of complexity thresholds in .golangci.yml reflects the reality that provider schema and client-wiring functions are inherently long and branch-heavy, so the limits now target actual hotspots instead of fighting the framework.

- Add trailing periods to comments for Go documentation consistency
- Fix redundant boolean comparison in CheckResourceAttrGreaterThanValue
- Remove unnecessary blank lines in ip_ranges_data_source.go
- Remove unnecessary blank line in organization_data_source.go

These changes address golangci-lint findings for improved code style
and documentation formatting across the codebase.
Add explicit error checking for all schema.ResourceData.Set() calls
that were previously ignoring return values. This addresses Go linter
warnings about unchecked errors and ensures proper error propagation
when setting resource attributes fails.

Changes across multiple files:
- internal/conns/conns.go
- internal/create/attrmap.go
- internal/service/iam/access_key.go
- internal/service/macie2/resource_macie2_organization_settings.go
- internal/service/meta/*.go
- internal/service/organizations/*.go
- internal/service/securityhub/resource_organization_settings.go
- internal/service/sts/caller_identity_data_source.go
Update fmt.Errorf calls throughout the codebase to use %w verb
instead of %s for error wrapping. This follows Go 1.13+ best
practices and enables proper error unwrapping with errors.Is()
and errors.As().

Changes include:
- Replace %s with %w in fmt.Errorf for error arguments
- Add sentinel errors for specific error conditions
- Import errors package where needed for errors.New()
Replace string-based error creation with predefined sentinel errors
across the codebase to enable proper error checking with errors.Is()
and errors.As(). This improves error handling consistency and allows
callers to programmatically identify specific error conditions.

Changes include:
- Add sentinel error variables in multiple packages
- Update fmt.Errorf calls to wrap sentinel errors with %w
- Convert simple error strings to predefined error variables
- Maintain backward-compatible error messages with additional context
- Add nolint:staticcheck comments for deprecated SDK APIs that are
  intentionally retained for backwards compatibility
- Convert error messages to lowercase for Go conventions
- Replace fmt.Errorf string formatting with sentinel errors wrapped
  via %w for better error handling and testability
- Use context-aware retry functions (RetryContext, WaitForStateContext)
  instead of deprecated non-context variants
- Replace deprecated rand.Seed with local rand.Source for thread safety
- Update schema importers to use StateContext variant
- Expand allowInts and allowStrs in add-constant linter config to
  reduce false positives for common AWS resource attribute names
- Increase maxLitCount from 3 to 5 for add-constant rule
- Relax complexity and length thresholds in .golangci.yml to
  accommodate existing codebase patterns
- Extract magic numbers into named constants for validation
  functions and error format strings
- Add nolint directives with explanations for intentional
  patterns (SHA-1 for X.509, interface signatures, jitter)
- Convert if-else chains to switch statements where appropriate
- Use compound assignment operators (^=, &^=) for cleaner code
- Fix variable alignment in error declarations
- Add t.Parallel() to table-driven test subtests
- Remove os.Getenv forbidigo rule (viper not used in this fork)
@RoseSecurity
RoseSecurity requested review from a team as code owners April 7, 2026 18:46
@RoseSecurity RoseSecurity changed the title Fix golanglint findings chore: fix golanglint findings Apr 7, 2026
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d0c0064b-8cfb-435f-b67f-87e723bac2d8

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR refactors error handling throughout the codebase by introducing shared sentinel errors and replacing string formatting with error wrapping (%w). It adjusts linter thresholds, adds missing doc comment punctuation, introduces explicit error handling for previously ignored d.Set() operations, and updates functions to use context-aware APIs.

Changes

Cohort / File(s) Summary
Linter Configuration
.golangci.yml
Adjusted complexity/size thresholds: increased cyclop.max-complexity (15→25), gocognit.min-complexity (20→50), nestif.min-complexity (4→13); expanded funlen limits (60→260 lines, 40→150 statements); relaxed revive rules for file/function length and cognitive complexity; widened add-constant allowances; removed forbidigo rule for os.Getenv.
Core Error Handling Refactoring
internal/acctest/acctest.go, internal/conns/conns.go, internal/conns/envvar.go, internal/create/attrmap.go, internal/experimental/nullable/bool.go, internal/experimental/nullable/int.go, internal/tfresource/not_found_error.go, internal/tfresource/retry.go, internal/verify/diff.go, internal/verify/validate.go, internal/vault/helper/pgpkeys/*, internal/vault/sdk/helper/jsonutil/json.go, names/errors.go, names/names.go
Introduced package-level sentinel errors and replaced fmt.Errorf strings with wrapped error formatting using %w, improving error-chain propagation. Added context-aware API calls and error-handling constants.
Service-Layer Error Handling
internal/service/ec2/find.go, internal/service/guardduty/resource_guardduty_organization_settings.go, internal/service/iam/access_key.go, internal/service/macie2/resource_macie2_organization_settings.go, internal/service/meta/arn_data_source.go, internal/service/meta/region_data_source.go, internal/service/meta/service_data_source.go, internal/service/organizations/..., internal/service/securityhub/resource_*
Added explicit error checking for d.Set() calls that were previously ignored; replaced %s formatting with %w wrapping for error propagation; introduced sentinel errors for resource-specific failures (e.g., errNotFound, errDesignatingMembers).
Meta Service Data Sources
internal/service/meta/arn_data_source.go, internal/service/meta/billing_service_account_data_source.go, internal/service/meta/default_tags_data_source.go, internal/service/meta/ip_ranges_data_source.go, internal/service/meta/partition_data_source.go, internal/service/meta/region_data_source.go, internal/service/meta/regions_data_source.go, internal/service/meta/service_data_source.go
Standardized error handling across data sources: added field-specific error wrapping for d.Set() calls; normalized error message casing (uppercase → lowercase); introduced sentinel errors for not-found and validation failures.
Documentation Punctuation
internal/acctest/crypto.go, internal/acctest/ec2_classic.go, internal/conns/config.go, internal/conns/mutexkv.go, internal/create/hashcode.go, internal/create/naming.go, internal/flex/flex.go, internal/provider/provider.go, internal/service/iam/encryption.go, internal/tags/key_value_tags.go, internal/verify/resource_differ.go, version/version.go
Added trailing periods to doc comments and function descriptions; no functional or control-flow changes.
Lint Suppression & Configuration
internal/acctest/crypto.go, internal/conns/config.go, internal/experimental/nullable/int.go, internal/experimental/nullable/testing.go, internal/provider/fwprovider/duration.go, internal/provider/fwprovider/provider.go, internal/provider/provider_test.go, internal/service/ec2/find.go, internal/service/meta/region_data_source.go, internal/tfresource/retry.go
Added //nolint directives for gosec, staticcheck, gocritic, and revive to suppress specific linting warnings without functional changes.
Context-Aware API Migration
internal/conns/config.go, internal/service/organizations/account.go, internal/service/organizations/organizational_unit.go, internal/service/organizations/organization.go, internal/service/organizations/policy.go, internal/service/organizations/policy_attachment.go, internal/verify/retry.go
Switched from non-context variants (e.g., WaitForState(), Retry(), ImportStatePassthrough) to context-aware variants (e.g., WaitForStateContext(), RetryContext(), ImportStatePassthroughContext), enabling better context propagation and cancellation.
Test Parallelization
internal/provider/fwprovider/duration_test.go, internal/service/meta/arn_test.go
Added t.Parallel() calls within subtests to enable concurrent test execution; no test logic changes.
Provider Configuration
internal/provider/provider.go, internal/provider/validate.go
Introduced shared constants for assume-role and external-ID validation limits; refactored retry logic and validation bounds to use named constants instead of hardcoded literals.
Code Style & Operators
internal/tags/key_value_tags.go, main.go
Simplified bitwise operations using compound assignment operators (e.g., hash ^= ..., logFlags &^= ...); updated doc comments for clarity.
Deprecation & Removal
internal/conns/config.go
Simplified SecurityHub retry handler logic from switch statement to direct if equality check; added lint suppression for deprecated API usage.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

  • Added go lint #90: Both PRs modify .golangci.yml—the retrieved PR adds initial linter configuration while this PR adjusts existing rules and thresholds for complexity/size metrics.
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.48% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'chore: fix golanglint findings' clearly summarizes the primary change of the PR: resolving golangci-lint findings across the provider.
Description check ✅ Passed The PR description is directly related to the changeset, explaining the scope of fixes (633→77 issues), categories addressed, and the rationale for changes including sentinel errors, context-aware API migration, and .golangci.yml tuning.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-golanglint-findings

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.

@mergify mergify Bot added the triage Needs triage label Apr 7, 2026
@mergify

mergify Bot commented Apr 7, 2026

Copy link
Copy Markdown

Important

Cloud Posse Engineering Team Review Required

This pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes.

To expedite this process, reach out to us on Slack in the #pr-reviews channel.

@mergify mergify Bot added the needs-cloudposse Needs Cloud Posse assistance label Apr 7, 2026
@RoseSecurity RoseSecurity added the patch A minor, backward compatible change label Apr 7, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/service/iam/access_key.go (1)

166-196: ⚠️ Potential issue | 🔴 Critical

Best-effort delete the key on post-create failures.

These added returns increase the number of failure paths after the IAM key has already been created. If local post-processing fails here, Terraform exits without state, but the access key remains active in AWS and unmanaged.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/iam/access_key.go` around lines 166 - 196, The new
post-create steps (starting from computing sesSMTPPasswordV4 using
SessmTPPasswordFromSecretKeySigV4 and the PGP encryption block using
RetrieveGPGKey and EncryptValue, then setting d.Set for
key_fingerprint/encrypted_secret/encrypted_ses_smtp_password_v4) introduce
multiple early returns after the IAM access key has been created
(createResp.AccessKey). Update these failure paths so that before returning any
error you attempt a best-effort deletion of the newly-created access key using
the AWS client from meta.(*conns.AWSClient) and the created key id
(createResp.AccessKey.AccessKeyId), swallow/log any deletion error but ensure
the original error is returned; do this for every place that currently returns
after the creation (e.g., after RetrieveGPGKey, EncryptValue, and d.Set
failures).
🧹 Nitpick comments (13)
internal/service/securityhub/resource_control_disablement.go (1)

127-127: Consider clarifying delete-path error wording.

This path re-enables the control (ControlStatus: "ENABLED"), so "error enabling security hub control %s" is clearer than "error updating...".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/securityhub/resource_control_disablement.go` at line 127,
The error message currently says "error updating security hub control %s" but
this code path is re-enabling the control; update the fmt.Errorf call where
controlArn and err are returned (the return fmt.Errorf(...) statement) to use
clearer wording like "error enabling security hub control %s" while preserving
the %w wrapping of the original err and the controlArn variable so the returned
error context remains intact.
internal/conns/mutexkv.go (1)

19-20: Prefer GoDoc comments to start with exported identifier names.

For idiomatic GoDoc and lint friendliness, use Lock ... and NewMutexKV ... instead of Locks ... / Returns ....

Suggested wording
-// Locks the mutex for the given key. Caller is responsible for calling Unlock
+// Lock locks the mutex for the given key. Caller is responsible for calling Unlock
 // for the same key.
@@
-// Returns a properly initialized MutexKV.
+// NewMutexKV returns a properly initialized MutexKV.
 func NewMutexKV() *MutexKV {

Also applies to: 46-47

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/conns/mutexkv.go` around lines 19 - 20, Update the GoDoc comments to
start with the exported identifier names: change the comment that currently
begins "Locks the mutex..." to start with "Lock ..." and similarly change the
constructor comment to start with "NewMutexKV ..." (and any other comments like
"Returns ..." to "NewMutexKV ...") so they follow idiomatic GoDoc style and
linting expectations; locate comments near the methods/constructors named Lock,
Unlock, and NewMutexKV in mutexkv.go and rewrite the first word(s) to match the
exported symbol names.
internal/service/macie2/resource_macie2_organization_settings.go (1)

180-186: Consider using AWS SDK error types instead of string matching.

The string-based error detection (strings.Contains(err.Error(), "specified account is not associated...")) is fragile and could break if AWS changes the error message. Consider using the AWS SDK's typed error checking with errors.As or checking specific error codes if available.

That said, the current approach works and the %w wrapping is correct.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/macie2/resource_macie2_organization_settings.go` around
lines 180 - 186, Replace fragile string matching on err.Error() in the
conn.DeleteMember error handling with typed SDK error checking: use errors.As to
see if err implements the SDK's API error interface (e.g., smithy.APIError or
the SDK error type returned by the Macie2 client) and compare the error code
(ErrorCode()/Code()) against the specific code for "account not associated"
(instead of substring matching). Keep the same logging for the non-matching case
and continue to wrap and return the error with fmt.Errorf("%w", err) when it is
a different error; reference the DeleteMember call, the err variable, and
disassociateMemberInput.Id to locate where to apply this change.
internal/vault/helper/pgpkeys/keybase.go (1)

19-26: Consider relocating shared sentinel errors out of Keybase-specific file.

errPGPInputKeysMismatch (Line 25) is not Keybase-specific and is consumed by EncryptShares. Moving shared sentinels to a package-level errors.go (or the encrypt/decrypt unit) would reduce coupling.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/vault/helper/pgpkeys/keybase.go` around lines 19 - 26, The sentinel
error errPGPInputKeysMismatch is not Keybase-specific and should be moved out of
keybase.go into a shared package-level errors file (e.g., errors.go) or into the
encrypt/decrypt unit where EncryptShares lives; remove errPGPInputKeysMismatch
from internal/vault/helper/pgpkeys/keybase.go and declare it once in the shared
file so EncryptShares and other callers import the common sentinel instead of
the Keybase-specific file.
internal/vault/helper/pgpkeys/encrypt_decrypt.go (1)

19-20: Preserve mismatch context while keeping sentinel matching.

Line 20 returns only the sentinel now, which reduces debugging detail. Consider wrapping the sentinel with input/key counts so callers can still use errors.Is.

Proposed refinement
 if len(input) != len(pgpKeys) {
-	return nil, nil, errPGPInputKeysMismatch
+	return nil, nil, fmt.Errorf(
+		"%w: input=%d pgp_keys=%d",
+		errPGPInputKeysMismatch,
+		len(input),
+		len(pgpKeys),
+	)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/vault/helper/pgpkeys/encrypt_decrypt.go` around lines 19 - 20, The
function currently returns only the sentinel errPGPInputKeysMismatch when
len(input) != len(pgpKeys), losing useful context; change the return to wrap the
sentinel with the counts so callers can still use errors.Is while seeing
details—for example create a wrapped error using fmt.Errorf("%w: inputs=%d
keys=%d", errPGPInputKeysMismatch, len(input), len(pgpKeys)) and return nil,
nil, wrappedErr; update the code in encrypt_decrypt.go where input and pgpKeys
are compared and ensure errPGPInputKeysMismatch is wrapped with %w so errors.Is
continues to work.
internal/service/guardduty/resource_guardduty_organization_settings.go (1)

168-171: Remove redundant nested if err != nil in disassociate flow.

The inner if err != nil is unreachable because the outer condition already guarantees err != nil. This same pattern appears in multiple files (securityhub/resource_organization_settings.go, macie2/resource_macie2_organization_settings.go), so consider applying the same simplification across them.

Proposed simplification
-		if _, err := conn.DisassociateMembers(disassociateMembersInput); err != nil {
-			if err != nil {
-				return fmt.Errorf("error disassociating guardduty administrator account members: %w", err)
-			}
-		}
+		if _, err := conn.DisassociateMembers(disassociateMembersInput); err != nil {
+			return fmt.Errorf("error disassociating guardduty administrator account members: %w", err)
+		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/guardduty/resource_guardduty_organization_settings.go`
around lines 168 - 171, The disassociate flow contains a redundant nested "if
err != nil" inside the outer "if _, err :=
conn.DisassociateMembers(disassociateMembersInput); err != nil" check; remove
the inner unreachable conditional and return the formatted error directly (e.g.,
in the function handling DisassociateMembers in
resource_guardduty_organization_settings.go, replace the inner if block with a
single return fmt.Errorf(...) when err is present). Apply the same
simplification to the analogous blocks in
securityhub/resource_organization_settings.go and
macie2/resource_macie2_organization_settings.go where conn.DisassociateMembers
(or equivalent) is checked.
internal/service/securityhub/resource_organization_settings.go (1)

181-184: Remove redundant nested if err != nil check in disassociate branch.

The inner condition is logically redundant—since the outer if already verifies err != nil, the error is guaranteed to be non-nil inside the block. Simplify by removing the inner check:

Proposed change
 		if _, err := conn.DisassociateMembers(disassociateMembersInput); err != nil {
-			if err != nil {
-				return fmt.Errorf("error disassociating security hub administrator account members: %w", err)
-			}
+			return fmt.Errorf("error disassociating security hub administrator account members: %w", err)
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/securityhub/resource_organization_settings.go` around lines
181 - 184, Remove the redundant inner error check inside the DisassociateMembers
call: in the block handling the result of
conn.DisassociateMembers(disassociateMembersInput) (where the outer if already
checks `if _, err := conn.DisassociateMembers(disassociateMembersInput); err !=
nil {`), delete the nested `if err != nil` and directly return the formatted
error (e.g., `return fmt.Errorf("error disassociating security hub administrator
account members: %w", err)`), so the error handling is concise and not
duplicated.
internal/service/sts/caller_identity_data_source.go (1)

100-103: Partition-specific ARN prefix may miss GovCloud and China regions.

The check strings.HasPrefix(..., "arn:aws:sts") only matches the standard AWS partition. For AWS GovCloud (arn:aws-us-gov:sts) or China (arn:aws-cn:sts), this condition will be false and eks_role_arn won't be set even for assumed roles.

Consider using a more partition-agnostic check:

♻️ Suggested fix for partition-agnostic assumed role detection
-	// If the caller identity is an assumed role, get the IAM role ARN and set it as the ARN.
-	if strings.HasPrefix(aws.StringValue(res.Arn), "arn:aws:sts") {
+	// If the caller identity is an assumed role, get the IAM role ARN and set it as the ARN.
+	// Check for assumed-role in any AWS partition (aws, aws-cn, aws-us-gov, etc.)
+	if strings.Contains(aws.StringValue(res.Arn), ":sts:") && strings.Contains(aws.StringValue(res.Arn), ":assumed-role/") {
		if err := d.Set("eks_role_arn", getIamRoleArnFromCallerRoleArn(aws.StringValue(res.Arn))); err != nil {
			return fmt.Errorf("error setting eks_role_arn: %w", err)
		}
	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/sts/caller_identity_data_source.go` around lines 100 - 103,
The current prefix check strings.HasPrefix(aws.StringValue(res.Arn),
"arn:aws:sts") misses GovCloud/China partitions; update the assumed-role
detection in caller_identity_data_source.go to be partition-agnostic by checking
for the sts service segment (e.g., test for ":sts:" or use a regex like
`^arn:[^:]+:sts:`) against aws.StringValue(res.Arn) before calling
getIamRoleArnFromCallerRoleArn and d.Set("eks_role_arn", ...), so eks_role_arn
is set for assumed roles across aws, aws-us-gov, and aws-cn partitions.
internal/service/organizations/policy_attachment.go (1)

59-71: RetryContext still uses context.Background() instead of propagating Terraform's request context.

This resource defines Create, Read, and Delete legacy callbacks (not context-aware), yet the create retry loop passes context.Background(). To fully propagate Terraform cancellation through retries, migrate this resource to CreateContext, ReadContext, and DeleteContext callbacks and thread the request context through the retry path.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/organizations/policy_attachment.go` around lines 59 - 71,
The retry loop uses context.Background() so Terraform cancellations aren't
propagated; update the legacy Create/Read/Delete callbacks to context-aware
CreateContext/ReadContext/DeleteContext, accept the incoming context parameter
(ctx) and pass that ctx into resource.RetryContext instead of
context.Background(), and ensure the ctx is threaded into the AWS call (e.g.,
the AttachPolicy invocation on conn) and any other retry loops so
cancellations/timeouts from Terraform are observed; also update corresponding
registration of the resource callbacks to use the new Context variants.
internal/service/organizations/organizational_unit.go (1)

100-112: This retry loop cannot be cancelled by Terraform's request context because the resource uses legacy CRUD callbacks.

The resource defines Create:, Read:, Update:, and Delete: callbacks (not context-aware variants), which cannot receive a context parameter. Using context.Background() here means interrupted applies won't cancel the OU create retries.

To fix this, migrate the resource to context-aware CRUD callbacks (CreateContext:, ReadContext:, UpdateContext:, DeleteContext:) and pass the request context into the RetryContext call.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/organizations/organizational_unit.go` around lines 100 -
112, The retry loop uses resource.RetryContext with context.Background(), so
interrupts can't cancel retries because the resource still registers legacy
callbacks (Create:, Read:, Update:, Delete:); migrate the resource to use
context-aware callbacks (CreateContext:, ReadContext:, UpdateContext:,
DeleteContext:) and update the create implementation to accept the incoming
context and pass that context into resource.RetryContext instead of
context.Background(), keeping the CreateOrganizationalUnit call and existing
retry logic otherwise unchanged.
internal/service/organizations/organization.go (1)

529-529: Consider propagating context from callers instead of using context.Background().

While migrating from WaitForState() to WaitForStateContext(context.Background()) is an improvement over the deprecated API, using context.Background() loses the ability to propagate cancellation signals. For a complete migration, consider:

  1. Converting resourceOrganizationCreate/resourceOrganizationUpdate to use CreateContext/UpdateContext signatures
  2. Passing the context through to these wait helper functions

This is a recommended follow-up improvement rather than a blocking issue since the current change still addresses the deprecation warning.

Also applies to: 545-545

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/organizations/organization.go` at line 529, The call to
stateConf.WaitForStateContext currently uses context.Background(), which
discards caller cancellation; update resourceOrganizationCreate and
resourceOrganizationUpdate to their context-aware signatures
(CreateContext/UpdateContext), accept a ctx parameter, and pass that ctx into
stateConf.WaitForStateContext (and any other wait helpers) instead of
context.Background() so cancellation and deadlines propagate from callers to
WaitForStateContext.
internal/verify/validate.go (1)

191-214: Consider using constants in error messages for consistency.

The refactored switch statements are cleaner, but the error messages still hardcode numeric limits instead of referencing the defined constants. This creates a maintenance risk if the constants change.

🔧 Suggested improvement
 func ValidLaunchTemplateID(v interface{}, k string) (ws []string, errors []error) {
 	value := v.(string)
 	switch {
 	case len(value) < 1:
 		errors = append(errors, fmt.Errorf("%w: %q cannot be shorter than 1 character", errValidation, k))
 	case len(value) > launchTemplateIDMaxLen:
-		errors = append(errors, fmt.Errorf("%w: %q cannot be longer than 255 characters", errValidation, k))
+		errors = append(errors, fmt.Errorf("%w: %q cannot be longer than %d characters", errValidation, k, launchTemplateIDMaxLen))
 	case !regexp.MustCompile(`^lt\-[a-z0-9]+$`).MatchString(value):
 		errors = append(errors, fmt.Errorf(
 			"%w: %q must begin with 'lt-' and be comprised of only alphanumeric characters: %v", errValidation, k, value))
 	}
 	return ws, errors
 }

 func ValidLaunchTemplateName(v interface{}, k string) (ws []string, errors []error) {
 	value := v.(string)
 	switch {
 	case len(value) < 3:
 		errors = append(errors, fmt.Errorf("%w: %q cannot be less than 3 characters", errValidation, k))
 	case strings.HasSuffix(k, "prefix") && len(value) > launchTemplatePrefixMaxLen:
-		errors = append(errors, fmt.Errorf("%w: %q cannot be longer than 99 characters, name is limited to 125", errValidation, k))
+		errors = append(errors, fmt.Errorf("%w: %q cannot be longer than %d characters, name is limited to %d", errValidation, k, launchTemplatePrefixMaxLen, launchTemplateNameMaxLen))
 	case !strings.HasSuffix(k, "prefix") && len(value) > launchTemplateNameMaxLen:
-		errors = append(errors, fmt.Errorf("%w: %q cannot be longer than 125 characters", errValidation, k))
+		errors = append(errors, fmt.Errorf("%w: %q cannot be longer than %d characters", errValidation, k, launchTemplateNameMaxLen))
 	case !regexp.MustCompile(`^[0-9a-zA-Z()./_\-]+$`).MatchString(value):
 		errors = append(errors, fmt.Errorf("%w: %q can only alphanumeric characters and ()./_- symbols", errValidation, k))
 	}
 	return ws, errors
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/verify/validate.go` around lines 191 - 214, Update the hardcoded
numeric limits in the validation error messages to use the defined constants
instead of literal numbers: replace "1" and "255" in the ValidLaunchTemplateID
error messages with the appropriate constants (e.g., launchTemplateMinLen and
launchTemplateIDMaxLen), and replace "3", "99", and "125" in
ValidLaunchTemplateName with the corresponding constants (e.g.,
launchTemplateMinLen, launchTemplatePrefixMaxLen, launchTemplateNameMaxLen),
formatting the messages with those constants (using %d or fmt.Sprintf) so the
strings stay correct if the constants change; locate these edits in the switch
blocks inside ValidLaunchTemplateID (or the function above) and
ValidLaunchTemplateName and update the fmt.Errorf calls that currently hardcode
the numeric limits.
internal/verify/retry.go (1)

12-14: Consider accepting a context parameter for proper cancellation support.

Using context.Background() works for the lint fix, but RetryOnAWSCode is a public function. To enable proper timeout/cancellation propagation from callers, consider updating the signature to accept a context:

♻️ Suggested improvement
-func RetryOnAWSCode(code string, f func() (interface{}, error)) (interface{}, error) {
+func RetryOnAWSCode(ctx context.Context, code string, f func() (interface{}, error)) (interface{}, error) {
 	var resp interface{}
-	err := resource.RetryContext(context.Background(), 2*time.Minute, func() *resource.RetryError {
+	err := resource.RetryContext(ctx, 2*time.Minute, func() *resource.RetryError {

This would require updating all call sites. If that's out of scope for this PR, the current change is acceptable.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/verify/retry.go` around lines 12 - 14, The function RetryOnAWSCode
currently uses context.Background() which prevents caller-driven cancellation;
change the signature of RetryOnAWSCode to accept a ctx context.Context parameter
and pass that ctx into resource.RetryContext instead of context.Background(),
and then update all call sites to forward their context (including tests and any
goroutines) so timeouts/cancellations propagate correctly; keep the existing
behavior of the retry closure and error handling unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/conns/envvar.go`:
- Line 104: The error string in RequireOneOfEnvVar currently formats as "%w: of
%v. Usage: %s" which produces awkward output; change the format to remove the
stray "of" so the message reads naturally (e.g. "%w: %v. Usage: %s" or "%w: %v
(Usage: %s)") and keep the wrapped error symbol errEnvVarRequiredOneOf and the
variables names and usageMessage in the fmt.Errorf call.

In `@internal/create/hashcode.go`:
- Around line 9-10: Update the misleading comment that references a non-existent
Crc32 identifier: change the comment to mention crc32.ChecksumIEEE (the actual
function used) and state that "ChecksumIEEE returns a uint32, but for our use we
need a non-negative integer; here we cast to an integer" so the comment above
the hash conversion (where crc32.ChecksumIEEE is called) correctly documents the
behavior.

In `@internal/service/iam/access_key.go`:
- Around line 162-163: Move the nil-check for createResp.AccessKey so it runs
before any dereference (specifically before d.SetId() and any access to
createResp.AccessKey.SecretAccessKey); currently createResp.AccessKey is
dereferenced prior to the guard which can panic. Update the code in the create
path to first do "if createResp.AccessKey == nil { return
errMissingSecretAccessKey }" and only afterwards check SecretAccessKey and call
d.SetId() and other accesses to createResp.AccessKey.

In `@internal/service/macie2/resource_macie2_organization_settings.go`:
- Around line 174-178: The nested redundant error check inside the
DisassociateMember call causes dead code; in the block where you call
conn.DisassociateMember(disassociateMemberInput) you should remove the inner "if
err != nil" and directly return fmt.Errorf("error disassociating macie2
administrator account member: %w", err) when err is non-nil (i.e., replace the
current nested block with a single `if _, err :=
conn.DisassociateMember(disassociateMemberInput); err != nil { return
fmt.Errorf(..., err) }` using the same conn.DisassociateMember,
disassociateMemberInput and fmt.Errorf references).

In `@internal/service/meta/region_data_source.go`:
- Around line 64-66: When detecting multiple region matches in the block that
checks "if region != nil && region.ID() != matchingRegion.ID()", return an error
that includes both conflicting IDs instead of plain errMultipleRegionsMatched;
e.g., wrap or format errMultipleRegionsMatched with region.ID() and
matchingRegion.ID() (using fmt.Errorf or errors.Wrap) so the returned error
contains the two IDs for debugging, and ensure fmt is imported if adding
fmt.Errorf; keep the original sentinel errMultipleRegionsMatched as the wrapped
cause.

In `@internal/service/meta/service_data_source.go`:
- Around line 130-142: Default the "supported" field to false first, then call
endpoints.PartitionForRegion(endpoints.DefaultPartitions(),
d.Get("region").(string)) and only set supported to true after both the
partition exists and partition.Services() contains d.Get("service_id").(string);
if the region is unknown or the service is not present, explicitly clear/unset
the "partition" field and ensure "supported" remains false. Update the logic
around d.Set("supported", ...), d.Set("partition", ...),
endpoints.PartitionForRegion, d.Get("region"), d.Get("service_id"), and
partition.Services() so state cannot become stale when switching to an unknown
region.

---

Outside diff comments:
In `@internal/service/iam/access_key.go`:
- Around line 166-196: The new post-create steps (starting from computing
sesSMTPPasswordV4 using SessmTPPasswordFromSecretKeySigV4 and the PGP encryption
block using RetrieveGPGKey and EncryptValue, then setting d.Set for
key_fingerprint/encrypted_secret/encrypted_ses_smtp_password_v4) introduce
multiple early returns after the IAM access key has been created
(createResp.AccessKey). Update these failure paths so that before returning any
error you attempt a best-effort deletion of the newly-created access key using
the AWS client from meta.(*conns.AWSClient) and the created key id
(createResp.AccessKey.AccessKeyId), swallow/log any deletion error but ensure
the original error is returned; do this for every place that currently returns
after the creation (e.g., after RetrieveGPGKey, EncryptValue, and d.Set
failures).

---

Nitpick comments:
In `@internal/conns/mutexkv.go`:
- Around line 19-20: Update the GoDoc comments to start with the exported
identifier names: change the comment that currently begins "Locks the mutex..."
to start with "Lock ..." and similarly change the constructor comment to start
with "NewMutexKV ..." (and any other comments like "Returns ..." to "NewMutexKV
...") so they follow idiomatic GoDoc style and linting expectations; locate
comments near the methods/constructors named Lock, Unlock, and NewMutexKV in
mutexkv.go and rewrite the first word(s) to match the exported symbol names.

In `@internal/service/guardduty/resource_guardduty_organization_settings.go`:
- Around line 168-171: The disassociate flow contains a redundant nested "if err
!= nil" inside the outer "if _, err :=
conn.DisassociateMembers(disassociateMembersInput); err != nil" check; remove
the inner unreachable conditional and return the formatted error directly (e.g.,
in the function handling DisassociateMembers in
resource_guardduty_organization_settings.go, replace the inner if block with a
single return fmt.Errorf(...) when err is present). Apply the same
simplification to the analogous blocks in
securityhub/resource_organization_settings.go and
macie2/resource_macie2_organization_settings.go where conn.DisassociateMembers
(or equivalent) is checked.

In `@internal/service/macie2/resource_macie2_organization_settings.go`:
- Around line 180-186: Replace fragile string matching on err.Error() in the
conn.DeleteMember error handling with typed SDK error checking: use errors.As to
see if err implements the SDK's API error interface (e.g., smithy.APIError or
the SDK error type returned by the Macie2 client) and compare the error code
(ErrorCode()/Code()) against the specific code for "account not associated"
(instead of substring matching). Keep the same logging for the non-matching case
and continue to wrap and return the error with fmt.Errorf("%w", err) when it is
a different error; reference the DeleteMember call, the err variable, and
disassociateMemberInput.Id to locate where to apply this change.

In `@internal/service/organizations/organization.go`:
- Line 529: The call to stateConf.WaitForStateContext currently uses
context.Background(), which discards caller cancellation; update
resourceOrganizationCreate and resourceOrganizationUpdate to their context-aware
signatures (CreateContext/UpdateContext), accept a ctx parameter, and pass that
ctx into stateConf.WaitForStateContext (and any other wait helpers) instead of
context.Background() so cancellation and deadlines propagate from callers to
WaitForStateContext.

In `@internal/service/organizations/organizational_unit.go`:
- Around line 100-112: The retry loop uses resource.RetryContext with
context.Background(), so interrupts can't cancel retries because the resource
still registers legacy callbacks (Create:, Read:, Update:, Delete:); migrate the
resource to use context-aware callbacks (CreateContext:, ReadContext:,
UpdateContext:, DeleteContext:) and update the create implementation to accept
the incoming context and pass that context into resource.RetryContext instead of
context.Background(), keeping the CreateOrganizationalUnit call and existing
retry logic otherwise unchanged.

In `@internal/service/organizations/policy_attachment.go`:
- Around line 59-71: The retry loop uses context.Background() so Terraform
cancellations aren't propagated; update the legacy Create/Read/Delete callbacks
to context-aware CreateContext/ReadContext/DeleteContext, accept the incoming
context parameter (ctx) and pass that ctx into resource.RetryContext instead of
context.Background(), and ensure the ctx is threaded into the AWS call (e.g.,
the AttachPolicy invocation on conn) and any other retry loops so
cancellations/timeouts from Terraform are observed; also update corresponding
registration of the resource callbacks to use the new Context variants.

In `@internal/service/securityhub/resource_control_disablement.go`:
- Line 127: The error message currently says "error updating security hub
control %s" but this code path is re-enabling the control; update the fmt.Errorf
call where controlArn and err are returned (the return fmt.Errorf(...)
statement) to use clearer wording like "error enabling security hub control %s"
while preserving the %w wrapping of the original err and the controlArn variable
so the returned error context remains intact.

In `@internal/service/securityhub/resource_organization_settings.go`:
- Around line 181-184: Remove the redundant inner error check inside the
DisassociateMembers call: in the block handling the result of
conn.DisassociateMembers(disassociateMembersInput) (where the outer if already
checks `if _, err := conn.DisassociateMembers(disassociateMembersInput); err !=
nil {`), delete the nested `if err != nil` and directly return the formatted
error (e.g., `return fmt.Errorf("error disassociating security hub administrator
account members: %w", err)`), so the error handling is concise and not
duplicated.

In `@internal/service/sts/caller_identity_data_source.go`:
- Around line 100-103: The current prefix check
strings.HasPrefix(aws.StringValue(res.Arn), "arn:aws:sts") misses GovCloud/China
partitions; update the assumed-role detection in caller_identity_data_source.go
to be partition-agnostic by checking for the sts service segment (e.g., test for
":sts:" or use a regex like `^arn:[^:]+:sts:`) against aws.StringValue(res.Arn)
before calling getIamRoleArnFromCallerRoleArn and d.Set("eks_role_arn", ...), so
eks_role_arn is set for assumed roles across aws, aws-us-gov, and aws-cn
partitions.

In `@internal/vault/helper/pgpkeys/encrypt_decrypt.go`:
- Around line 19-20: The function currently returns only the sentinel
errPGPInputKeysMismatch when len(input) != len(pgpKeys), losing useful context;
change the return to wrap the sentinel with the counts so callers can still use
errors.Is while seeing details—for example create a wrapped error using
fmt.Errorf("%w: inputs=%d keys=%d", errPGPInputKeysMismatch, len(input),
len(pgpKeys)) and return nil, nil, wrappedErr; update the code in
encrypt_decrypt.go where input and pgpKeys are compared and ensure
errPGPInputKeysMismatch is wrapped with %w so errors.Is continues to work.

In `@internal/vault/helper/pgpkeys/keybase.go`:
- Around line 19-26: The sentinel error errPGPInputKeysMismatch is not
Keybase-specific and should be moved out of keybase.go into a shared
package-level errors file (e.g., errors.go) or into the encrypt/decrypt unit
where EncryptShares lives; remove errPGPInputKeysMismatch from
internal/vault/helper/pgpkeys/keybase.go and declare it once in the shared file
so EncryptShares and other callers import the common sentinel instead of the
Keybase-specific file.

In `@internal/verify/retry.go`:
- Around line 12-14: The function RetryOnAWSCode currently uses
context.Background() which prevents caller-driven cancellation; change the
signature of RetryOnAWSCode to accept a ctx context.Context parameter and pass
that ctx into resource.RetryContext instead of context.Background(), and then
update all call sites to forward their context (including tests and any
goroutines) so timeouts/cancellations propagate correctly; keep the existing
behavior of the retry closure and error handling unchanged.

In `@internal/verify/validate.go`:
- Around line 191-214: Update the hardcoded numeric limits in the validation
error messages to use the defined constants instead of literal numbers: replace
"1" and "255" in the ValidLaunchTemplateID error messages with the appropriate
constants (e.g., launchTemplateMinLen and launchTemplateIDMaxLen), and replace
"3", "99", and "125" in ValidLaunchTemplateName with the corresponding constants
(e.g., launchTemplateMinLen, launchTemplatePrefixMaxLen,
launchTemplateNameMaxLen), formatting the messages with those constants (using
%d or fmt.Sprintf) so the strings stay correct if the constants change; locate
these edits in the switch blocks inside ValidLaunchTemplateID (or the function
above) and ValidLaunchTemplateName and update the fmt.Errorf calls that
currently hardcode the numeric limits.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3d414df4-65f5-42a1-8e5e-4f242e8b3601

📥 Commits

Reviewing files that changed from the base of the PR and between 6452846 and 664a648.

📒 Files selected for processing (62)
  • .golangci.yml
  • internal/acctest/acctest.go
  • internal/acctest/crypto.go
  • internal/acctest/ec2_classic.go
  • internal/conns/config.go
  • internal/conns/conns.go
  • internal/conns/envvar.go
  • internal/conns/mutexkv.go
  • internal/create/attrmap.go
  • internal/create/hashcode.go
  • internal/create/naming.go
  • internal/experimental/nullable/bool.go
  • internal/experimental/nullable/int.go
  • internal/experimental/nullable/testing.go
  • internal/flex/flex.go
  • internal/provider/fwprovider/duration.go
  • internal/provider/fwprovider/duration_test.go
  • internal/provider/fwprovider/provider.go
  • internal/provider/provider.go
  • internal/provider/provider_test.go
  • internal/provider/validate.go
  • internal/service/ec2/find.go
  • internal/service/guardduty/resource_guardduty_organization_settings.go
  • internal/service/iam/access_key.go
  • internal/service/iam/encryption.go
  • internal/service/macie2/resource_macie2_organization_settings.go
  • internal/service/meta/arn.go
  • internal/service/meta/arn_data_source.go
  • internal/service/meta/arn_test.go
  • internal/service/meta/billing_service_account_data_source.go
  • internal/service/meta/default_tags_data_source.go
  • internal/service/meta/ip_ranges_data_source.go
  • internal/service/meta/partition_data_source.go
  • internal/service/meta/region_data_source.go
  • internal/service/meta/regions_data_source.go
  • internal/service/meta/service_data_source.go
  • internal/service/organizations/account.go
  • internal/service/organizations/delegated_administrator.go
  • internal/service/organizations/organization.go
  • internal/service/organizations/organization_data_source.go
  • internal/service/organizations/organizational_unit.go
  • internal/service/organizations/policy.go
  • internal/service/organizations/policy_attachment.go
  • internal/service/organizations/resource_tags_data_source.go
  • internal/service/securityhub/resource_control_disablement.go
  • internal/service/securityhub/resource_organization_settings.go
  • internal/service/sts/caller_identity_data_source.go
  • internal/tags/key_value_tags.go
  • internal/tags/tag_resources.go
  • internal/tfresource/not_found_error.go
  • internal/tfresource/retry.go
  • internal/vault/helper/pgpkeys/encrypt_decrypt.go
  • internal/vault/helper/pgpkeys/keybase.go
  • internal/vault/sdk/helper/jsonutil/json.go
  • internal/verify/diff.go
  • internal/verify/resource_differ.go
  • internal/verify/retry.go
  • internal/verify/validate.go
  • main.go
  • names/errors.go
  • names/names.go
  • version/version.go

Comment thread internal/conns/envvar.go Resolved
Comment thread internal/create/hashcode.go Resolved
Comment thread internal/service/iam/access_key.go Resolved

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-cloudposse Needs Cloud Posse assistance patch A minor, backward compatible change triage Needs triage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant