Skip to content

Conversation

@anandkuma77
Copy link

Summary

Fixes multiple golangci-lint errors to ensure the codebase passes all linting checks.

Changes

  • forcetypeassert: Replace unsafe type assertions with checked assertions across istiocsr and deployment packages
  • contextcheck: Add nolint for SetupSignalHandler (intentionally creates new context)
  • wastedassign: Add nolint for deployment assignment (kept for clarity)
  • makezero: Initialize slices with zero length and pre-allocate capacity
  • depguard: Disabled due to golangci-lint v2 configuration issues

@openshift-ci-robot openshift-ci-robot added the jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. label Dec 24, 2025
@openshift-ci-robot
Copy link

openshift-ci-robot commented Dec 24, 2025

@anandkuma77: This pull request references CM-841 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "4.22.0" version, but no target version was set.

Details

In response to this:

Summary

Fixes multiple golangci-lint errors to ensure the codebase passes all linting checks.

Changes

  • forcetypeassert: Replace unsafe type assertions with checked assertions across istiocsr and deployment packages
  • contextcheck: Add nolint for SetupSignalHandler (intentionally creates new context)
  • wastedassign: Add nolint for deployment assignment (kept for clarity)
  • makezero: Initialize slices with zero length and pre-allocate capacity
  • depguard: Disabled due to golangci-lint v2 configuration issues

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@coderabbitai
Copy link

coderabbitai bot commented Dec 24, 2025

Walkthrough

This pull request enhances Go linting configuration, improves error handling with explicit wrapping and type assertions across the istiocsr controller, updates test mocks to use consistent error sentinels, refactors internal helper methods for type safety, and makes minor bug fixes and code cleanup throughout the operator codebase.

Changes

Cohort / File(s) Summary
Linting Configuration
\.golangci\.yaml
Removes depguard from enabled linters and re-adds under disable; adds extensive per-path and per-linter exclusions, overrides for godot, gosec, wrapcheck, nestif, gocritic, staticcheck, unparam with customized scopes and exclusions; adds detailed per-path overrides with contextual comments.
istiocsr Client & Error Handling
pkg/controller/istiocsr/client.go, deployments.go, utils.go, networkpolicies.go, rbacs.go, certificates.go
Wraps all client method errors (Get, List, Create, Delete, Update, UpdateWithRetry, StatusUpdate, Patch) with descriptive formatted messages including object keys; adds explicit type assertions with ok-checks in utils.go for Certificate, ClusterRole, ClusterRoleBinding, Deployment, Role, RoleBinding, Service, ConfigMap, NetworkPolicy; validates NetworkPolicy type at runtime; renames error sentinel from invalidIssuerRefConfigError to errInvalidIssuerRefConfig; refactors updateClusterRoleNameInStatus and updateClusterRoleBindingNameInStatus to use "desired" instead of "new" parameter naming; updates DNSNames allocation pattern.
istiocsr Test Mock Updates
certificates_test.go, controller_test.go, deployments_test.go, install_instiocsr_test.go, rbacs_test.go, serviceaccounts_test.go, services_test.go, test_utils.go
Replaces sentinel error value across all test mocks from testError to errTestClient; updates expected error messages to reflect new error propagation paths and wording (e.g., "any of" instead of "anyof"); no control-flow changes.
istiocsr Controller
pkg/controller/istiocsr/controller.go
Adds nolint:unparam directive with explanatory comment to cleanUp function for future implementation.
Operator Client & Starter
pkg/operator/operatorclient/operatorclient.go, pkg/operator/starter.go
Renames local variable from "copy" to "updated" in UpdateOperatorSpec and UpdateOperatorStatus; refactors EnsureFinalizer to reuse finalizers variable; adds nolint:contextcheck on SetupSignalHandler call with explanatory comment.
Deployment Controller
pkg/controller/deployment/deployment_unsupported_overrides.go, generic_deployment_controller.go
Adds nolint:staticcheck,wastedassign directive to json.Unmarshal error handling in deployment_unsupported_overrides.go; replaces informers factory reference with local variable form and adds infrastructure informer to informers slice in generic_deployment_controller.go.
Main Entry Point
main.go
Assigns return value of cmd.Help() to blank identifier to explicitly handle error in NewOperatorCommand Run handler.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

✨ Finishing touches
  • 📝 Generate docstrings

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

@anandkuma77 anandkuma77 marked this pull request as draft December 24, 2025 03:13
@openshift-ci openshift-ci bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Dec 24, 2025
Copy link

@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 (4)
pkg/controller/deployment/credentials_request.go (1)

46-56: Consider evaluating the wrapcheck suppressions for consistency with error handling patterns.

Lines 48 wraps the error with context (fmt.Errorf), but lines 50 and 55 return errors directly with //nolint:wrapcheck comments claiming "error from lister is already contextual."

