Repository: envoyproxy/ai-gateway
Pull request #298 (2025-02-06 03:47:37)

chore: stricter golangci-lint
**Commit Message**

This makes the lint settings stricter and
starts enforcing more rules.


Patch:
diff --git a/.golangci.yml b/.golangci.yml
index 2711c77..4b4ac85 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -71,13 +71,7 @@ linters-settings:
   govet:
     enable-all: true
     disable:
-      - shadow
       - fieldalignment
-  revive:
-    rules:
-      # TODO: enable if-return check
-      - name: if-return
-        disabled: true
   testifylint:
     disable:
       - float-compare
diff --git a/internal/apischema/awsbedrock/awsbedrock.go b/internal/apischema/awsbedrock/awsbedrock.go
index 104bda9..6f28c3b 100644
--- a/internal/apischema/awsbedrock/awsbedrock.go
+++ b/internal/apischema/awsbedrock/awsbedrock.go
@@ -337,7 +337,9 @@ type ConverseMetrics struct {
 	LatencyMs *int64 `json:"latencyMs"`
 }
 
-type ConverseOutput struct {
+// ConverseResponse is the response from a call to Converse.
+// https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html
+type ConverseResponse struct {
 	// Metrics for the call to Converse.
 	//
 	// Metrics is a required field
@@ -346,7 +348,7 @@ type ConverseOutput struct {
 	// The result from the call to Converse.
 	//
 	// Output is a required field
-	Output *ConverseOutput_ `json:"output"`
+	Output *ConverseOutput `json:"output"`
 
 	// The reason why the model stopped generating output.
 	//
@@ -362,9 +364,9 @@ type ConverseOutput struct {
 	Usage *TokenUsage `json:"usage"`
 }
 
-// ConverseOutput_ ConverseResponseOutput is defined in the AWS Bedrock API:
+// ConverseOutput is defined in the AWS Bedrock API:
 // https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseOutput.html
-type ConverseOutput_ struct {
+type ConverseOutput struct {
 	Message Message `json:"message,omitempty"`
 }
 
diff --git a/internal/controller/ai_gateway_route.go b/internal/controller/ai_gateway_route.go
index b76cdbc..58c8249 100644
--- a/internal/controller/ai_gateway_route.go
+++ b/internal/controller/ai_gateway_route.go
@@ -153,7 +153,7 @@ func (c *aiGatewayRouteController) ensuresExtProcConfigMapExists(ctx context.Con
 			},
 			Data: map[string]string{expProcConfigFileName: filterapi.DefaultConfig},
 		}
-		if err := ctrlutil.SetControllerReference(aiGatewayRoute, configMap, c.client.Scheme()); err != nil {
+		if err = ctrlutil.SetControllerReference(aiGatewayRoute, configMap, c.client.Scheme()); err != nil {
 			panic(fmt.Errorf("BUG: failed to set controller reference for extproc configmap: %w", err))
 		}
 		_, err = c.kube.CoreV1().ConfigMaps(aiGatewayRoute.Namespace).Create(ctx, configMap, metav1.CreateOptions{})
diff --git a/internal/controller/sink.go b/internal/controller/sink.go
index 470b518..136a0c6 100644
--- a/internal/controller/sink.go
+++ b/internal/controller/sink.go
@@ -149,7 +149,7 @@ func (c *configSink) syncAIGatewayRoute(ctx context.Context, aiGatewayRoute *aig
 				},
 			},
 		}
-		if err := c.client.Create(ctx, &httpRouteFilter); err != nil {
+		if err = c.client.Create(ctx, &httpRouteFilter); err != nil {
 			c.logger.Error(err, "failed to create HTTPRouteFilter", "namespace", aiGatewayRoute.Namespace, "name", hostRewriteHTTPFilterName)
 			return
 		}
@@ -181,20 +181,20 @@ func (c *configSink) syncAIGatewayRoute(ctx context.Context, aiGatewayRoute *aig
 	}
 
 	// Update the HTTPRoute with the new AIGatewayRoute.
-	if err := c.newHTTPRoute(ctx, &httpRoute, aiGatewayRoute); err != nil {
+	if err = c.newHTTPRoute(ctx, &httpRoute, aiGatewayRoute); err != nil {
 		c.logger.Error(err, "failed to update HTTPRoute with AIGatewayRoute", "namespace", aiGatewayRoute.Namespace, "name", aiGatewayRoute.Name)
 		return
 	}
 
 	if existingRoute {
 		c.logger.Info("updating HTTPRoute", "namespace", httpRoute.Namespace, "name", httpRoute.Name)
-		if err := c.client.Update(ctx, &httpRoute); err != nil {
+		if err = c.client.Update(ctx, &httpRoute); err != nil {
 			c.logger.Error(err, "failed to update HTTPRoute", "namespace", httpRoute.Namespace, "name", httpRoute.Name)
 			return
 		}
 	} else {
 		c.logger.Info("creating HTTPRoute", "namespace", httpRoute.Namespace, "name", httpRoute.Name)
-		if err := c.client.Create(ctx, &httpRoute); err != nil {
+		if err = c.client.Create(ctx, &httpRoute); err != nil {
 			c.logger.Error(err, "failed to create HTTPRoute", "namespace", httpRoute.Namespace, "name", httpRoute.Name)
 			return
 		}
@@ -202,7 +202,7 @@ func (c *configSink) syncAIGatewayRoute(ctx context.Context, aiGatewayRoute *aig
 
 	// Update the extproc configmap.
 	uuid := string(uuid2.NewUUID())
-	if err := c.updateExtProcConfigMap(ctx, aiGatewayRoute, uuid); err != nil {
+	if err = c.updateExtProcConfigMap(ctx, aiGatewayRoute, uuid); err != nil {
 		c.logger.Error(err, "failed to update extproc configmap", "namespace", aiGatewayRoute.Namespace, "name", aiGatewayRoute.Name)
 		return
 	}
@@ -277,19 +277,20 @@ func (c *configSink) updateExtProcConfigMap(ctx context.Context, aiGatewayRoute
 			key := fmt.Sprintf("%s.%s", backend.Name, aiGatewayRoute.Namespace)
 			ec.Rules[i].Backends[j].Name = key
 			ec.Rules[i].Backends[j].Weight = backend.Weight
-			backendObj, err := c.backend(ctx, aiGatewayRoute.Namespace, backend.Name)
+			var backendObj *aigv1a1.AIServiceBackend
+			backendObj, err = c.backend(ctx, aiGatewayRoute.Namespace, backend.Name)
 			if err != nil {
 				return fmt.Errorf("failed to get AIServiceBackend %s: %w", key, err)
-			} else {
-				ec.Rules[i].Backends[j].Schema.Name = filterapi.APISchemaName(backendObj.Spec.APISchema.Name)
-				ec.Rules[i].Backends[j].Schema.Version = backendObj.Spec.APISchema.Version
 			}
+			ec.Rules[i].Backends[j].Schema.Name = filterapi.APISchemaName(backendObj.Spec.APISchema.Name)
+			ec.Rules[i].Backends[j].Schema.Version = backendObj.Spec.APISchema.Version
 
 			if bspRef := backendObj.Spec.BackendSecurityPolicyRef; bspRef != nil {
 				volumeName := backendSecurityPolicyVolumeName(
 					i, j, string(backendObj.Spec.BackendSecurityPolicyRef.Name),
 				)
-				backendSecurityPolicy, err := c.backendSecurityPolicy(ctx, aiGatewayRoute.Namespace, string(bspRef.Name))
+				var backendSecurityPolicy *aigv1a1.BackendSecurityPolicy
+				backendSecurityPolicy, err = c.backendSecurityPolicy(ctx, aiGatewayRoute.Namespace, string(bspRef.Name))
 				if err != nil {
 					return fmt.Errorf("failed to get BackendSecurityPolicy %s: %w", bspRef.Name, err)
 				}
@@ -338,7 +339,7 @@ func (c *configSink) updateExtProcConfigMap(ctx context.Context, aiGatewayRoute
 			fc.Type = filterapi.LLMRequestCostTypeCELExpression
 			expr := *cost.CELExpression
 			// Sanity check the CEL expression.
-			_, err := llmcostcel.NewProgram(expr)
+			_, err = llmcostcel.NewProgram(expr)
 			if err != nil {
 				return fmt.Errorf("invalid CEL expression: %w", err)
 			}
@@ -513,10 +514,11 @@ func (c *configSink) syncExtProcDeployment(ctx context.Context, aiGatewayRoute *
 					},
 				},
 			}
-			if err := ctrlutil.SetControllerReference(aiGatewayRoute, deployment, c.client.Scheme()); err != nil {
+			if err = ctrlutil.SetControllerReference(aiGatewayRoute, deployment, c.client.Scheme()); err != nil {
 				panic(fmt.Errorf("BUG: failed to set controller reference for deployment: %w", err))
 			}
-			updatedSpec, err := c.mountBackendSecurityPolicySecrets(ctx, &deployment.Spec.Template.Spec, aiGatewayRoute)
+			var updatedSpec *corev1.PodSpec
+			updatedSpec, err = c.mountBackendSecurityPolicySecrets(ctx, &deployment.Spec.Template.Spec, aiGatewayRoute)
 			if err == nil {
 				deployment.Spec.Template.Spec = *updatedSpec
 			}
@@ -530,7 +532,8 @@ func (c *configSink) syncExtProcDeployment(ctx context.Context, aiGatewayRoute *
 			return fmt.Errorf("failed to get deployment: %w", err)
 		}
 	} else {
-		updatedSpec, err := c.mountBackendSecurityPolicySecrets(ctx, &deployment.Spec.Template.Spec, aiGatewayRoute)
+		var updatedSpec *corev1.PodSpec
+		updatedSpec, err = c.mountBackendSecurityPolicySecrets(ctx, &deployment.Spec.Template.Spec, aiGatewayRoute)
 		if err == nil {
 			deployment.Spec.Template.Spec = *updatedSpec
 		}
diff --git a/internal/extproc/router/request_body.go b/internal/extproc/router/request_body.go
index 724e039..bc298f2 100644
--- a/internal/extproc/router/request_body.go
+++ b/internal/extproc/router/request_body.go
@@ -32,7 +32,6 @@ func openAIParseBody(path string, body *extprocv3.HttpBody) (modelName string, r
 			return "", nil, fmt.Errorf("failed to unmarshal body: %w", err)
 		}
 		return openAIReq.Model, &openAIReq, nil
-	} else {
-		return "", nil, fmt.Errorf("unsupported path: %s", path)
 	}
+	return "", nil, fmt.Errorf("unsupported path: %s", path)
 }
diff --git a/internal/extproc/server.go b/internal/extproc/server.go
index c791d81..68627d7 100644
--- a/internal/extproc/server.go
+++ b/internal/extproc/server.go
@@ -66,11 +66,10 @@ func (s *Server[P]) LoadConfig(ctx context.Context, config *filterapi.Config) er
 			}
 
 			if b.Auth != nil {
-				h, err := backendauth.NewHandler(ctx, b.Auth)
+				backendAuthHandlers[b.Name], err = backendauth.NewHandler(ctx, b.Auth)
 				if err != nil {
 					return fmt.Errorf("cannot create backend auth handler: %w", err)
 				}
-				backendAuthHandlers[b.Name] = h
 			}
 		}
 	}
diff --git a/internal/extproc/translator/openai_awsbedrock.go b/internal/extproc/translator/openai_awsbedrock.go
index 55c9398..3297cc5 100644
--- a/internal/extproc/translator/openai_awsbedrock.go
+++ b/internal/extproc/translator/openai_awsbedrock.go
@@ -25,9 +25,8 @@ import (
 func newOpenAIToAWSBedrockTranslator(path string) (Translator, error) {
 	if path == "/v1/chat/completions" {
 		return &openAIToAWSBedrockTranslatorV1ChatCompletion{}, nil
-	} else {
-		return nil, fmt.Errorf("unsupported path: %s", path)
 	}
+	return nil, fmt.Errorf("unsupported path: %s", path)
 }
 
 // openAIToAWSBedrockTranslator implements [Translator] for /v1/chat/completions.
@@ -92,10 +91,8 @@ func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) RequestBody(body router.R
 	}
 
 	mut := &extprocv3.BodyMutation_Body{}
-	if b, err := json.Marshal(bedrockReq); err != nil {
+	if mut.Body, err = json.Marshal(bedrockReq); err != nil {
 		return nil, nil, nil, fmt.Errorf("failed to marshal body: %w", err)
-	} else {
-		mut.Body = b
 	}
 	setContentLength(headerMutation, mut.Body)
 	return headerMutation, &extprocv3.BodyMutation{Mutation: mut}, override, nil
@@ -238,9 +235,8 @@ func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) openAIMessageToBedrockMes
 			}
 		}
 		return chatMessage, nil
-	} else {
-		return nil, fmt.Errorf("unexpected content type")
 	}
+	return nil, fmt.Errorf("unexpected content type")
 }
 
 // unmarshalToolCallArguments is a helper method to unmarshal tool call arguments.
@@ -468,7 +464,7 @@ func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) ResponseError(respHeaders
 	var openaiError openai.Error
 	if v, ok := respHeaders[contentTypeHeaderName]; ok && v == jsonContentType {
 		var bedrockError awsbedrock.BedrockException
-		if err := json.NewDecoder(body).Decode(&bedrockError); err != nil {
+		if err = json.NewDecoder(body).Decode(&bedrockError); err != nil {
 			return nil, nil, fmt.Errorf("failed to unmarshal error body: %w", err)
 		}
 		openaiError = openai.Error{
@@ -480,7 +476,8 @@ func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) ResponseError(respHeaders
 			},
 		}
 	} else {
-		buf, err := io.ReadAll(body)
+		var buf []byte
+		buf, err = io.ReadAll(body)
 		if err != nil {
 			return nil, nil, fmt.Errorf("failed to read error body: %w", err)
 		}
@@ -494,10 +491,9 @@ func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) ResponseError(respHeaders
 		}
 	}
 	mut := &extprocv3.BodyMutation_Body{}
-	if errBody, err := json.Marshal(openaiError); err != nil {
+	mut.Body, err = json.Marshal(openaiError)
+	if err != nil {
 		return nil, nil, fmt.Errorf("failed to marshal error body: %w", err)
-	} else {
-		mut.Body = errBody
 	}
 	headerMutation = &extprocv3.HeaderMutation{}
 	setContentLength(headerMutation, mut.Body)
@@ -508,9 +504,10 @@ func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) ResponseError(respHeaders
 func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) ResponseBody(respHeaders map[string]string, body io.Reader, endOfStream bool) (
 	headerMutation *extprocv3.HeaderMutation, bodyMutation *extprocv3.BodyMutation, tokenUsage LLMTokenUsage, err error,
 ) {
-	if v, ok := respHeaders[statusHeaderName]; ok {
-		if v, err := strconv.Atoi(v); err == nil {
-			if !isGoodStatusCode(v) {
+	if statusStr, ok := respHeaders[statusHeaderName]; ok {
+		var status int
+		if status, err = strconv.Atoi(statusStr); err == nil {
+			if !isGoodStatusCode(status) {
 				headerMutation, bodyMutation, err = o.ResponseError(respHeaders, body)
 				return headerMutation, bodyMutation, LLMTokenUsage{}, err
 			}
@@ -518,7 +515,8 @@ func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) ResponseBody(respHeaders
 	}
 	mut := &extprocv3.BodyMutation_Body{}
 	if o.stream {
-		buf, err := io.ReadAll(body)
+		var buf []byte
+		buf, err = io.ReadAll(body)
 		if err != nil {
 			return nil, nil, tokenUsage, fmt.Errorf("failed to read body: %w", err)
 		}
@@ -538,7 +536,8 @@ func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) ResponseBody(respHeaders
 			if !ok {
 				continue
 			}
-			oaiEventBytes, err := json.Marshal(oaiEvent)
+			var oaiEventBytes []byte
+			oaiEventBytes, err = json.Marshal(oaiEvent)
 			if err != nil {
 				panic(fmt.Errorf("failed to marshal event: %w", err))
 			}
@@ -553,8 +552,8 @@ func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) ResponseBody(respHeaders
 		return headerMutation, &extprocv3.BodyMutation{Mutation: mut}, tokenUsage, nil
 	}
 
-	var bedrockResp awsbedrock.ConverseOutput
-	if err := json.NewDecoder(body).Decode(&bedrockResp); err != nil {
+	var bedrockResp awsbedrock.ConverseResponse
+	if err = json.NewDecoder(body).Decode(&bedrockResp); err != nil {
 		return nil, nil, tokenUsage, fmt.Errorf("failed to unmarshal body: %w", err)
 	}
 
@@ -590,10 +589,9 @@ func (o *openAIToAWSBedrockTranslatorV1ChatCompletion) ResponseBody(respHeaders
 		openAIResp.Choices = append(openAIResp.Choices, choice)
 	}
 
-	if b, err := json.Marshal(openAIResp); err != nil {
+	mut.Body, err = json.Marshal(openAIResp)
+	if err != nil {
 		return nil, nil, tokenUsage, fmt.Errorf("failed to marshal body: %w", err)
-	} else {
-		mut.Body = b
 	}
 	headerMutation = &extprocv3.HeaderMutation{}
 	setContentLength(headerMutation, mut.Body)
diff --git a/internal/extproc/translator/openai_openai.go b/internal/extproc/translator/openai_openai.go
index 14b29a4..e14779f 100644
--- a/internal/extproc/translator/openai_openai.go
+++ b/internal/extproc/translator/openai_openai.go
@@ -18,9 +18,8 @@ import (
 func newOpenAIToOpenAITranslator(path string) (Translator, error) {
 	if path == "/v1/chat/completions" {
 		return &openAIToOpenAITranslatorV1ChatCompletion{}, nil
-	} else {
-		return nil, fmt.Errorf("unsupported path: %s", path)
 	}
+	return nil, fmt.Errorf("unsupported path: %s", path)
 }
 
 // openAIToOpenAITranslatorV1ChatCompletion implements [Translator] for /v1/chat/completions.
@@ -70,10 +69,9 @@ func (o *openAIToOpenAITranslatorV1ChatCompletion) ResponseError(respHeaders map
 			},
 		}
 		mut := &extprocv3.BodyMutation_Body{}
-		if errBody, err := json.Marshal(openaiError); err != nil {
+		mut.Body, err = json.Marshal(openaiError)
+		if err != nil {
 			return nil, nil, fmt.Errorf("failed to marshal error body: %w", err)
-		} else {
-			mut.Body = errBody
 		}
 		headerMutation = &extprocv3.HeaderMutation{}
 		setContentLength(headerMutation, mut.Body)
diff --git a/internal/extproc/watcher.go b/internal/extproc/watcher.go
index 871f884..20bf23c 100644
--- a/internal/extproc/watcher.go
+++ b/internal/extproc/watcher.go
@@ -74,12 +74,12 @@ func (cw *configWatcher) loadConfig(ctx context.Context) error {
 	if cw.l.Enabled(ctx, slog.LevelDebug) {
 		// Re-hydrate the current config file for later diffing.
 		previous := cw.current
-		current, err := cw.getConfigString()
+		cw.current, err = cw.getConfigString()
 		if err != nil {
 			return fmt.Errorf("failed to read the config file: %w", err)
 		}
 
-		cw.diff(previous, current)
+		cw.diff(previous, cw.current)
 	}
 
 	cfg, err := filterapi.UnmarshalConfigYaml(cw.path)
@@ -96,10 +96,7 @@ func (cw *configWatcher) getConfigString() (string, error) {
 	if err != nil {
 		return "", err
 	}
-	current := string(currentByte)
-	cw.current = current
-
-	return current, nil
+	return string(currentByte), nil
 }
 
 func (cw *configWatcher) diff(oldConfig, newConfig string) {
diff --git a/internal/llmcostcel/cel.go b/internal/llmcostcel/cel.go
index bd67d3f..6055cdf 100644
--- a/internal/llmcostcel/cel.go
+++ b/internal/llmcostcel/cel.go
@@ -38,7 +38,7 @@ func init() {
 func NewProgram(expr string) (prog cel.Program, err error) {
 	ast, issues := env.Compile(expr)
 	if issues != nil && issues.Err() != nil {
-		err := issues.Err()
+		err = issues.Err()
 		return nil, fmt.Errorf("cannot compile CEL expression: %w", err)
 	}
 	prog, err = env.Program(ast)


Test patch:
diff --git a/internal/controller/ai_gateway_route_test.go b/internal/controller/ai_gateway_route_test.go
index ca72353..5fe2f2c 100644
--- a/internal/controller/ai_gateway_route_test.go
+++ b/internal/controller/ai_gateway_route_test.go
@@ -157,7 +157,7 @@ func Test_applyExtProcDeploymentConfigUpdate(t *testing.T) {
 			},
 		},
 	}
-	t.Run("not panic", func(t *testing.T) {
+	t.Run("not panic", func(_ *testing.T) {
 		applyExtProcDeploymentConfigUpdate(dep, nil)
 		applyExtProcDeploymentConfigUpdate(dep, &aigv1a1.AIGatewayFilterConfig{})
 		applyExtProcDeploymentConfigUpdate(dep, &aigv1a1.AIGatewayFilterConfig{
diff --git a/internal/controller/ai_service_backend_test.go b/internal/controller/ai_service_backend_test.go
index 1806e68..575abb3 100644
--- a/internal/controller/ai_service_backend_test.go
+++ b/internal/controller/ai_service_backend_test.go
@@ -6,7 +6,6 @@ import (
 
 	"github.com/stretchr/testify/require"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-	"k8s.io/apimachinery/pkg/runtime"
 	"k8s.io/apimachinery/pkg/types"
 	fake2 "k8s.io/client-go/kubernetes/fake"
 	"k8s.io/utils/ptr"
@@ -42,9 +41,6 @@ func TestAIServiceBackendController_Reconcile(t *testing.T) {
 }
 
 func Test_AiServiceBackendIndexFunc(t *testing.T) {
-	scheme := runtime.NewScheme()
-	require.NoError(t, aigv1a1.AddToScheme(scheme))
-
 	c := fake.NewClientBuilder().
 		WithScheme(scheme).
 		WithIndex(&aigv1a1.AIServiceBackend{}, k8sClientIndexBackendSecurityPolicyToReferencingAIServiceBackend, aiServiceBackendIndexFunc).
diff --git a/internal/controller/controller_test.go b/internal/controller/controller_test.go
index f1e4bb4..4cc0b5c 100644
--- a/internal/controller/controller_test.go
+++ b/internal/controller/controller_test.go
@@ -7,7 +7,6 @@ import (
 	"github.com/stretchr/testify/require"
 	"go.uber.org/goleak"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-	"k8s.io/apimachinery/pkg/runtime"
 	"k8s.io/utils/ptr"
 	"sigs.k8s.io/controller-runtime/pkg/client"
 	"sigs.k8s.io/controller-runtime/pkg/client/fake"
@@ -22,9 +21,6 @@ func TestMain(m *testing.M) {
 }
 
 func Test_aiGatewayRouteIndexFunc(t *testing.T) {
-	scheme := runtime.NewScheme()
-	require.NoError(t, aigv1a1.AddToScheme(scheme))
-
 	c := fake.NewClientBuilder().
 		WithScheme(scheme).
 		WithIndex(&aigv1a1.AIGatewayRoute{}, k8sClientIndexBackendToReferencingAIGatewayRoute, aiGatewayRouteIndexFunc).
@@ -137,9 +133,6 @@ func Test_backendSecurityPolicyIndexFunc(t *testing.T) {
 		},
 	} {
 		t.Run(bsp.name, func(t *testing.T) {
-			scheme := runtime.NewScheme()
-			require.NoError(t, aigv1a1.AddToScheme(scheme))
-
 			c := fake.NewClientBuilder().
 				WithScheme(scheme).
 				WithIndex(&aigv1a1.BackendSecurityPolicy{}, k8sClientIndexSecretToReferencingBackendSecurityPolicy, backendSecurityPolicyIndexFunc).
diff --git a/internal/controller/sink_test.go b/internal/controller/sink_test.go
index df0aae8..a35d221 100644
--- a/internal/controller/sink_test.go
+++ b/internal/controller/sink_test.go
@@ -30,7 +30,7 @@ import (
 
 func requireNewFakeClientWithIndexes(t *testing.T) client.Client {
 	builder := fake.NewClientBuilder().WithScheme(scheme)
-	err := applyIndexing(context.Background(), func(ctx context.Context, obj client.Object, field string, extractValue client.IndexerFunc) error {
+	err := applyIndexing(context.Background(), func(_ context.Context, obj client.Object, field string, extractValue client.IndexerFunc) error {
 		builder = builder.WithIndex(obj, field, extractValue)
 		return nil
 	})
@@ -501,8 +501,7 @@ func TestConfigSink_SyncExtprocDeployment(t *testing.T) {
 			},
 		},
 	} {
-		err := fakeClient.Create(context.Background(), bsp, &client.CreateOptions{})
-		require.NoError(t, err)
+		require.NoError(t, fakeClient.Create(context.Background(), bsp, &client.CreateOptions{}))
 	}
 
 	for _, b := range []*aigv1a1.AIServiceBackend{
@@ -530,8 +529,7 @@ func TestConfigSink_SyncExtprocDeployment(t *testing.T) {
 			},
 		},
 	} {
-		err := fakeClient.Create(context.Background(), b, &client.CreateOptions{})
-		require.NoError(t, err)
+		require.NoError(t, fakeClient.Create(context.Background(), b, &client.CreateOptions{}))
 	}
 	require.NotNil(t, s)
 
diff --git a/internal/extproc/mocks_test.go b/internal/extproc/mocks_test.go
index d1f2d5f..c731d80 100644
--- a/internal/extproc/mocks_test.go
+++ b/internal/extproc/mocks_test.go
@@ -97,7 +97,7 @@ func (m mockTranslator) ResponseError(_ map[string]string, body io.Reader) (head
 }
 
 // ResponseBody implements [translator.Translator.ResponseBody].
-func (m mockTranslator) ResponseBody(respHeader map[string]string, body io.Reader, _ bool) (headerMutation *extprocv3.HeaderMutation, bodyMutation *extprocv3.BodyMutation, tokenUsage translator.LLMTokenUsage, err error) {
+func (m mockTranslator) ResponseBody(_ map[string]string, body io.Reader, _ bool) (headerMutation *extprocv3.HeaderMutation, bodyMutation *extprocv3.BodyMutation, tokenUsage translator.LLMTokenUsage, err error) {
 	if m.expResponseBody != nil {
 		buf, err := io.ReadAll(body)
 		require.NoError(m.t, err)
@@ -179,7 +179,7 @@ func (m mockExternalProcessingStream) Recv() (*extprocv3.ProcessingRequest, erro
 }
 
 // SetHeader implements [extprocv3.ExternalProcessor_ProcessServer].
-func (m mockExternalProcessingStream) SetHeader(md metadata.MD) error { panic("TODO") }
+func (m mockExternalProcessingStream) SetHeader(_ metadata.MD) error { panic("TODO") }
 
 // SendHeader implements [extprocv3.ExternalProcessor_ProcessServer].
 func (m mockExternalProcessingStream) SendHeader(metadata.MD) error { panic("TODO") }
diff --git a/internal/extproc/router/router_test.go b/internal/extproc/router/router_test.go
index c6a359b..34b23e7 100644
--- a/internal/extproc/router/router_test.go
+++ b/internal/extproc/router/router_test.go
@@ -18,7 +18,7 @@ func (c *dummyCustomRouter) Calculate(map[string]string) (*filterapi.Backend, er
 }
 
 func TestRouter_NewRouter_Custom(t *testing.T) {
-	r, err := NewRouter(&filterapi.Config{}, func(defaultRouter x.Router, config *filterapi.Config) x.Router {
+	r, err := NewRouter(&filterapi.Config{}, func(defaultRouter x.Router, _ *filterapi.Config) x.Router {
 		require.NotNil(t, defaultRouter)
 		_, ok := defaultRouter.(*router)
 		require.True(t, ok) // Checking if the default router is correctly passed.
diff --git a/internal/extproc/translator/openai_awsbedrock_test.go b/internal/extproc/translator/openai_awsbedrock_test.go
index 22bb232..873ba0d 100644
--- a/internal/extproc/translator/openai_awsbedrock_test.go
+++ b/internal/extproc/translator/openai_awsbedrock_test.go
@@ -881,18 +881,18 @@ func TestOpenAIToAWSBedrockTranslatorV1ChatCompletion_ResponseBody(t *testing.T)
 	})
 	tests := []struct {
 		name   string
-		input  awsbedrock.ConverseOutput
+		input  awsbedrock.ConverseResponse
 		output openai.ChatCompletionResponse
 	}{
 		{
 			name: "basic_testing",
-			input: awsbedrock.ConverseOutput{
+			input: awsbedrock.ConverseResponse{
 				Usage: &awsbedrock.TokenUsage{
 					InputTokens:  10,
 					OutputTokens: 20,
 					TotalTokens:  30,
 				},
-				Output: &awsbedrock.ConverseOutput_{
+				Output: &awsbedrock.ConverseOutput{
 					Message: awsbedrock.Message{
 						Role: "assistant",
 						Content: []*awsbedrock.ContentBlock{
@@ -940,14 +940,14 @@ func TestOpenAIToAWSBedrockTranslatorV1ChatCompletion_ResponseBody(t *testing.T)
 		},
 		{
 			name: "test stop reason",
-			input: awsbedrock.ConverseOutput{
+			input: awsbedrock.ConverseResponse{
 				Usage: &awsbedrock.TokenUsage{
 					InputTokens:  10,
 					OutputTokens: 20,
 					TotalTokens:  30,
 				},
 				StopReason: ptr.To("stop_sequence"),
-				Output: &awsbedrock.ConverseOutput_{
+				Output: &awsbedrock.ConverseOutput{
 					Message: awsbedrock.Message{
 						Role: awsbedrock.ConversationRoleAssistant,
 						Content: []*awsbedrock.ContentBlock{
@@ -977,9 +977,9 @@ func TestOpenAIToAWSBedrockTranslatorV1ChatCompletion_ResponseBody(t *testing.T)
 		},
 		{
 			name: "test tool use",
-			input: awsbedrock.ConverseOutput{
+			input: awsbedrock.ConverseResponse{
 				StopReason: ptr.To(awsbedrock.StopReasonToolUse),
-				Output: &awsbedrock.ConverseOutput_{
+				Output: &awsbedrock.ConverseOutput{
 					Message: awsbedrock.Message{
 						Role: awsbedrock.ConversationRoleAssistant,
 						Content: []*awsbedrock.ContentBlock{
diff --git a/tests/controller/controller_test.go b/tests/controller/controller_test.go
index 3ce300f..eb90691 100644
--- a/tests/controller/controller_test.go
+++ b/tests/controller/controller_test.go
@@ -260,7 +260,7 @@ func TestStartControllers(t *testing.T) {
 		// Verify that the HTTPRoute resource is recreated.
 		require.Eventually(t, func() bool {
 			var egExtPolicy egv1a1.EnvoyExtensionPolicy
-			err := c.Get(ctx, client.ObjectKey{Name: policyName, Namespace: policyNamespace}, &egExtPolicy)
+			err = c.Get(ctx, client.ObjectKey{Name: policyName, Namespace: policyNamespace}, &egExtPolicy)
 			if err != nil {
 				t.Logf("failed to get envoy extension policy %s: %v", policyName, err)
 				return false
@@ -277,7 +277,7 @@ func TestStartControllers(t *testing.T) {
 		// Verify that the HTTPRoute resource is recreated.
 		require.Eventually(t, func() bool {
 			var httpRoute gwapiv1.HTTPRoute
-			err := c.Get(ctx, client.ObjectKey{Name: routeName, Namespace: routeNamespace}, &httpRoute)
+			err = c.Get(ctx, client.ObjectKey{Name: routeName, Namespace: routeNamespace}, &httpRoute)
 			if err != nil {
 				t.Logf("failed to get http route %s: %v", routeName, err)
 				return false
@@ -296,7 +296,7 @@ func TestStartControllers(t *testing.T) {
 		// Verify that the deployment is recreated.
 		require.Eventually(t, func() bool {
 			var deployment appsv1.Deployment
-			err := c.Get(ctx, client.ObjectKey{Name: deployName, Namespace: deployNamespace}, &deployment)
+			err = c.Get(ctx, client.ObjectKey{Name: deployName, Namespace: deployNamespace}, &deployment)
 			if err != nil {
 				t.Logf("failed to get deployment %s: %v", deployName, err)
 				return false
diff --git a/tests/internal/envtest.go b/tests/internal/envtest.go
index b696eb8..c0171ad 100644
--- a/tests/internal/envtest.go
+++ b/tests/internal/envtest.go
@@ -42,7 +42,7 @@ func NewEnvTest(t *testing.T) (c client.Client, cfg *rest.Config, k kubernetes.I
 	cfg, err = env.Start()
 	require.NoError(t, err)
 	t.Cleanup(func() {
-		if err := env.Stop(); err != nil {
+		if err = env.Stop(); err != nil {
 			panic(fmt.Sprintf("Failed to stop testenv: %v", err))
 		}
 	})
@@ -59,9 +59,11 @@ func NewEnvTest(t *testing.T) (c client.Client, cfg *rest.Config, k kubernetes.I
 // It returns the path to the CRD as-is to make it easier to use in the caller.
 func requireThirdPartyCRDDownloaded(t *testing.T, path, url string) string {
 	if _, err := os.Stat(path); os.IsNotExist(err) {
-		crd, err := http.DefaultClient.Get(url)
+		var crd *http.Response
+		crd, err = http.DefaultClient.Get(url)
 		require.NoError(t, err)
-		body, err := os.Create(path)
+		var body *os.File
+		body, err = os.Create(path)
 		defer func() {
 			_ = crd.Body.Close()
 		}()
diff --git a/tests/internal/testupstreamlib/testupstream/main.go b/tests/internal/testupstreamlib/testupstream/main.go
index 6301767..999b75d 100644
--- a/tests/internal/testupstreamlib/testupstream/main.go
+++ b/tests/internal/testupstreamlib/testupstream/main.go
@@ -47,7 +47,7 @@ func doMain(l net.Listener) {
 		}
 	}
 	defer l.Close()
-	http.HandleFunc("/health", func(writer http.ResponseWriter, request *http.Request) { writer.WriteHeader(http.StatusOK) })
+	http.HandleFunc("/health", func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusOK) })
 	http.HandleFunc("/", handler)
 	if err := http.Serve(l, nil); err != nil { // nolint: gosec
 		logger.Printf("failed to serve: %v", err)
@@ -127,9 +127,8 @@ func handler(w http.ResponseWriter, r *http.Request) {
 			logger.Println(msg)
 			http.Error(w, msg, http.StatusBadRequest)
 			return
-		} else {
-			logger.Println("testupstream-id matched:", v)
 		}
+		logger.Println("testupstream-id matched:", v)
 	} else {
 		logger.Println("no expected testupstream-id")
 	}
@@ -157,7 +156,8 @@ func handler(w http.ResponseWriter, r *http.Request) {
 	}
 
 	if expectedReqBody := r.Header.Get(testupstreamlib.ExpectedRequestBodyHeaderKey); expectedReqBody != "" {
-		expectedBody, err := base64.StdEncoding.DecodeString(expectedReqBody)
+		var expectedBody []byte
+		expectedBody, err = base64.StdEncoding.DecodeString(expectedReqBody)
 		if err != nil {
 			logger.Println("failed to decode the expected request body")
 			http.Error(w, "failed to decode the expected request body", http.StatusBadRequest)
@@ -174,7 +174,8 @@ func handler(w http.ResponseWriter, r *http.Request) {
 	}
 
 	if v := r.Header.Get(testupstreamlib.ResponseHeadersKey); v != "" {
-		responseHeaders, err := base64.StdEncoding.DecodeString(v)
+		var responseHeaders []byte
+		responseHeaders, err = base64.StdEncoding.DecodeString(v)
 		if err != nil {
 			logger.Println("failed to decode the response headers")
 			http.Error(w, "failed to decode the response headers", http.StatusBadRequest)
@@ -212,8 +213,8 @@ func handler(w http.ResponseWriter, r *http.Request) {
 	switch r.Header.Get(testupstreamlib.ResponseTypeKey) {
 	case "sse":
 		w.Header().Set("Content-Type", "text/event-stream")
-
-		expResponseBody, err := base64.StdEncoding.DecodeString(r.Header.Get(testupstreamlib.ResponseBodyHeaderKey))
+		var expResponseBody []byte
+		expResponseBody, err = base64.StdEncoding.DecodeString(r.Header.Get(testupstreamlib.ResponseBodyHeaderKey))
 		if err != nil {
 			logger.Println("failed to decode the response body")
 			http.Error(w, "failed to decode the response body", http.StatusBadRequest)
@@ -245,7 +246,8 @@ func handler(w http.ResponseWriter, r *http.Request) {
 	case "aws-event-stream":
 		w.Header().Set("Content-Type", "application/vnd.amazon.eventstream")
 
-		expResponseBody, err := base64.StdEncoding.DecodeString(r.Header.Get(testupstreamlib.ResponseBodyHeaderKey))
+		var expResponseBody []byte
+		expResponseBody, err = base64.StdEncoding.DecodeString(r.Header.Get(testupstreamlib.ResponseBodyHeaderKey))
 		if err != nil {
 			logger.Println("failed to decode the response body")
 			http.Error(w, "failed to decode the response body", http.StatusBadRequest)
@@ -260,7 +262,7 @@ func handler(w http.ResponseWriter, r *http.Request) {
 				continue
 			}
 			time.Sleep(streamingInterval)
-			if err := e.Encode(w, eventstream.Message{
+			if err = e.Encode(w, eventstream.Message{
 				Headers: eventstream.Headers{{Name: "event-type", Value: eventstream.StringValue("content")}},
 				Payload: line,
 			}); err != nil {
@@ -270,7 +272,7 @@ func handler(w http.ResponseWriter, r *http.Request) {
 			logger.Println("response line sent:", string(line))
 		}
 
-		if err := e.Encode(w, eventstream.Message{
+		if err = e.Encode(w, eventstream.Message{
 			Headers: eventstream.Headers{{Name: "event-type", Value: eventstream.StringValue("end")}},
 			Payload: []byte("this-is-end"),
 		}); err != nil {
@@ -351,8 +353,9 @@ func getFakeResponse(path string) ([]byte, error) {
 	case "/v1/chat/completions":
 		const template = `{"choices":[{"message":{"content":"%s"}}]}`
 		msg := fmt.Sprintf(template,
-			chatCompletionFakeResponses[rand.New(rand.NewSource(uint64(time.Now().UnixNano()))). //nolint:gosec
-														Intn(len(chatCompletionFakeResponses))])
+			//nolint:gosec
+			chatCompletionFakeResponses[rand.New(rand.NewSource(uint64(time.Now().UnixNano()))).
+				Intn(len(chatCompletionFakeResponses))])
 		return []byte(msg), nil
 	default:
 		return nil, fmt.Errorf("unknown path: %s", path)
diff --git a/tests/internal/testupstreamlib/testupstream/main_test.go b/tests/internal/testupstreamlib/testupstream/main_test.go
index 2ed58ee..c98ac32 100644
--- a/tests/internal/testupstreamlib/testupstream/main_test.go
+++ b/tests/internal/testupstreamlib/testupstream/main_test.go
@@ -275,7 +275,8 @@ func Test_main(t *testing.T) {
 
 		decoder := eventstream.NewDecoder()
 		for i := 0; i < 5; i++ {
-			message, err := decoder.Decode(response.Body, nil)
+			var message eventstream.Message
+			message, err = decoder.Decode(response.Body, nil)
 			require.NoError(t, err)
 			require.Equal(t, "content", message.Headers.Get("event-type").String())
 			require.Equal(t, fmt.Sprintf("%d", i+1), string(message.Payload))