Repository navigation
chore: fix golanglint findings - #96
RoseSecurity wants to merge 7 commits into
Conversation
- 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)
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughThis PR refactors error handling throughout the codebase by introducing shared sentinel errors and replacing string formatting with error wrapping ( Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~40 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
|
Important Cloud Posse Engineering Team Review RequiredThis 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 |
There was a problem hiding this comment.
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 | 🔴 CriticalBest-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 ...andNewMutexKV ...instead ofLocks .../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 witherrors.Asor checking specific error codes if available.That said, the current approach works and the
%wwrapping 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 byEncryptShares. Moving shared sentinels to a package-levelerrors.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 nestedif err != nilin disassociate flow.The inner
if err != nilis unreachable because the outer condition already guaranteeserr != 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 nestedif err != nilcheck in disassociate branch.The inner condition is logically redundant—since the outer
ifalready verifieserr != 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 andeks_role_arnwon'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:RetryContextstill usescontext.Background()instead of propagating Terraform's request context.This resource defines
Create,Read, andDeletelegacy callbacks (not context-aware), yet the create retry loop passescontext.Background(). To fully propagate Terraform cancellation through retries, migrate this resource toCreateContext,ReadContext, andDeleteContextcallbacks 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:, andDelete:callbacks (not context-aware variants), which cannot receive a context parameter. Usingcontext.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 theRetryContextcall.🤖 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 usingcontext.Background().While migrating from
WaitForState()toWaitForStateContext(context.Background())is an improvement over the deprecated API, usingcontext.Background()loses the ability to propagate cancellation signals. For a complete migration, consider:
- Converting
resourceOrganizationCreate/resourceOrganizationUpdateto useCreateContext/UpdateContextsignatures- 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, butRetryOnAWSCodeis 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
📒 Files selected for processing (62)
.golangci.ymlinternal/acctest/acctest.gointernal/acctest/crypto.gointernal/acctest/ec2_classic.gointernal/conns/config.gointernal/conns/conns.gointernal/conns/envvar.gointernal/conns/mutexkv.gointernal/create/attrmap.gointernal/create/hashcode.gointernal/create/naming.gointernal/experimental/nullable/bool.gointernal/experimental/nullable/int.gointernal/experimental/nullable/testing.gointernal/flex/flex.gointernal/provider/fwprovider/duration.gointernal/provider/fwprovider/duration_test.gointernal/provider/fwprovider/provider.gointernal/provider/provider.gointernal/provider/provider_test.gointernal/provider/validate.gointernal/service/ec2/find.gointernal/service/guardduty/resource_guardduty_organization_settings.gointernal/service/iam/access_key.gointernal/service/iam/encryption.gointernal/service/macie2/resource_macie2_organization_settings.gointernal/service/meta/arn.gointernal/service/meta/arn_data_source.gointernal/service/meta/arn_test.gointernal/service/meta/billing_service_account_data_source.gointernal/service/meta/default_tags_data_source.gointernal/service/meta/ip_ranges_data_source.gointernal/service/meta/partition_data_source.gointernal/service/meta/region_data_source.gointernal/service/meta/regions_data_source.gointernal/service/meta/service_data_source.gointernal/service/organizations/account.gointernal/service/organizations/delegated_administrator.gointernal/service/organizations/organization.gointernal/service/organizations/organization_data_source.gointernal/service/organizations/organizational_unit.gointernal/service/organizations/policy.gointernal/service/organizations/policy_attachment.gointernal/service/organizations/resource_tags_data_source.gointernal/service/securityhub/resource_control_disablement.gointernal/service/securityhub/resource_organization_settings.gointernal/service/sts/caller_identity_data_source.gointernal/tags/key_value_tags.gointernal/tags/tag_resources.gointernal/tfresource/not_found_error.gointernal/tfresource/retry.gointernal/vault/helper/pgpkeys/encrypt_decrypt.gointernal/vault/helper/pgpkeys/keybase.gointernal/vault/sdk/helper/jsonutil/json.gointernal/verify/diff.gointernal/verify/resource_differ.gointernal/verify/retry.gointernal/verify/validate.gomain.gonames/errors.gonames/names.goversion/version.go
what
This PR resolves all actionable
golangci-lintfindings across the provider, reducing issues from 633 to 77 (the remaining 77 areunusedfindings 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%wwrapping, deprecated Terraform Plugin SDK calls (ImportStatePassthrough,WaitForState,resource.Retry) were migrated to their context-aware equivalents, andmath/rand.Seedusage was replaced withrand.New(rand.NewSource(...)). The.golangci.ymlconfig was also tuned to set realistic thresholds for a Terraform provider (funlen, cyclop, gocognit, nestif, revive cyclomatic/cognitive-complexity) and to drop theos.Getenvforbid 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.ymlreflects 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.