While Kubernetes lister/informer errors typically do include method context (e.g., secrets.Get(), infrastructure.Get()), the inconsistency between wrapping some errors and suppressing wrapping for others may warrant clarification: Is the distinction intentional (some errors need additional context, others don't), or should all be wrapped consistently for clarity?

This doesn't block the PR, but ensure the pattern aligns with your team's error handling conventions.

pkg/controller/deployment/deployment_overrides.go (1)

196-201: Consider wrapping the error for consistency and better debugging.

While the lister error includes the resource name and namespace, wrapping it with operation context (similar to line 198) would improve debugging by clarifying this occurred during trusted CA configmap loading.

🔎 Proposed refactor to wrap the error
 		_, err := configmapinformer.Lister().ConfigMaps(operatorclient.TargetNamespace).Get(trustedCAConfigmapName)
 		if err != nil && apierrors.IsNotFound(err) {
 			return fmt.Errorf("(Retrying) trusted CA config map %q doesn't exist due to %w", trustedCAConfigmapName, err)
 		} else if err != nil {
-			return err //nolint:wrapcheck // error from lister is already contextual
+			return fmt.Errorf("failed to get trusted CA config map %q: %w", trustedCAConfigmapName, err)
 		}
pkg/controller/deployment/default_cert_manager_controller.go (1)

58-58: Consider wrapping the error instead of suppressing the linter.

While the Kubernetes client error contains API-level details, wrapping it would add application context about the specific operation that failed (creating the default cert manager). This improves debugging by making error messages more informative in logs and traces.

🔎 Proposed refactor to wrap the error
-	return c.certManagerClient.CertManagers().Create(ctx, cm, metav1.CreateOptions{}) //nolint:wrapcheck // error from client is already contextual
+	cm, err := c.certManagerClient.CertManagers().Create(ctx, cm, metav1.CreateOptions{})
+	if err != nil {
+		return nil, fmt.Errorf("failed to create default cert manager: %w", err)
+	}
+	return cm, nil

Don't forget to import fmt if not already present.

pkg/controller/istiocsr/utils.go (1)

404-423: Consider simplifying the redundant type assertions.

In these generic functions, after the type switch on desired, the types are already known. The additional any(desired).(*rbacv1.ClusterRole) assertions are technically redundant since the switch case already confirms the type. However, this doesn't affect correctness and satisfies the linter.

Also applies to: 425-444, 446-465

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between b0b1af8 and c3b053f.

📒 Files selected for processing (29)
  • .golangci.yaml
  • api/operator/v1alpha1/certmanager_types.go
  • api/operator/v1alpha1/istiocsr_types.go
  • main.go
  • pkg/controller/deployment/credentials_request.go
  • pkg/controller/deployment/default_cert_manager_controller.go
  • pkg/controller/deployment/deployment_overrides.go
  • pkg/controller/deployment/deployment_unsupported_overrides.go
  • pkg/controller/deployment/generic_deployment_controller.go
  • pkg/controller/istiocsr/certificates.go
  • pkg/controller/istiocsr/certificates_test.go
  • pkg/controller/istiocsr/client.go
  • pkg/controller/istiocsr/controller.go
  • pkg/controller/istiocsr/controller_test.go
  • pkg/controller/istiocsr/deployments.go
  • pkg/controller/istiocsr/deployments_test.go
  • pkg/controller/istiocsr/install_instiocsr_test.go
  • pkg/controller/istiocsr/networkpolicies.go
  • pkg/controller/istiocsr/rbacs.go
  • pkg/controller/istiocsr/rbacs_test.go
  • pkg/controller/istiocsr/serviceaccounts_test.go
  • pkg/controller/istiocsr/services_test.go
  • pkg/controller/istiocsr/test_utils.go
  • pkg/controller/istiocsr/utils.go
  • pkg/features/features.go
  • pkg/operator/operatorclient/operatorclient.go
  • pkg/operator/optionalinformer/optional_informer.go
  • pkg/operator/setup_manager.go
  • pkg/operator/starter.go
💤 Files with no reviewable changes (1)
  • pkg/controller/deployment/generic_deployment_controller.go
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

-Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity.

Files:

  • pkg/controller/istiocsr/controller.go
  • pkg/operator/setup_manager.go
  • pkg/operator/starter.go
  • pkg/controller/deployment/default_cert_manager_controller.go
  • pkg/operator/optionalinformer/optional_informer.go
  • pkg/controller/deployment/deployment_overrides.go
  • api/operator/v1alpha1/istiocsr_types.go
  • pkg/features/features.go
  • pkg/controller/istiocsr/controller_test.go
  • pkg/controller/deployment/deployment_unsupported_overrides.go
  • pkg/controller/istiocsr/certificates.go
  • pkg/controller/istiocsr/rbacs_test.go
  • pkg/controller/istiocsr/serviceaccounts_test.go
  • pkg/operator/operatorclient/operatorclient.go
  • pkg/controller/istiocsr/rbacs.go
  • pkg/controller/istiocsr/services_test.go
  • pkg/controller/istiocsr/client.go
  • pkg/controller/istiocsr/deployments.go
  • pkg/controller/istiocsr/deployments_test.go
  • pkg/controller/deployment/credentials_request.go
  • pkg/controller/istiocsr/utils.go
  • pkg/controller/istiocsr/certificates_test.go
  • api/operator/v1alpha1/certmanager_types.go
  • pkg/controller/istiocsr/install_instiocsr_test.go
  • pkg/controller/istiocsr/networkpolicies.go
  • pkg/controller/istiocsr/test_utils.go
  • main.go
🧬 Code graph analysis (4)
pkg/controller/istiocsr/rbacs.go (2)
pkg/controller/istiocsr/controller.go (1)
  • Reconciler (48-55)
api/operator/v1alpha1/istiocsr_types.go (1)
  • IstioCSR (48-64)
pkg/controller/istiocsr/deployments.go (3)
pkg/controller/istiocsr/errors.go (1)
  • NewIrrecoverableError (28-37)
api/operator/v1alpha1/istiocsr_types.go (1)
  • IstioCSRConfig (80-159)
api/operator/v1alpha1/certmanager_types.go (1)
  • CertManager (191-200)
pkg/controller/istiocsr/utils.go (3)
api/operator/v1alpha1/groupversion_info.go (1)
  • SchemeGroupVersion (29-29)
api/operator/v1alpha1/istiocsr_types.go (1)
  • IstioCSR (48-64)
api/operator/v1alpha1/conditions.go (2)
  • Ready (27-27)
  • ReasonFailed (31-31)
pkg/controller/istiocsr/networkpolicies.go (2)
api/operator/v1alpha1/certmanager_types.go (1)
  • NetworkPolicy (247-272)
pkg/operator/applyconfigurations/operator/v1alpha1/networkpolicy.go (1)
  • NetworkPolicy (20-22)
🔇 Additional comments (42)
pkg/features/features.go (1)

22-27: Well-reasoned lint suppression with clear justification.

The //nolint:wrapcheck annotation is appropriate here. The comment clearly explains that featuregate.Set() already returns contextually meaningful errors, eliminating the need for additional error wrapping. This is a pragmatic approach to lint fixes that avoids artificial wrapper layers when they don't add value.

pkg/controller/deployment/credentials_request.go (1)

23-23: Lint suppressions for path/volume constants are appropriate.

The //nolint:gosec comments correctly identify these as path and volume name constants rather than hardcoded credentials. This aligns with the security intent behind the G101 rule.

Also applies to: 29-29

pkg/controller/deployment/deployment_unsupported_overrides.go (2)

42-45: LGTM!

The wrapcheck suppression is appropriate here. json.Unmarshal errors already include sufficient context about the unmarshaling failure, and the calling context (UnsupportedConfigOverrides.Raw) is evident from the surrounding code.


47-48: LGTM!

The suppression is well-justified. Since unsupportedConfigOverrides modifies the deployment via pointer, the assignment is technically redundant but keeping it documents the intent that the deployment is being transformed at this point.

pkg/controller/deployment/deployment_overrides.go (1)

35-35: LGTM! Appropriate gosec suppression.

The nolint comment correctly suppresses the G101 (hardcoded credentials) warning. This is a standard Kubernetes service account token directory path, not a credential.

api/operator/v1alpha1/istiocsr_types.go (1)

46-48: LGTM!

The nolint:godot directive with explanatory comment is appropriate for suppressing the linter on operator-sdk annotations that don't require trailing periods.

api/operator/v1alpha1/certmanager_types.go (1)

189-191: LGTM!

Consistent with the same pattern applied to IstioCSR type.

pkg/operator/optionalinformer/optional_informer.go (1)

57-58: LGTM!

The nolint:wrapcheck is justified here since Kubernetes discovery client errors include sufficient context. The inline comment documents the rationale.

pkg/operator/operatorclient/operatorclient.go (3)

172-176: Good rename from copy to updated.

Avoiding the builtin function name copy improves code clarity and prevents potential confusion.


207-214: LGTM!

Using slices.Contains is cleaner than manual iteration. The variable reuse for finalizers is functionally equivalent to the previous approach.


249-253: LGTM!

The nolint:wrapcheck directives throughout this file are consistent with the configured exclusions for Kubernetes client interfaces where wrapping adds no value.

.golangci.yaml (3)

60-61: LGTM on depguard disable.

Good practice to document the issue reference for the temporary disable.


224-250: Comprehensive wrapcheck configuration.

The exclusions for internal packages and Kubernetes client interfaces are well-structured and reduce false positives without compromising error handling quality.


275-279: The staticcheck configuration format is correct for golangci-lint v2. The use of checks: ["all", "-SA4006", "-SA4031"] properly disables specific checks while enabling all others, and the explanatory comments justify the disables appropriately.

pkg/controller/istiocsr/test_utils.go (1)

39-41: Good rename following Go conventions.

Prefixing error variables with err (e.g., errTestClient) follows Go naming conventions and improves code consistency.

main.go (1)

30-31: LGTM!

Explicitly ignoring the Help() error is acceptable here since the program exits immediately afterward regardless of success or failure.

pkg/controller/istiocsr/serviceaccounts_test.go (2)

45-50: LGTM!

Consistent usage of the renamed errTestClient variable from test_utils.go.


55-63: LGTM!

Test case correctly uses the renamed error variable while maintaining the expected error message.

pkg/controller/istiocsr/networkpolicies.go (1)

47-50: LGTM! Type-safe assertion prevents panics.

The checked type assertion correctly handles type mismatches by returning a descriptive error instead of panicking. This aligns with the PR's forcetypeassert lint fix objective.

pkg/operator/setup_manager.go (1)

82-82: LGTM! Appropriate lint suppression.

The nolint directive is justified since manager errors already provide contextual information, making additional wrapping redundant.

pkg/controller/istiocsr/certificates.go (1)

77-81: LGTM! Efficient slice pre-allocation.

Pre-allocating the slice capacity prevents reallocations during subsequent appends, improving performance while maintaining the same functional behavior.

pkg/controller/istiocsr/services_test.go (1)

48-48: LGTM! Consistent test error naming.

The renaming from testError to errTestClient improves clarity and aligns with the broader test refactoring across IstioCSR test files.

Also applies to: 61-61, 84-84

pkg/controller/istiocsr/certificates_test.go (1)

37-37: LGTM! Consistent test error naming.

These changes align with the test refactoring to use errTestClient consistently across IstioCSR test files.

Also applies to: 67-67, 116-116

pkg/controller/istiocsr/deployments_test.go (1)

119-119: LGTM! Consistent test error naming.

All instances updated to use errTestClient, maintaining consistency with the broader test refactoring effort.

Also applies to: 170-170, 220-220, 363-363, 530-530, 566-566

pkg/controller/istiocsr/controller_test.go (1)

147-147: LGTM! Consistent test error naming.

The error variable renaming maintains consistency with the test refactoring across all IstioCSR controller tests.

Also applies to: 379-379, 401-401, 682-682, 731-731

pkg/controller/istiocsr/install_instiocsr_test.go (1)

75-75: LGTM! Consistent test error naming.

These final updates complete the consistent error variable naming across all IstioCSR test files.

Also applies to: 88-88, 104-104

pkg/controller/istiocsr/controller.go (2)

106-106: LGTM!

The nolint:wrapcheck comment is appropriate here since cache.New returns errors that are already contextual and don't need additional wrapping in this thin wrapper function.


130-130: LGTM!

The lint suppression comments are well-justified:

  • nestif suppressions for complex but necessary control flow in label processing and deployment reconciliation
  • wrapcheck for builder chain that returns contextual errors
  • unparam for error return kept for future implementation (as noted in the TODO)

Also applies to: 198-199, 275-275, 332-334

pkg/controller/istiocsr/client.go (2)

78-82: LGTM - Good type-safe object instantiation.

The reflection-based object creation with explicit type assertion prevents potential panics from unchecked type assertions and provides a clear error message if the assertion fails.


46-46: LGTM!

The nolint:wrapcheck comments are appropriate for these thin wrapper methods - the underlying client errors are already contextual and wrapping would add redundant information.

Also applies to: 52-52, 58-58, 64-64, 70-70, 92-92, 101-101, 107-107, 115-115

pkg/operator/starter.go (2)

48-48: LGTM!

The nolint:wrapcheck comments are appropriate - NewForConfig errors are already contextual from the Kubernetes client library.

Also applies to: 53-53, 58-58, 83-83


149-149: LGTM!

The nolint:contextcheck is correctly applied and well-documented. SetupSignalHandler intentionally creates a new context for OS signal handling rather than using the passed context, which is the expected pattern for graceful shutdown.

pkg/controller/istiocsr/rbacs_test.go (1)

31-31: LGTM!

Consistent renaming of test error variable to errTestClient follows Go conventions for error variable naming (err prefix) and aligns with the updated sentinel defined in test_utils.go.

Also applies to: 47-47, 63-63, 76-76, 90-90, 105-105, 119-119

pkg/controller/istiocsr/deployments.go (3)

32-32: LGTM!

Renaming invalidIssuerRefConfigError to errInvalidIssuerRefConfig follows Go naming conventions for package-level error variables.


253-260: LGTM - Type-safe issuer handling.

The type switch with explicit handling for ClusterIssuer and Issuer types, plus a default case that returns an irrecoverable error, eliminates the risk of panics from unchecked type assertions while providing clear error messages for unexpected types.


366-373: LGTM!

Consistent application of the same type switch pattern in handleIssuerBasedCA ensures type safety throughout the issuer handling code paths.

pkg/controller/istiocsr/rbacs.go (2)

135-146: LGTM!

Renaming parameter from new to desired avoids shadowing Go's builtin new function and improves code clarity by using consistent terminology (desired vs existing/fetched) throughout the codebase.


225-236: LGTM!

Consistent parameter renaming applied to updateClusterRoleBindingNameInStatus.

pkg/controller/istiocsr/utils.go (4)

66-66: LGTM!

The nolint:wrapcheck is appropriate - the retry loop already wraps errors with context before returning.


163-173: LGTM - Hardened decode helpers.

Adding checked type assertions to decode functions provides clear panic messages if static assets contain unexpected types. Since these decode static manifests bundled with the operator, a type mismatch indicates a programming/build error that should fail fast.

Also applies to: 175-185, 187-197, 199-209, 211-221, 223-233, 235-245, 247-257


265-322: LGTM!

The added type assertions in hasObjectChanged provide defense-in-depth, though the initial reflect.TypeOf check at line 260-262 should already catch type mismatches. The explicit assertions give clearer panic messages.


502-517: LGTM - Good helper extraction.

handleProcessingRejection cleanly consolidates the status condition update and annotation handling, reducing duplication and improving maintainability.

@anandkuma77 anandkuma77 marked this pull request as ready for review December 24, 2025 05:07
@openshift-ci openshift-ci bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Dec 24, 2025
@openshift-ci openshift-ci bot requested a review from swghosh December 24, 2025 05:08
@PillaiManish
Copy link
Member

/retest

Copy link
Member

@PillaiManish PillaiManish left a comment

Choose a reason for hiding this comment

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

Looks good to me, just we need to check why the CI job is failing.

Comment on lines 168 to 172
deployment, ok := obj.(*appsv1.Deployment)
if !ok {
panic(fmt.Sprintf("decoded object is not a Deployment, got %T", obj))
}
return deployment
Copy link
Member

@PillaiManish PillaiManish Dec 29, 2025

Choose a reason for hiding this comment

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

What was the reason to modify this?

Copy link
Author

Choose a reason for hiding this comment

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

We are typecasting here, so we are checking if the typecasting is successful or not. The ok bool has value true if the typecasting successful otherwise it has false value

Copy link
Author

Choose a reason for hiding this comment

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

We are doing it at multiple places.

@anandkuma77
Copy link
Author

/retest

1 similar comment
@anandkuma77
Copy link
Author

/retest

Copy link
Member

Choose a reason for hiding this comment

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

I think we should have proper reasoning and trackers for all the exclusions to be fixed in the future.

@anandkuma77
Copy link
Author

/retest

Copy link

@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

Caution

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

⚠️ Outside diff range comments (1)
test/e2e/issuer_acme_dns01_test.go (1)

295-314: Add deployment rollout wait to GCP credentials setup for consistency.

The setupAmbientGCPCredentials function (lines 309-313) patches the subscription with environment variables but lacks the corresponding deployment rollout synchronization step present in setupAmbientAWSCredentials (lines 250-256). Both functions perform identical subscription patches and should synchronize the cert-manager deployment rollout to prevent potential test flakiness:

By("waiting for cert-manager deployment to rollout with new credentials")
err = waitForDeploymentRollout(ctx, "cert-manager", "cert-manager", 2*time.Minute)
Expect(err).NotTo(HaveOccurred(), "timeout waiting for cert-manager deployment rollout")
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between c3b053f and bd61e67.

📒 Files selected for processing (1)
  • test/e2e/issuer_acme_dns01_test.go
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

-Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity.

Files:

  • test/e2e/issuer_acme_dns01_test.go
🔇 Additional comments (1)
test/e2e/issuer_acme_dns01_test.go (1)

250-252: LGTM! Improves test reliability.

The addition of a synchronous wait for the cert-manager deployment rollout after patching the subscription prevents race conditions and ensures the deployment has picked up the new credentials before proceeding. This follows the established pattern used elsewhere in the test suite (lines 772, 841, 1095) and uses a consistent 2-minute timeout.

@anandkuma77
Copy link
Author

/retest

1 similar comment
@anandkuma77
Copy link
Author

/retest

@anandkuma77 anandkuma77 force-pushed the anandkuma77/cm-841-lint-fix branch from f1825dd to c3b053f Compare January 8, 2026 08:47
Fix forcetypeassert, contextcheck, wastedassign, and makezero lint errors
across istiocsr and deployment controller packages. Disable depguard due
to golangci-lint v2 configuration issues.
@anandkuma77 anandkuma77 force-pushed the anandkuma77/cm-841-lint-fix branch from c3b053f to 28de263 Compare January 8, 2026 08:51
Copy link

@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 (5)
pkg/controller/deployment/deployment_overrides.go (1)

197-200: Consider wrapping for consistency.

The wrapcheck suppression is acceptable for this lint-fix PR. However, note the inconsistency: Line 198 wraps NotFound errors with application context, while Line 200 returns other lister errors unwrapped. For consistency, consider wrapping both cases with context about the trusted CA configmap validation.

♻️ Optional: Consistent error wrapping
-		return err //nolint:wrapcheck // error from lister is already contextual
+		return fmt.Errorf("failed to get trusted CA config map %q: %w", trustedCAConfigmapName, err)
pkg/controller/deployment/credentials_request.go (1)

50-50: Inconsistent error handling approach.

While the wrapcheck suppressions are acceptable for this lint-fix PR, note that Line 48 wraps NotFound errors with context, but other lister errors (lines 50, 55) are returned without additional context. For consistency and better debuggability, consider wrapping all errors to indicate which operation failed.

♻️ Optional: Consistent error wrapping
-		return err //nolint:wrapcheck // error from lister is already contextual
+		return fmt.Errorf("failed to get cloud secret %q: %w", secretName, err)
-		return err //nolint:wrapcheck // error from lister is already contextual
+		return fmt.Errorf("failed to get infrastructure config: %w", err)

Also applies to: 55-55

pkg/controller/deployment/deployment_unsupported_overrides.go (1)

42-45: Consider wrapping the unmarshal error for better debugging context.

While json.Unmarshal errors are self-descriptive, adding context about which configuration field failed to unmarshal would significantly aid production debugging.

🔧 Suggested improvement
 	err := json.Unmarshal(operatorSpec.UnsupportedConfigOverrides.Raw, cfg)
 	if err != nil {
-		return err //nolint:wrapcheck // json.Unmarshal error is already clear
+		return fmt.Errorf("failed to unmarshal unsupported config overrides: %w", err)
 	}

Add fmt to imports:

import (
	"encoding/json"
	"fmt"
	// ... rest of imports
)
pkg/controller/istiocsr/deployments.go (1)

366-373: Consider extracting duplicate type-switch logic.

This type switch is identical to the one in assertIssuerRefExists (lines 253-260). Consider extracting a helper function like getIssuerConfig(obj client.Object) (certmanagerv1.IssuerConfig, error) to reduce duplication.

♻️ Suggested helper function
func getIssuerConfig(obj client.Object) (certmanagerv1.IssuerConfig, error) {
	switch typedObj := obj.(type) {
	case *certmanagerv1.ClusterIssuer:
		return typedObj.Spec.IssuerConfig, nil
	case *certmanagerv1.Issuer:
		return typedObj.Spec.IssuerConfig, nil
	default:
		return certmanagerv1.IssuerConfig{}, fmt.Errorf("unexpected issuer type %T, expected ClusterIssuer or Issuer", obj)
	}
}
.golangci.yaml (1)

275-279: Remove the redundant staticcheck exclusions from linters-settings.

The checks exclusions at lines 278-279 duplicate the issues-level text pattern exclusion already in place at lines 147-149, which covers SA4006|SA4031. These rules are already excluded globally; remove the redundant staticcheck.checks configuration to simplify the config. If targeted exclusions are preferred instead of global, add //nolint:staticcheck directives at specific locations and remove both this and the issues-level pattern.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between d6ba138 and 28de263.

📒 Files selected for processing (29)
  • .golangci.yaml
  • api/operator/v1alpha1/certmanager_types.go
  • api/operator/v1alpha1/istiocsr_types.go
  • main.go
  • pkg/controller/deployment/credentials_request.go
  • pkg/controller/deployment/default_cert_manager_controller.go
  • pkg/controller/deployment/deployment_overrides.go
  • pkg/controller/deployment/deployment_unsupported_overrides.go
  • pkg/controller/deployment/generic_deployment_controller.go
  • pkg/controller/istiocsr/certificates.go
  • pkg/controller/istiocsr/certificates_test.go
  • pkg/controller/istiocsr/client.go
  • pkg/controller/istiocsr/controller.go
  • pkg/controller/istiocsr/controller_test.go
  • pkg/controller/istiocsr/deployments.go
  • pkg/controller/istiocsr/deployments_test.go
  • pkg/controller/istiocsr/install_instiocsr_test.go
  • pkg/controller/istiocsr/networkpolicies.go
  • pkg/controller/istiocsr/rbacs.go
  • pkg/controller/istiocsr/rbacs_test.go
  • pkg/controller/istiocsr/serviceaccounts_test.go
  • pkg/controller/istiocsr/services_test.go
  • pkg/controller/istiocsr/test_utils.go
  • pkg/controller/istiocsr/utils.go
  • pkg/features/features.go
  • pkg/operator/operatorclient/operatorclient.go
  • pkg/operator/optionalinformer/optional_informer.go
  • pkg/operator/setup_manager.go
  • pkg/operator/starter.go
💤 Files with no reviewable changes (1)
  • pkg/controller/deployment/generic_deployment_controller.go
🚧 Files skipped from review as they are similar to previous changes (14)
  • pkg/controller/istiocsr/certificates.go
  • pkg/controller/deployment/default_cert_manager_controller.go
  • pkg/operator/setup_manager.go
  • pkg/features/features.go
  • api/operator/v1alpha1/certmanager_types.go
  • pkg/controller/istiocsr/certificates_test.go
  • pkg/controller/istiocsr/deployments_test.go
  • pkg/operator/operatorclient/operatorclient.go
  • pkg/controller/istiocsr/rbacs_test.go
  • pkg/controller/istiocsr/install_instiocsr_test.go
  • pkg/operator/optionalinformer/optional_informer.go
  • pkg/operator/starter.go
  • pkg/controller/istiocsr/rbacs.go
  • main.go
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

-Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity.

Files:

  • pkg/controller/deployment/credentials_request.go
  • pkg/controller/istiocsr/networkpolicies.go
  • pkg/controller/deployment/deployment_unsupported_overrides.go
  • api/operator/v1alpha1/istiocsr_types.go
  • pkg/controller/istiocsr/services_test.go
  • pkg/controller/istiocsr/controller.go
  • pkg/controller/istiocsr/controller_test.go
  • pkg/controller/deployment/deployment_overrides.go
  • pkg/controller/istiocsr/utils.go
  • pkg/controller/istiocsr/serviceaccounts_test.go
  • pkg/controller/istiocsr/client.go
  • pkg/controller/istiocsr/deployments.go
  • pkg/controller/istiocsr/test_utils.go
🧬 Code graph analysis (3)
pkg/controller/istiocsr/utils.go (2)
api/operator/v1alpha1/istiocsr_types.go (1)
  • IstioCSR (48-64)
api/operator/v1alpha1/conditions.go (2)
  • Ready (27-27)
  • ReasonFailed (31-31)
pkg/controller/istiocsr/client.go (2)
pkg/version/version.go (1)
  • Get (24-32)
pkg/controller/istiocsr/controller.go (1)
  • New (110-122)
pkg/controller/istiocsr/deployments.go (2)
pkg/controller/istiocsr/errors.go (1)
  • NewIrrecoverableError (28-37)
api/operator/v1alpha1/certmanager_types.go (1)
  • CertManager (191-200)
🔇 Additional comments (23)
pkg/controller/deployment/deployment_overrides.go (1)

35-35: LGTM! Appropriate lint suppression.

The gosec G101 suppression is correct—this is a path constant, not a credential. The justification comment is clear.

pkg/controller/deployment/credentials_request.go (1)

23-23: LGTM! Appropriate gosec suppressions.

The nolint directives correctly suppress false-positive credential warnings on path and volume name constants. The justification comments clearly explain these are not actual credentials.

Also applies to: 29-29

pkg/controller/deployment/deployment_unsupported_overrides.go (1)

47-47: Lint suppression is acceptable.

The wastedassign suppression is justified here. While the assignment appears redundant since unsupportedConfigOverrides modifies the deployment in place, keeping the assignment maintains consistency with the function's return contract.

api/operator/v1alpha1/istiocsr_types.go (1)

46-47: LGTM!

The nolint:godot directive appropriately suppresses the linter for the operator-sdk annotation, which is a machine-readable marker that doesn't follow sentence conventions.

pkg/controller/istiocsr/deployments.go (2)

32-32: LGTM!

Renaming to errInvalidIssuerRefConfig follows Go's idiomatic naming convention for unexported error variables.


253-260: LGTM!

The type switch safely handles both ClusterIssuer and Issuer types with a proper default case for unexpected types, eliminating potential panics from unsafe type assertions.

.golangci.yaml (2)

60-61: LGTM!

Disabling depguard with a clear comment referencing the GitHub issue provides good documentation for future maintainers.


224-250: LGTM!

The wrapcheck configuration is well-structured with appropriate ignore patterns for internal packages and standard Kubernetes client interfaces where additional wrapping would add noise without value.

pkg/controller/istiocsr/client.go (2)

33-41: LGTM!

Using the manager's client directly is the correct approach - it ensures the reconciler reads from the same cache that the controller's watches use, preventing cache mismatch issues.


78-82: LGTM - safe type assertion pattern.

The reflection-based approach correctly creates a new instance matching the concrete type of obj, then safely asserts it to client.Object with an ok check. This eliminates the potential panic from direct type assertions while preserving the original retry-with-fresh-fetch semantics.

pkg/controller/istiocsr/utils.go (3)

168-172: LGTM!

Safe type assertion with explicit error message on mismatch. Panicking here is appropriate since a type mismatch indicates a programming error (wrong asset being decoded), not a runtime condition.


265-271: Redundant but linter-compliant type checks.

The ok checks on lines 267-270 will always succeed because line 260 already verifies type equality via reflect.TypeOf. While redundant at runtime, these satisfy the forcetypeassert linter requirement. The pattern is acceptable for this lint-fix PR.


502-517: LGTM - good helper extraction!

The handleProcessingRejection method consolidates the status condition update and annotation logic, reducing duplication in disallowMultipleIstioCSRInstances. The error aggregation properly handles partial failures.

pkg/controller/istiocsr/networkpolicies.go (1)

47-50: LGTM!

Safe type assertion with descriptive error return. Unlike the decode* functions in utils.go that panic (since they're for known static assets), this function correctly returns an error since the asset path comes from runtime iteration.

pkg/controller/istiocsr/test_utils.go (1)

40-40: LGTM!

Renaming to errTestClient follows Go's idiomatic naming convention for error variables, maintaining consistency with similar changes elsewhere in the PR.

pkg/controller/istiocsr/serviceaccounts_test.go (1)

45-45: LGTM! Consistent test error sentinel renaming.

The update from testError to errTestClient in test mocks is consistent with the broader test suite standardization mentioned in the PR summary.

Also applies to: 58-58

pkg/controller/istiocsr/services_test.go (1)

48-48: LGTM! Consistent test error sentinel renaming.

The changes align with the test suite standardization pattern, replacing testError with errTestClient across service-related test mocks.

Also applies to: 61-61, 84-84

pkg/controller/istiocsr/controller.go (5)

106-106: Verify that cache.New provides sufficient error context.

The //nolint:wrapcheck directive assumes cache.New returns contextual errors. Ensure that errors from cache.New include enough information to identify the failure point during cache initialization.


130-130: LGTM! Complexity acknowledged in lint suppression.

The //nolint:nestif directive appropriately acknowledges the complexity in label processing logic. While this could be refactored in a future PR, the suppression is reasonable given this PR's focus on resolving linter errors.


198-198: Verify that builder.Complete() provides sufficient error context.

The //nolint:wrapcheck directive assumes errors from builder.Complete() are already contextual. Ensure that controller setup failures provide clear diagnostic information to identify which watch or configuration step failed.


275-275: LGTM! Complexity acknowledged in lint suppression.

The //nolint:nestif directive appropriately acknowledges the complexity in deployment reconciliation error handling. The nested logic differentiates between irrecoverable and recoverable errors, which justifies the complexity.


332-334: LGTM! Appropriate use of nolint for future implementation.

The //nolint:unparam directive is justified here. The function signature is intentionally designed to support future cleanup logic (as indicated by the TODO on line 335), even though the current implementation returns static values.

pkg/controller/istiocsr/controller_test.go (1)

147-147: LGTM! Comprehensive test error sentinel standardization.

All mock error returns have been consistently updated from testError to errTestClient across controller test scenarios, maintaining alignment with the test suite standardization pattern.

Also applies to: 379-379, 401-401, 605-605, 682-682, 731-731

Anand Kumar added 2 commits January 8, 2026 14:36
- Update generic_deployment_controller.go
- Refactor istiocsr certificates, client, deployments, and utils
- Simplify and optimize controller code
- Rename invalidIssuerRefConfigError to errInvalidIssuerRefConfig to conform to errname lint rule
- Wrap all error returns in client.go methods with fmt.Errorf for proper error wrapping
- Wrap RetryOnConflict error in utils.go status update function

This fixes 1 errname and 10 wrapcheck lint errors as requested.
@anandkuma77
Copy link
Author

/retest

Anand Kumar added 2 commits January 8, 2026 21:58
- Add type assertion checks with ok pattern in client.go UpdateWithRetry
- Fix type assertions in deployments.go assertIssuerRefExists and handleIssuerBasedCA
- Fix all type assertions in utils.go decode functions and type switch cases
- Ensure all type assertions are properly checked before use
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
pkg/controller/istiocsr/deployments.go (1)

375-385: Consider improving error message clarity.

The safe type assertions are correctly implemented. However, the error message "failed to fetch issuer" on type conversion failure is slightly misleading since the issuer was successfully fetched but the type conversion failed. A more accurate message would be "failed to convert issuer to expected type" or similar.

Additionally, getIssuer is called in both assertIssuerRefExists (line 247) and handleIssuerBasedCA (line 367), which results in duplicate API calls. Consider storing the result from assertIssuerRefExists to avoid the redundant call.

♻️ Suggested improvements

Option 1: Improve error message

 clusterIssuer, ok := obj.(*certmanagerv1.ClusterIssuer)
 if !ok {
-    return FromClientError(fmt.Errorf("failed to convert to ClusterIssuer"), "failed to fetch issuer")
+    return FromClientError(fmt.Errorf("failed to convert to ClusterIssuer"), "failed to convert issuer to expected type")
 }
 issuer, ok := obj.(*certmanagerv1.Issuer)
 if !ok {
-    return FromClientError(fmt.Errorf("failed to convert to Issuer"), "failed to fetch issuer")
+    return FromClientError(fmt.Errorf("failed to convert to Issuer"), "failed to convert issuer to expected type")
 }

Option 2: Cache issuer object to avoid duplicate getIssuer calls

Consider modifying assertIssuerRefExists to return the fetched issuer object, and then pass it to handleIssuerBasedCA instead of fetching again.

pkg/controller/istiocsr/utils.go (1)

260-357: LGTM! Consider reducing redundancy in type checks.

The safe type assertions are correctly implemented and add defensive programming. However, since line 260 already verifies that desired and fetched have the same type using reflect.TypeOf, the type assertions within each case block will always succeed. This redundancy doesn't cause issues but could be simplified.

♻️ Optional simplification

Given the type equality check at line 260, you could simplify by either:

Option 1: Keep the initial type check and use direct type assertions (without ok-checks) in each case, relying on the upfront validation.

Option 2: Remove the initial type check and keep the ok-checks in each case (current defensive approach).

The current implementation prioritizes safety over brevity, which is a valid choice for production code.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 1115c3f and 4740bd2.

📒 Files selected for processing (3)
  • pkg/controller/istiocsr/client.go
  • pkg/controller/istiocsr/deployments.go
  • pkg/controller/istiocsr/utils.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/controller/istiocsr/client.go
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

-Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity.

Files:

  • pkg/controller/istiocsr/utils.go
  • pkg/controller/istiocsr/deployments.go
🧬 Code graph analysis (1)
pkg/controller/istiocsr/deployments.go (2)
pkg/controller/istiocsr/errors.go (2)
  • NewIrrecoverableError (28-37)
  • FromClientError (61-71)
test/e2e/config_template.go (1)
  • IssuerConfig (14-17)
🔇 Additional comments (3)
pkg/controller/istiocsr/deployments.go (1)

255-265: LGTM! Safe type assertions correctly implemented.

The defensive type assertions with ok-checks are properly implemented, and the error handling using NewIrrecoverableError is appropriate for invalid issuer configurations. This change successfully addresses the golangci-lint forcetypeassert warnings.

pkg/controller/istiocsr/utils.go (2)

168-256: LGTM! Defensive type assertions correctly implemented in decode functions.

All decode functions consistently implement safe type assertions with ok-checks and panic on failure. The panic approach is appropriate here since these functions decode static assets, and type assertion failures would indicate programming errors (incorrect asset content) rather than runtime conditions.


443-515: LGTM! Generic functions correctly implement safe type assertions.

The safe type assertions in the generic RBAC comparison functions are correctly implemented using the any() conversion pattern required for Go generics. The panic on type assertion failure is appropriate since these would indicate type constraint violations (programming errors).

@anandkuma77
Copy link
Author

/retest

Anand Kumar added 2 commits January 9, 2026 19:56
Wrapped all unwrapped errors with fmt.Errorf using %w verb to properly preserve error context.
Copy link

@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

Caution

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

⚠️ Outside diff range comments (1)
pkg/controller/istiocsr/client.go (1)

91-114: UpdateWithRetry: improve safety with DeepCopyObject and defensive error handling.

  • reflect.TypeOf(obj).Elem() will panic if obj is nil or not a pointer. While all current callers pass valid objects, using obj.DeepCopyObject() is safer and more idiomatic.
  • Wrapping the Update(...) error in fmt.Errorf is safe with k8s v0.33.2+ (errors.IsConflict properly unwraps), but explicitly returning unwrapped conflict errors improves clarity and follows defensive patterns in similar retry loops.
Proposed change
 func (c *ctrlClientImpl) UpdateWithRetry(
 	ctx context.Context, obj client.Object, opts ...client.UpdateOption,
 ) error {
 	key := client.ObjectKeyFromObject(obj)
 	if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
-		currentInterface := reflect.New(reflect.TypeOf(obj).Elem()).Interface()
-		current, ok := currentInterface.(client.Object)
+		currentRuntime := obj.DeepCopyObject()
+		current, ok := currentRuntime.(client.Object)
 		if !ok {
-			return fmt.Errorf("failed to convert to client.Object")
+			return fmt.Errorf("failed to convert to client.Object (got %T)", currentRuntime)
 		}
 		if err := c.Client.Get(ctx, key, current); err != nil {
 			return fmt.Errorf("failed to fetch latest %q for update: %w", key, err)
 		}
 		obj.SetResourceVersion(current.GetResourceVersion())
 		if err := c.Client.Update(ctx, obj, opts...); err != nil {
-			return fmt.Errorf("failed to update %q resource: %w", key, err)
+			if apierrors.IsConflict(err) {
+				return err
+			}
+			return fmt.Errorf("failed to update %q resource: %w", key, err)
 		}
 		return nil
 	}); err != nil {
 		return fmt.Errorf("failed to update with retry %q: %w", key, err)
 	}
 
 	return nil
 }
🤖 Fix all issues with AI agents
In @pkg/controller/istiocsr/utils.go:
- Around line 593-610: The logic is inverted: when ignoreProcessing is false we
should allow the oldest instance to proceed (return nil) and when
ignoreProcessing is true we should mark/reject this instance; modify the branch
around ignoreProcessing so that if !ignoreProcessing the function returns nil,
otherwise perform the existing rejection flow (call
istiocsr.Status.SetCondition(... Ready false ...), call
r.updateCondition(istiocsr, nil) as needed, call
addProcessingRejectedAnnotation(istiocsr) and r.UpdateWithRetry(...), aggregate
condUpdateErr and annUpdateErr and return NewMultipleInstanceError(...) on
error); keep use of symbols istiocsr, ignoreProcessing, updateCondition,
addProcessingRejectedAnnotation, UpdateWithRetry and NewMultipleInstanceError to
locate and apply the change.
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between fd04023 and 947d98a.

📒 Files selected for processing (2)
  • pkg/controller/istiocsr/client.go
  • pkg/controller/istiocsr/utils.go
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

-Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity.

Files:

  • pkg/controller/istiocsr/utils.go
  • pkg/controller/istiocsr/client.go
🧬 Code graph analysis (1)
pkg/controller/istiocsr/utils.go (2)
pkg/controller/istiocsr/errors.go (1)
  • NewMultipleInstanceError (39-48)
api/operator/v1alpha1/conditions.go (1)
  • Ready (27-27)
🔇 Additional comments (5)
pkg/controller/istiocsr/utils.go (4)

66-66: LGTM: Error wrapping improves debugging context.

The error wrapping with fmt.Errorf and %w provides better context when status updates fail.


163-257: LGTM: Defensive type assertions in decode functions.

The explicit type assertions with panic on failure are appropriate for decode functions that process static manifests. If the assertion fails, it indicates a programming error or corrupted manifest, justifying the panic.


259-362: Type assertions are redundant but defensively correct.

The explicit type assertions in each case branch are technically redundant given the type equality check at line 260. However, they provide defense-in-depth against future code changes and satisfy the linter's requirements.


440-519: LGTM: Type assertions required in generic functions.

The explicit type assertions within generic functions are necessary because Go's type system doesn't automatically narrow types in switch branches when using type parameters. The panic-on-failure approach is appropriate as the type switch should guarantee the type.

pkg/controller/istiocsr/client.go (1)

43-50: Good improvement: consistent error wrapping with operation + object key context.

This should make debugging significantly easier while preserving the underlying error via %w (including NotFound handling in Exists).

To ensure no behavior changes in callers that rely on Kubernetes sentinel checks, please verify k8s.io/apimachinery/pkg/api/errors.IsNotFound/IsConflict unwrap wrapped errors for the dependency versions in this repo.

Also applies to: 52-59, 61-69, 71-79, 81-89, 116-124, 126-134, 136-144

…ate tests

- Fixed inverted condition: oldest instance now correctly returns nil to allow processing
- Updated test expectations to match new error message format after wrapping errors with fmt.Errorf
Copy link

@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

🤖 Fix all issues with AI agents
In @pkg/controller/istiocsr/utils.go:
- Around line 593-612: Add a unit test for disallowMultipleIstioCSRInstances
that covers the allowed-oldest-instance branch: create two IstioCSR objects with
different creation timestamps, ensure the one with the earliest timestamp is
processed by calling disallowMultipleIstioCSRInstances (or invoking the
controller logic that uses it) and assert it returns nil (no error), does not
set the rejection annotation, and leaves the Ready condition unchanged/true;
similarly assert the newer instance still follows the existing rejection path.
Use the same helper setup/mocks as existing tests for the rejection branch and
reference the function disallowMultipleIstioCSRInstances, the Ready condition
(v1alpha1.Ready), and addProcessingRejectedAnnotation behavior to locate where
to assert outcomes.
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 947d98a and 53af2dd.

📒 Files selected for processing (5)
  • pkg/controller/istiocsr/controller_test.go
  • pkg/controller/istiocsr/deployments_test.go
  • pkg/controller/istiocsr/rbacs_test.go
  • pkg/controller/istiocsr/serviceaccounts_test.go
  • pkg/controller/istiocsr/utils.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/controller/istiocsr/deployments_test.go
  • pkg/controller/istiocsr/controller_test.go
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

-Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity.

Files:

  • pkg/controller/istiocsr/utils.go
  • pkg/controller/istiocsr/rbacs_test.go
  • pkg/controller/istiocsr/serviceaccounts_test.go
🧬 Code graph analysis (2)
pkg/controller/istiocsr/utils.go (4)
api/operator/v1alpha1/groupversion_info.go (1)
  • SchemeGroupVersion (29-29)
api/operator/v1alpha1/certmanager_types.go (1)
  • NetworkPolicy (247-272)
pkg/operator/applyconfigurations/operator/v1alpha1/networkpolicy.go (1)
  • NetworkPolicy (20-22)
api/operator/v1alpha1/conditions.go (2)
  • Ready (27-27)
  • ReasonFailed (31-31)
pkg/controller/istiocsr/rbacs_test.go (1)
api/operator/v1alpha1/istiocsr_types.go (1)
  • IstioCSR (48-64)
🔇 Additional comments (5)
pkg/controller/istiocsr/serviceaccounts_test.go (1)

45-45: LGTM! Test updates align with error constant rename.

The changes consistently replace testError with errTestClient and update the expected error message to reflect the new error wrapping format introduced in the status update path. These updates maintain test accuracy with the refactored error handling.

Also applies to: 58-58, 63-63

pkg/controller/istiocsr/rbacs_test.go (1)

31-31: LGTM! Test mocks consistently updated with renamed error constant.

All test mock configurations have been updated to use errTestClient instead of testError, maintaining consistency with the test utility refactoring. The error message expectations (lines 258, 296) correctly reflect the new error wrapping format with the "status for" phrase in the status update path.

Also applies to: 47-47, 63-63, 76-76, 90-90, 105-105, 119-119, 176-176, 217-217, 250-250, 258-258, 287-287, 296-296, 313-313, 336-336, 358-358, 378-378, 403-403, 427-427, 450-450, 470-470, 495-495, 519-519

pkg/controller/istiocsr/utils.go (3)

66-66: LGTM! Enhanced error context for status updates.

The additional error wrapping provides clearer context by including the resource identifier when status updates fail after retries, improving debuggability while maintaining the error chain.


168-172: LGTM! Safe type assertions address linter warnings.

The explicit type assertions with descriptive panic messages appropriately address the golangci-lint forcetypeassert warnings. Since these decode functions are internal utilities called with known byte content corresponding to specific resource types, the panics serve as programming error detection rather than runtime error handling. The consistent pattern across all decode functions ensures maintainability.

Also applies to: 180-184, 192-196, 204-208, 216-220, 228-232, 240-244, 252-256


267-275: LGTM! Type assertions ensure type safety in comparisons and generic functions.

The explicit type assertions in hasObjectChanged and the generic RBAC helper functions (rbacRoleRulesModified, rbacRoleBindingRefModified, rbacRoleBindingSubjectsModified) address the forcetypeassert linter warnings while maintaining type safety.

For the generic functions, the type assertions within switch cases are necessary because Go's type system doesn't automatically narrow generic type parameters. The panics provide clear diagnostics for programming errors while keeping the runtime behavior predictable for correctly typed inputs.

Also applies to: 277-285, 287-296, 298-306, 308-316, 318-327, 329-337, 339-347, 349-357, 443-461, 470-488, 497-515

Renamed invalidIssuerRefConfigError to errInvalidIssuerRefConfig to conform to errXxx format required by errname linter.
Copy link

@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

🤖 Fix all issues with AI agents
In @pkg/controller/istiocsr/deployments.go:
- Line 239: Update the error message passed to NewIrrecoverableError (in the
errInvalidIssuerRefConfig creation for
spec.istioCSRConfig.certManager.issuerRef.kind) to correct the typo "anyof" to
"any of" so the message reads "can be any of `%s` or `%s`, configured: %s".
🧹 Nitpick comments (2)
pkg/controller/istiocsr/deployments.go (2)

375-385: Consider aligning error handling with assertIssuerRefExists for consistency.

The defensive type assertions are correct, but the error handling differs from the similar code in assertIssuerRefExists:

  • Here: FromClientError(fmt.Errorf("failed to convert to ClusterIssuer"), "failed to fetch issuer")
  • In assertIssuerRefExists: NewIrrecoverableError(errInvalidIssuerRefConfig, "failed to convert to ClusterIssuer")

Type conversion failures indicate programming errors (bugs in getIssuer), not transient client errors. Consider using NewIrrecoverableError with errInvalidIssuerRefConfig for consistency, as the error semantics are identical in both functions.

🔄 Proposed consistency fix
 	case clusterIssuerKind:
 		clusterIssuer, ok := obj.(*certmanagerv1.ClusterIssuer)
 		if !ok {
-			return FromClientError(fmt.Errorf("failed to convert to ClusterIssuer"), "failed to fetch issuer")
+			return NewIrrecoverableError(errInvalidIssuerRefConfig, "failed to convert to ClusterIssuer")
 		}
 		issuerConfig = clusterIssuer.Spec.IssuerConfig
 	case issuerKind:
 		issuer, ok := obj.(*certmanagerv1.Issuer)
 		if !ok {
-			return FromClientError(fmt.Errorf("failed to convert to Issuer"), "failed to fetch issuer")
+			return NewIrrecoverableError(errInvalidIssuerRefConfig, "failed to convert to Issuer")
 		}
 		issuerConfig = issuer.Spec.IssuerConfig

255-265: Consider extracting a helper function to reduce duplication.

Both assertIssuerRefExists (lines 255-265) and handleIssuerBasedCA (lines 375-385) contain nearly identical type assertion logic for converting the issuer object and extracting IssuerConfig. Consider extracting this into a helper function to follow the DRY principle.

💡 Example helper function
// getIssuerConfig extracts IssuerConfig from a fetched issuer object based on kind.
func getIssuerConfig(obj client.Object, issuerRefKind string) (certmanagerv1.IssuerConfig, error) {
	switch issuerRefKind {
	case clusterIssuerKind:
		clusterIssuer, ok := obj.(*certmanagerv1.ClusterIssuer)
		if !ok {
			return certmanagerv1.IssuerConfig{}, fmt.Errorf("failed to convert to ClusterIssuer")
		}
		return clusterIssuer.Spec.IssuerConfig, nil
	case issuerKind:
		issuer, ok := obj.(*certmanagerv1.Issuer)
		if !ok {
			return certmanagerv1.IssuerConfig{}, fmt.Errorf("failed to convert to Issuer")
		}
		return issuer.Spec.IssuerConfig, nil
	default:
		return certmanagerv1.IssuerConfig{}, fmt.Errorf("unsupported issuer kind: %s", issuerRefKind)
	}
}

Then both functions can use:

issuerConfig, err := getIssuerConfig(obj, issuerRefKind)
if err != nil {
	return NewIrrecoverableError(errInvalidIssuerRefConfig, err.Error())
}

Also applies to: 375-385

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 53af2dd and 96b8883.

📒 Files selected for processing (1)
  • pkg/controller/istiocsr/deployments.go
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

-Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity.

Files:

  • pkg/controller/istiocsr/deployments.go
🔇 Additional comments (2)
pkg/controller/istiocsr/deployments.go (2)

32-32: LGTM!

The error variable renaming from invalidIssuerRefConfigError to errInvalidIssuerRefConfig correctly follows Go naming conventions for error variables and satisfies the errname linter requirement.


255-265: LGTM!

The defensive type assertions with ok-checks correctly address the forcetypeassert linter requirement. While these assertions should always succeed given the getIssuer implementation, the defensive checks are valuable for catching potential bugs and make the code more robust.

@anandkuma77
Copy link
Author

/retest

- Fixed makezero errors in certificates.go by initializing slice with length 0 and appropriate capacity
- Fixed typo in deployments.go: changed 'anyof' to 'any of' in error message
Copy link

@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

Caution

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

⚠️ Outside diff range comments (2)
pkg/controller/istiocsr/deployments.go (2)

236-272: Fix incorrect “configured” value in issuerRef kind error message (currently always prints issuerKind).

At Line 239 the last format arg is issuerKind, so the message won’t reflect what the user actually configured.

Proposed fix
 func (r *Reconciler) assertIssuerRefExists(istiocsr *v1alpha1.IstioCSR) error {
 	issuerRefKind := strings.ToLower(istiocsr.Spec.IstioCSRConfig.CertManager.IssuerRef.Kind)
 	if issuerRefKind != clusterIssuerKind && issuerRefKind != issuerKind {
-		return NewIrrecoverableError(errInvalidIssuerRefConfig, "spec.istioCSRConfig.certManager.issuerRef.kind can be any of `%s` or `%s`, configured: %s", clusterIssuerKind, issuerKind, issuerKind)
+		return NewIrrecoverableError(errInvalidIssuerRefConfig, "spec.istioCSRConfig.certManager.issuerRef.kind can be any of `%s` or `%s`, configured: %s", clusterIssuerKind, issuerKind, issuerRefKind)
 	}

Also: the ok-checked assertions are a solid improvement and align with the PR lint objectives.


362-386: Don’t wrap type-conversion failures as “failed to fetch issuer” client errors.

If the conversion fails, the issuer was fetched; it’s an unexpected object type / internal inconsistency. Using FromClientError(..., "failed to fetch issuer") is misleading (and may affect retry behavior depending on FromClientError semantics).

Suggested adjustment
 	switch issuerRefKind {
 	case clusterIssuerKind:
 		clusterIssuer, ok := obj.(*certmanagerv1.ClusterIssuer)
 		if !ok {
-			return FromClientError(fmt.Errorf("failed to convert to ClusterIssuer"), "failed to fetch issuer")
+			return NewIrrecoverableError(errInvalidIssuerRefConfig, "unexpected issuer object type for kind %q: got %T, want *certmanagerv1.ClusterIssuer", issuerRefKind, obj)
 		}
 		issuerConfig = clusterIssuer.Spec.IssuerConfig
 	case issuerKind:
 		issuer, ok := obj.(*certmanagerv1.Issuer)
 		if !ok {
-			return FromClientError(fmt.Errorf("failed to convert to Issuer"), "failed to fetch issuer")
+			return NewIrrecoverableError(errInvalidIssuerRefConfig, "unexpected issuer object type for kind %q: got %T, want *certmanagerv1.Issuer", issuerRefKind, obj)
 		}
 		issuerConfig = issuer.Spec.IssuerConfig
 	}
🧹 Nitpick comments (1)
pkg/controller/istiocsr/deployments.go (1)

32-32: Prefer errors.New for a non-formatted sentinel error.

fmt.Errorf("...") works here (no formatting), but errors.New(...) is the idiomatic sentinel and makes it clearer this should never wrap another error.

Proposed tweak
+import (
 	"crypto/x509"
 	"encoding/pem"
+	"errors"
 	"fmt"
 	"os"
 	"reflect"
 	"strings"
 	"unsafe"
@@
-var errInvalidIssuerRefConfig = fmt.Errorf("invalid issuerRef config")
+var errInvalidIssuerRefConfig = errors.New("invalid issuerRef config")
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 96b8883 and 9c0482b.

📒 Files selected for processing (2)
  • pkg/controller/istiocsr/certificates.go
  • pkg/controller/istiocsr/deployments.go
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

-Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity.

Files:

  • pkg/controller/istiocsr/certificates.go
  • pkg/controller/istiocsr/deployments.go
🧬 Code graph analysis (1)
pkg/controller/istiocsr/certificates.go (1)
api/operator/v1alpha1/istiocsr_types.go (2)
  • IstioCSRConfig (80-159)
  • IstiodTLSConfig (185-250)
🔇 Additional comments (1)
pkg/controller/istiocsr/certificates.go (1)

77-78: LGTM! Efficient pre-allocation strategy.

The change correctly addresses the makezero lint error by initializing the slice with zero length and pre-allocating capacity for both CertificateDNSNames and Revisions. This prevents multiple reallocations during the append operations in the revision loop (lines 82-93), improving performance compared to the previous approach.

Anand Kumar added 2 commits January 11, 2026 21:04
Fixed the test expectation for invalid issuerRef kind error message.
The test expected 'anyof' but the actual error message uses 'any of'.
Updated the test to match the actual error message format.
Fixed gocritic typeSwitchVar error by using type switch with assignment.
Removed unnecessary explicit type arguments from generic function calls
since Go can infer them from the function arguments.

- Changed switch desired.(type) to switch desiredObj := desired.(type)
- Removed explicit type arguments from rbacRoleRulesModified calls
- Removed explicit type arguments from rbacRoleBindingRefModified calls
- Removed explicit type arguments from rbacRoleBindingSubjectsModified calls
Copy link

@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

Caution

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

⚠️ Outside diff range comments (1)
pkg/controller/istiocsr/utils.go (1)

520-577: Fix namespace-scoped logic and error wrapping consistency

The loop at line 544 skips only same-namespace items, which allows multiple IstioCSRs in the same namespace to both attempt processing (as long as they're not older than instances in other namespaces). This contradicts the statusMessage implying one instance total. Change the skip condition to item.GetNamespace() == istiocsr.GetNamespace() && item.GetName() == istiocsr.GetName() to skip only self.

Also, lines 572-574 return a plain utilerrors.NewAggregate() on update failures, whereas lines 530 and 576 wrap errors in NewMultipleInstanceError(). This inconsistency causes the caller's IsMultipleInstanceError(err) check to fail when updates fail, changing reconciliation behavior from returning nil to propagating an error. Always wrap the aggregated errors in NewMultipleInstanceError(), whether updates succeed or fail.

Proposed fix
 	ignoreProcessing := false
 	for _, item := range istiocsrList.Items {
-		if item.GetNamespace() == istiocsr.Namespace {
+		if item.GetNamespace() == istiocsr.GetNamespace() && item.GetName() == istiocsr.GetName() {
 			continue
 		}
 		if item.CreationTimestamp.Time.Before(istiocsr.CreationTimestamp.Time) ||
 			// Even when timestamps are equal will skip processing. And if this ends
 			// up in ignoring all istiocsr instances, which means user must have created
 			// all in parallel, onus is on user to delete all and recreate just one required
 			// instance of istiocsr.
 			item.CreationTimestamp.Time.Equal(istiocsr.CreationTimestamp.Time) {
 			ignoreProcessing = true
 		}
 	}

 	if !ignoreProcessing {
 		// This is the oldest instance, allow it to proceed
 		return nil
 	}

 	// This instance should be rejected as there's an older or equally old instance
 	var condUpdateErr, annUpdateErr error
 	if istiocsr.Status.SetCondition(v1alpha1.Ready, metav1.ConditionFalse, v1alpha1.ReasonFailed, statusMessage) {
 		condUpdateErr = r.updateCondition(istiocsr, nil)
 	}
 	if addProcessingRejectedAnnotation(istiocsr) {
 		if err := r.UpdateWithRetry(r.ctx, istiocsr); err != nil {
 			annUpdateErr = fmt.Errorf("failed to update reject processing annotation to %s/%s: %w", istiocsr.GetNamespace(), istiocsr.GetName(), err)
 		}
 	}
-	if condUpdateErr != nil || annUpdateErr != nil {
-		return utilerrors.NewAggregate([]error{condUpdateErr, annUpdateErr})
-	}
-
-	return NewMultipleInstanceError(fmt.Errorf("%s", statusMessage))
+	agg := utilerrors.NewAggregate([]error{fmt.Errorf("%s", statusMessage), condUpdateErr, annUpdateErr})
+	return NewMultipleInstanceError(agg)
 }
🧹 Nitpick comments (3)
pkg/controller/istiocsr/utils.go (3)

404-483: RBAC generic helpers: runtime assertions are redundant; if kept, improve panic context

Because the type parameter forces desired and fetched to the same concrete type, the extra any(desired).(*rbacv1.Role) assertions shouldn’t fail unless something is very off. If you keep these for linting, consider panicking with %T context (like the decode helpers) to avoid opaque crashes.


163-257: Improve panic diagnostics in decode*ObjBytes helpers

The panic messages lose the actual decoded type, making troubleshooting harder. While panic is acceptable here since these helpers load only static embedded manifests (via assets.MustAsset), improve diagnostics to aid debugging:

Proposed improvement
 func decodeDeploymentObjBytes(objBytes []byte) *appsv1.Deployment {
 	obj, err := runtime.Decode(codecs.UniversalDecoder(appsv1.SchemeGroupVersion), objBytes)
 	if err != nil {
-		panic(err)
+		panic(fmt.Errorf("failed to decode Deployment: %w", err))
 	}
 	deployment, ok := obj.(*appsv1.Deployment)
 	if !ok {
-		panic("failed to convert to *appsv1.Deployment")
+		panic(fmt.Sprintf("failed to convert decoded object (%T) to *appsv1.Deployment", obj))
 	}
 	return deployment
 }

Apply the same pattern to all other decode helpers.


259-326: hasObjectChanged: panics on unhandled types are safe given controlled call sites, but consider error return for future-proofing

All 12 call sites in the istiocsr package construct and pass explicitly typed objects (ClusterRole, Deployment, ConfigMap, Certificate, Service, NetworkPolicy, Role, and RoleBinding variants). While the function accepts the client.Object interface and panics in the default case, this is only reachable if a new object type is added to the callers without updating the switch statement—indicating a development-time error rather than a runtime crash risk.

That said, returning (bool, error) instead of panicking would improve robustness and allow callers to handle unsupported types gracefully, especially if this function is ever made public or used beyond the current controlled set of callers.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 9c0482b and 715e8db.

📒 Files selected for processing (2)
  • pkg/controller/istiocsr/deployments_test.go
  • pkg/controller/istiocsr/utils.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/controller/istiocsr/deployments_test.go
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

-Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity.

Files:

  • pkg/controller/istiocsr/utils.go
🧬 Code graph analysis (1)
pkg/controller/istiocsr/utils.go (2)
api/operator/v1alpha1/groupversion_info.go (1)
  • SchemeGroupVersion (29-29)
api/operator/v1alpha1/conditions.go (2)
  • Ready (27-27)
  • ReasonFailed (31-31)
🔇 Additional comments (1)
pkg/controller/istiocsr/utils.go (1)

49-70: Good: status update now returns contextual, wrapped errors

Wrapping the RetryOnConflict failure with failed to update status for ... (Line 66) makes reconcile failures easier to diagnose.

…nt controller

The informers variable was being built but never used (nil was passed instead),
causing a wastedassign lint error. However, removing the variable caused E2E
test failures because the controller needs to watch ConfigMaps, Secrets, and
Infrastructure resources to react to changes.

The fix passes the informers slice to NewDeploymentController so the controller
properly watches these resources, fixing both the lint error and E2E test failures.
@anandkuma77 anandkuma77 force-pushed the anandkuma77/cm-841-lint-fix branch from c523b90 to cf12dc3 Compare January 12, 2026 02:45
Copy link

@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

🤖 Fix all issues with AI agents
In @pkg/controller/istiocsr/deployments.go:
- Line 239: The NewIrrecoverableError call in
pkg/controller/istiocsr/deployments.go currently passes issuerKind twice (once
as a valid option and again as the "configured" value); update the call so the
final formatting argument is the actual configured issuer kind (the variable
holding the configured value, e.g., issuerRef.Kind or configuredIssuerKind)
instead of reusing issuerKind, so the message shows the real configured value.
🧹 Nitpick comments (4)
pkg/controller/deployment/deployment_overrides.go (1)

196-200: Consider wrapping the error for consistency.

The NotFound case at line 198 wraps the error with context (configmap name), but other errors are returned unwrapped. Lister errors may not always include the resource being accessed.

That said, for a lint-fix PR, the suppression is acceptable.

♻️ Optional: wrap for consistency with the NotFound case
 	} else if err != nil {
-		return err //nolint:wrapcheck // error from lister is already contextual
+		return fmt.Errorf("failed to get trusted CA config map %q: %w", trustedCAConfigmapName, err)
 	}
.golangci.yaml (2)

263-265: Consider using path-specific exclusions instead of global G101 disable.

Disabling G101 (hardcoded credentials) globally in gosec.excludes is broader than necessary. You already have path-specific exclusions at lines 133-140 for the actual false positives. The global exclusion makes those redundant and reduces security coverage across the entire codebase.

Suggested fix: Remove the global exclusion
   gosec:
-    excludes:
-      - G101  # False positives for hardcoded credentials (these are directory/volume paths)
+    # Path-specific exclusions for G101 false positives are defined in exclusions.rules

275-279: Global SA4006 disable may mask legitimate unused-value bugs.

Disabling SA4006 ("value is never used") globally affects the entire codebase. While the comment mentions "intentional in hooks," this could mask real bugs elsewhere. Consider using //nolint:staticcheck directives on specific hook functions instead, or adding a path-based exclusion if the hooks are in a specific directory.

Alternative: Use path-based exclusion or inline nolint

If the unused values are specific to controller reconciliation hooks, consider either:

  1. Path-based exclusion in exclusions.rules:
      - path: pkg/controller/.*_controller.go
        text: "SA4006"
        linters:
          - staticcheck
  1. Or keep SA4006 enabled globally and add //nolint:staticcheck // intentional unused assignment on specific lines.
pkg/controller/istiocsr/utils.go (1)

405-428: The type assertions inside the type switch cases are redundant but satisfy the linter.

Since we're inside case *rbacv1.ClusterRole:, we already know desired is *rbacv1.ClusterRole. The assertions will always succeed. This is a trade-off to satisfy forcetypeassert lint rules. Consider adding a brief comment noting this is for lint compliance if it helps future maintainers.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between c523b90 and cf12dc3.

📒 Files selected for processing (29)
  • .golangci.yaml
  • api/operator/v1alpha1/certmanager_types.go
  • api/operator/v1alpha1/istiocsr_types.go
  • main.go
  • pkg/controller/deployment/credentials_request.go
  • pkg/controller/deployment/default_cert_manager_controller.go
  • pkg/controller/deployment/deployment_overrides.go
  • pkg/controller/deployment/deployment_unsupported_overrides.go
  • pkg/controller/deployment/generic_deployment_controller.go
  • pkg/controller/istiocsr/certificates.go
  • pkg/controller/istiocsr/certificates_test.go
  • pkg/controller/istiocsr/client.go
  • pkg/controller/istiocsr/controller.go
  • pkg/controller/istiocsr/controller_test.go
  • pkg/controller/istiocsr/deployments.go
  • pkg/controller/istiocsr/deployments_test.go
  • pkg/controller/istiocsr/install_instiocsr_test.go
  • pkg/controller/istiocsr/networkpolicies.go
  • pkg/controller/istiocsr/rbacs.go
  • pkg/controller/istiocsr/rbacs_test.go
  • pkg/controller/istiocsr/serviceaccounts_test.go
  • pkg/controller/istiocsr/services_test.go
  • pkg/controller/istiocsr/test_utils.go
  • pkg/controller/istiocsr/utils.go
  • pkg/features/features.go
  • pkg/operator/operatorclient/operatorclient.go
  • pkg/operator/optionalinformer/optional_informer.go
  • pkg/operator/setup_manager.go
  • pkg/operator/starter.go
🚧 Files skipped from review as they are similar to previous changes (11)
  • pkg/controller/istiocsr/install_instiocsr_test.go
  • pkg/controller/istiocsr/serviceaccounts_test.go
  • pkg/controller/istiocsr/controller.go
  • pkg/controller/deployment/generic_deployment_controller.go
  • pkg/controller/deployment/deployment_unsupported_overrides.go
  • pkg/controller/istiocsr/deployments_test.go
  • pkg/controller/istiocsr/test_utils.go
  • pkg/operator/setup_manager.go
  • pkg/controller/deployment/credentials_request.go
  • pkg/controller/istiocsr/certificates.go
  • pkg/controller/istiocsr/controller_test.go
🧰 Additional context used
📓 Path-based instructions (1)
**

⚙️ CodeRabbit configuration file

-Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity.

Files:

  • pkg/operator/optionalinformer/optional_informer.go
  • pkg/controller/istiocsr/certificates_test.go
  • pkg/controller/istiocsr/networkpolicies.go
  • api/operator/v1alpha1/istiocsr_types.go
  • main.go
  • pkg/controller/deployment/default_cert_manager_controller.go
  • pkg/controller/istiocsr/rbacs.go
  • pkg/controller/deployment/deployment_overrides.go
  • pkg/operator/starter.go
  • pkg/controller/istiocsr/client.go
  • pkg/controller/istiocsr/deployments.go
  • pkg/controller/istiocsr/utils.go
  • api/operator/v1alpha1/certmanager_types.go
  • pkg/features/features.go
  • pkg/controller/istiocsr/services_test.go
  • pkg/controller/istiocsr/rbacs_test.go
  • pkg/operator/operatorclient/operatorclient.go
🧬 Code graph analysis (3)
pkg/controller/istiocsr/networkpolicies.go (2)
api/operator/v1alpha1/certmanager_types.go (1)
  • NetworkPolicy (247-272)
pkg/operator/applyconfigurations/operator/v1alpha1/networkpolicy.go (1)
  • NetworkPolicy (20-22)
pkg/controller/istiocsr/rbacs.go (2)
pkg/controller/istiocsr/controller.go (1)
  • Reconciler (48-55)
api/operator/v1alpha1/istiocsr_types.go (1)
  • IstioCSR (48-64)
pkg/controller/istiocsr/utils.go (4)
api/operator/v1alpha1/groupversion_info.go (1)
  • SchemeGroupVersion (29-29)
api/operator/v1alpha1/certmanager_types.go (1)
  • NetworkPolicy (247-272)
pkg/operator/applyconfigurations/operator/v1alpha1/networkpolicy.go (1)
  • NetworkPolicy (20-22)
api/operator/v1alpha1/conditions.go (2)
  • Ready (27-27)
  • ReasonFailed (31-31)
🔇 Additional comments (36)
pkg/controller/istiocsr/networkpolicies.go (1)

47-50: LGTM!

The safe type assertion correctly addresses the forcetypeassert lint error. The error message helpfully includes the actual type received (got %T), which aids debugging if an incorrect asset is ever loaded.

main.go (1)

29-32: LGTM!

Explicitly discarding the error from cmd.Help() with _ = is appropriate here—the program exits with code 1 immediately regardless, so there's no meaningful error handling to perform. This satisfies the linter while clearly documenting the intent.

api/operator/v1alpha1/certmanager_types.go (1)

188-191: LGTM!

The nolint:godot directive is appropriately placed to suppress the linter for the operator-sdk annotation, which is a directive comment and doesn't require a trailing period.

api/operator/v1alpha1/istiocsr_types.go (1)

45-48: LGTM!

Consistent with the same pattern applied in certmanager_types.go. The nolint:godot directive appropriately suppresses the linter for the operator-sdk annotation.

pkg/controller/deployment/deployment_overrides.go (1)

35-35: LGTM!

The nolint:gosec annotation is appropriate. G101 flags this path constant because it contains "secrets", but this is a standard OpenShift service account token mount path, not a hardcoded credential.

pkg/features/features.go (1)

26-26: LGTM!

The nolint:wrapcheck directive is appropriately justified with an inline comment explaining that the featuregate error is already contextual. This is good practice for documenting lint suppressions.

.golangci.yaml (2)

60-61: LGTM!

The depguard disable is well-documented with a link to the relevant issue. This is a reasonable workaround for the golangci-lint v2 configuration issue.


110-112: LGTM!

The path-based and text-based exclusions are reasonable:

  • Test files appropriately exclude linters that would generate noise (forcetypeassert, goconst, gocritic)
  • Kubebuilder/operator-sdk annotation exclusions from godot are correct
  • Path-specific gosec exclusions for credential-related false positives are well-targeted
  • Controller wrapcheck exclusions align with controller-runtime builder patterns

Also applies to: 120-153

pkg/operator/starter.go (2)

46-84: LGTM - wrapcheck suppressions are well-justified.

The //nolint:wrapcheck annotations on the NewForConfig error returns are reasonable. Kubernetes client-go errors include sufficient context, and the inline explanations document the rationale.


144-152: Suppression is appropriate; minor context lifecycle note.

The //nolint:contextcheck is valid—SetupSignalHandler() is the standard controller-runtime pattern for OS signal handling. The justification clearly documents the intent.

Note: The controller-runtime manager now has an independent lifecycle (OS signals) compared to other controllers using ctx. This appears intentional per the comment, but be aware that cancelling the passed ctx won't stop this manager.

pkg/controller/deployment/default_cert_manager_controller.go (1)

58-58: LGTM!

The nolint:wrapcheck annotation is appropriate here. Kubernetes client errors from Create already include sufficient context about the operation and resource, making additional wrapping redundant.

pkg/operator/optionalinformer/optional_informer.go (1)

57-57: LGTM!

The nolint:wrapcheck annotation is appropriate. Discovery client errors already include context about the group/version being queried.

pkg/operator/operatorclient/operatorclient.go (5)

7-8: LGTM!

The slices package import is properly utilized for slices.Contains in the EnsureFinalizer method.


172-178: Good refactor: avoiding builtin shadowing.

Renaming copy to updated is a good practice since copy is a Go builtin. This improves code clarity and prevents potential confusion. The nolint annotations are consistent with the rest of the file.


189-195: LGTM!

Consistent variable rename and nolint annotation pattern as UpdateOperatorSpec.


204-214: LGTM!

Using slices.Contains (line 208) is cleaner than manual iteration. The nolint annotations and finalizer handling are appropriate.


225-253: LGTM!

The remaining nolint annotations follow the same consistent pattern with appropriate justifications for suppressing wrapcheck on client/lister errors.

pkg/controller/istiocsr/utils.go (5)

66-66: LGTM!

Good improvement to wrap the underlying error with additional context about which resource failed the status update.


168-172: LGTM!

The explicit type assertion with ok-check addresses the forcetypeassert lint error. Panicking on failure is appropriate here since the decoder is configured with the correct scheme and a type mismatch would indicate a programming error.


180-184: LGTM!

Consistent pattern applied across all decode*ObjBytes helpers - checked type assertions with descriptive panic messages on failure.

Also applies to: 192-196, 204-208, 216-220, 228-232, 240-244, 252-256


265-321: LGTM!

The type assertions in hasObjectChanged are now explicit with ok-checks. While the preceding reflect.TypeOf(desired) != reflect.TypeOf(fetched) check (line 260) should prevent mismatches, the explicit checks satisfy the linter and provide clear panic messages if assumptions are violated.


557-576: Verify the inverted control flow logic.

The logic change looks correct:

  • If !ignoreProcessing (this is the oldest instance), return nil to allow processing
  • Otherwise, reject the instance by updating status/annotations and returning the error

This matches the AI summary description. The early return simplifies the happy path.

pkg/controller/istiocsr/certificates_test.go (1)

37-37: LGTM!

Consistent renaming of the test error sentinel from testError to errTestClient across all mock error returns. This aligns with Go naming conventions for error variables (err prefix).

Also applies to: 67-67, 116-116

pkg/controller/istiocsr/services_test.go (1)

48-48: LGTM!

Consistent error sentinel renaming (testErrorerrTestClient) matching the pattern across other IstioCSR test files.

Also applies to: 61-61, 84-84

pkg/controller/istiocsr/rbacs_test.go (2)

31-31: LGTM!

Comprehensive update of error sentinels from testError to errTestClient across all RBAC test cases.

Also applies to: 47-47, 63-63, 76-76, 90-90, 105-105, 119-119, 176-176, 217-217, 250-250, 287-287, 313-313, 336-336, 358-358, 378-378, 403-403, 427-427, 450-450, 470-470, 495-495, 519-519


258-258: LGTM!

The updated wantErr strings correctly reflect the new error wrapping format from utils.go line 66, which now includes "failed to update status for" in the error chain.

Also applies to: 296-296

pkg/controller/istiocsr/deployments.go (3)

32-32: LGTM!

Renamed error variable from invalidIssuerRefConfigError to errInvalidIssuerRefConfig following Go naming conventions for error variables.


255-265: LGTM!

Added explicit type assertion checks in assertIssuerRefExists. Returning NewIrrecoverableError on failure is appropriate since this is a validation path where failed assertions indicate configuration issues rather than programming errors.


375-385: LGTM!

Type assertion checks added in handleIssuerBasedCA. Using FromClientError here is appropriate since this is an operational path where the issuer was already fetched but type conversion failed unexpectedly.

pkg/controller/istiocsr/rbacs.go (2)

135-146: LGTM!

Good rename from new to desired — avoids shadowing the built-in new function and better conveys intent.


225-236: LGTM!

Consistent with the updateClusterRoleNameInStatus refactor above.

pkg/controller/istiocsr/client.go (5)

43-59: LGTM!

Consistent error wrapping with object context improves debuggability. Error chaining via %w preserves the original error for errors.Is/errors.As checks.


61-89: LGTM!

Consistent pattern across Create, Delete, and Update — extracting object key before the operation provides useful context in error messages.


96-100: Safe type assertion addresses forcetypeassert lint.

The reflection-based pattern correctly handles dynamic type creation and includes explicit error handling for the type assertion. One edge case: if obj is nil, reflect.TypeOf(obj) returns nil and .Elem() will panic. In practice this would be a caller bug, but consider whether a nil-guard is warranted here.


116-134: LGTM!

StatusUpdate and Patch follow the same consistent error-wrapping pattern.


136-144: LGTM!

Exists correctly preserves the NotFound → (false, nil) behavior while adding context to other errors.

Copy link
Contributor

@mytreya-rh mytreya-rh left a comment

Choose a reason for hiding this comment

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

Thanks for the changes @anandkuma77
Dropped few comments especially on linter settings and too many inline ignores which i feel could have been re-used from centrally codified golangci.yaml
cc: @bharath-b-rh

// CertManager is the Schema for the certmanagers API
// +operator-sdk:csv:customresourcedefinitions:displayName="CertManager"
//
//nolint:godot // operator-sdk annotation doesn't need period
Copy link
Contributor

Choose a reason for hiding this comment

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

Do we really need to inline ignore here (and few other places), given that godot linter for kubebuilder and operator-sdk annotations are excluded in .golangci.yaml

Copy link
Author

Choose a reason for hiding this comment

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

This file is not excluded.


// credentials for GCP.
gcpCredentialsDir = "/.config/gcloud"
gcpCredentialsDir = "/.config/gcloud" //nolint:gosec // G101: path constant, not a credential
Copy link
Contributor

Choose a reason for hiding this comment

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

Two points (for this and other G101 inline exclusions):

  1. In .golangci.yaml we have globally excluded G101 check from gosec. Thus, we perhaps don't need the explicit inline exclusion right?
  2. Can we instead not exclude the G101 check but change the variable name for example to gcpConfigDir so that the variable doesn't get flagged?

.golangci.yaml Outdated
chain-split-dots: false
chain-split-dots: false

linters-settings:
Copy link
Contributor

@mytreya-rh mytreya-rh Jan 16, 2026

Choose a reason for hiding this comment

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

This (linters-settings) seems to be specific to legacy v1 style: https://golangci.github.io/legacy-v1-doc/usage/linters/#linters-configuration and will not work for v2: https://golangci-lint.run/docs/linters/configuration/ (where linters.settings i.e. settings struct under linters struct is expected)
Please see the difference (between v1 and v2 linter settings examples), as the current linters-settings i think is not being used at all.
Found this while checking why we have inline wrap ignores despite wrapcheck setting here.

Copy link
Author

Choose a reason for hiding this comment

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

Thanks, it solved a lot

return fmt.Errorf("(Retrying) cloud secret %q doesn't exist due to %w", secretName, err)
} else if err != nil {
return err
return err //nolint:wrapcheck // error from lister is already contextual
Copy link
Contributor

Choose a reason for hiding this comment

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

please see comment golangci lint v1 vs v2 for linter-settings.. perhaps we will not need this explicit inline ignore after we fix the structure there, and if needed add some additional patterns to cover for common cases where wrapping is not needed. Same comment for all other similar inline ignores of wrapcheck

Copy link
Author

Choose a reason for hiding this comment

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

Thanks, updating setting to V2 solved this.

…int comments

- Migrate .golangci.yaml from v1 to v2 format
- Remove all //nolint:wrapcheck comment
- Fix G101 lint errors by renaming credential-related variables:
- Update godot linter configuration
@anandkuma77 anandkuma77 force-pushed the anandkuma77/cm-841-lint-fix branch from cf12dc3 to 3bbe34a Compare January 19, 2026 06:47
- Remove nolint comments from istiocsr controller and client
- Update variable names in credentials_request.go
- Clean up deployment_overrides.go
- Remove unused comments from istiocsr_types.go
@openshift-ci
Copy link
Contributor

openshift-ci bot commented Jan 19, 2026

@anandkuma77: all tests passed!

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

Copy link
Contributor

@bharath-b-rh bharath-b-rh left a comment

Choose a reason for hiding this comment

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

/lgtm

}
}
deployment = unsupportedConfigOverrides(deployment, cfg)
deployment = unsupportedConfigOverrides(deployment, cfg) //nolint:staticcheck,wastedassign // SA4006: deployment is modified in place, assignment kept for clarity
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: since deployment is modified in-place and the same is not used for any other purpose after this call, do we need to reassign?

Suggested change
deployment = unsupportedConfigOverrides(deployment, cfg) //nolint:staticcheck,wastedassign // SA4006: deployment is modified in place, assignment kept for clarity
unsupportedConfigOverrides(deployment, cfg)

- path: pkg/operators
linters:
- all
# Exclude hack directory from some linters
Copy link
Contributor

Choose a reason for hiding this comment

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

I think these can be simplified, but requires the golinter to be updated I guess. Lets check in the next iteration of linter. Especially operator-sdk and kubebuilder doesn't need to be excluded explicitly.

@openshift-ci openshift-ci bot added the lgtm Indicates that a PR is ready to be merged. label Jan 23, 2026
@openshift-ci
Copy link
Contributor

openshift-ci bot commented Jan 23, 2026

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: anandkuma77, bharath-b-rh

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-ci openshift-ci bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Jan 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. lgtm Indicates that a PR is ready to be merged.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants