Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add errorlint #1688

Merged
merged 1 commit into from
Jun 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ linters:
enable:
- deadcode
- errcheck
- errorlint
- gofmt
- goimports
- gosec
Expand Down
8 changes: 4 additions & 4 deletions cmd/nginx-ingress/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func checkAWSEntitlement() error {

cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
return fmt.Errorf("error loading AWS configuration: %v", err)
return fmt.Errorf("error loading AWS configuration: %w", err)
}

mpm := marketplacemetering.New(marketplacemetering.Options{Region: cfg.Region, Credentials: cfg.Credentials})
Expand All @@ -56,16 +56,16 @@ func checkAWSEntitlement() error {

pk, err := base64.StdEncoding.DecodeString(pubKeyString)
if err != nil {
return fmt.Errorf("error decoding Public Key string: %v", err)
return fmt.Errorf("error decoding Public Key string: %w", err)
}
pubKey, err := jwt.ParseRSAPublicKeyFromPEM(pk)
if err != nil {
return fmt.Errorf("error parsing Public Key: %v", err)
return fmt.Errorf("error parsing Public Key: %w", err)
}

token, err := jwt.ParseWithClaims(*out.Signature, &claims{}, jwt.KnownKeyfunc(jwt.SigningMethodPS256, pubKey))
if err != nil {
return fmt.Errorf("error parsing the JWT token: %v", err)
return fmt.Errorf("error parsing the JWT token: %w", err)
}

if claims, ok := token.Claims.(*claims); ok && token.Valid {
Expand Down
6 changes: 3 additions & 3 deletions cmd/nginx-ingress/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -796,15 +796,15 @@ func validateCIDRorIP(cidr string) error {
func getAndValidateSecret(kubeClient *kubernetes.Clientset, secretNsName string) (secret *api_v1.Secret, err error) {
ns, name, err := k8s.ParseNamespaceName(secretNsName)
if err != nil {
return nil, fmt.Errorf("could not parse the %v argument: %v", secretNsName, err)
return nil, fmt.Errorf("could not parse the %v argument: %w", secretNsName, err)
}
secret, err = kubeClient.CoreV1().Secrets(ns).Get(context.TODO(), name, meta_v1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("could not get %v: %v", secretNsName, err)
return nil, fmt.Errorf("could not get %v: %w", secretNsName, err)
}
err = secrets.ValidateTLSSecret(secret)
if err != nil {
return nil, fmt.Errorf("%v is invalid: %v", secretNsName, err)
return nil, fmt.Errorf("%v is invalid: %w", secretNsName, err)
}
return secret, nil
}
Expand Down
128 changes: 64 additions & 64 deletions internal/configs/configurator.go

Large diffs are not rendered by default.

16 changes: 9 additions & 7 deletions internal/configs/parsing_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func GetMapKeyAsBool(m map[string]string, key string, context apiObject) (bool,
if str, exists := m[key]; exists {
b, err := ParseBool(str)
if err != nil {
return false, exists, fmt.Errorf("%s %v/%v '%s' contains invalid bool: %v, ignoring", context.GetObjectKind().GroupVersionKind().Kind, context.GetNamespace(), context.GetName(), key, err)
return false, exists, fmt.Errorf("%s %v/%v '%s' contains invalid bool: %w, ignoring", context.GetObjectKind().GroupVersionKind().Kind, context.GetNamespace(), context.GetName(), key, err)
}

return b, exists, nil
Expand All @@ -37,7 +37,7 @@ func GetMapKeyAsInt(m map[string]string, key string, context apiObject) (int, bo
if str, exists := m[key]; exists {
i, err := ParseInt(str)
if err != nil {
return 0, exists, fmt.Errorf("%s %v/%v '%s' contains invalid integer: %v, ignoring", context.GetObjectKind().GroupVersionKind().Kind, context.GetNamespace(), context.GetName(), key, err)
return 0, exists, fmt.Errorf("%s %v/%v '%s' contains invalid integer: %w, ignoring", context.GetObjectKind().GroupVersionKind().Kind, context.GetNamespace(), context.GetName(), key, err)
}

return i, exists, nil
Expand All @@ -51,7 +51,7 @@ func GetMapKeyAsInt64(m map[string]string, key string, context apiObject) (int64
if str, exists := m[key]; exists {
i, err := ParseInt64(str)
if err != nil {
return 0, exists, fmt.Errorf("%s %v/%v '%s' contains invalid integer: %v, ignoring", context.GetObjectKind().GroupVersionKind().Kind, context.GetNamespace(), context.GetName(), key, err)
return 0, exists, fmt.Errorf("%s %v/%v '%s' contains invalid integer: %w, ignoring", context.GetObjectKind().GroupVersionKind().Kind, context.GetNamespace(), context.GetName(), key, err)
}

return i, exists, nil
Expand All @@ -65,7 +65,7 @@ func GetMapKeyAsUint64(m map[string]string, key string, context apiObject, nonZe
if str, exists := m[key]; exists {
i, err := ParseUint64(str)
if err != nil {
return 0, exists, fmt.Errorf("%s %v/%v '%s' contains invalid uint64: %v, ignoring", context.GetObjectKind().GroupVersionKind().Kind, context.GetNamespace(), context.GetName(), key, err)
return 0, exists, fmt.Errorf("%s %v/%v '%s' contains invalid uint64: %w, ignoring", context.GetObjectKind().GroupVersionKind().Kind, context.GetNamespace(), context.GetName(), key, err)
}

if nonZero && i == 0 {
Expand Down Expand Up @@ -264,7 +264,7 @@ func ParsePortList(s string) ([]int, error) {
func parsePort(value string) (int, error) {
port, err := strconv.ParseInt(value, 10, 16)
if err != nil {
return 0, fmt.Errorf("Unable to parse port as integer: %s", err)
return 0, fmt.Errorf("Unable to parse port as integer: %w", err)
}

if port <= 0 {
Expand Down Expand Up @@ -344,8 +344,10 @@ func parseRewrites(service string) (serviceName string, rewrite string, err erro
return svcNameParts[1], rwPathParts[1], nil
}

var threshEx = regexp.MustCompile(`high=([1-9]|[1-9][0-9]|100) low=([1-9]|[1-9][0-9]|100)\b`)
var threshExR = regexp.MustCompile(`low=([1-9]|[1-9][0-9]|100) high=([1-9]|[1-9][0-9]|100)\b`)
var (
threshEx = regexp.MustCompile(`high=([1-9]|[1-9][0-9]|100) low=([1-9]|[1-9][0-9]|100)\b`)
threshExR = regexp.MustCompile(`low=([1-9]|[1-9][0-9]|100) high=([1-9]|[1-9][0-9]|100)\b`)
)

// VerifyAppProtectThresholds ensures that threshold values are set correctly
func VerifyAppProtectThresholds(value string) bool {
Expand Down
16 changes: 9 additions & 7 deletions internal/k8s/appprotect/app_protect_resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func validateRequiredFields(obj *unstructured.Unstructured, fieldsList [][]strin
for _, fields := range fieldsList {
field, found, err := unstructured.NestedMap(obj.Object, fields...)
if err != nil {
return fmt.Errorf("Error checking for required field %v: %v", field, err)
return fmt.Errorf("Error checking for required field %v: %w", field, err)
}
if !found {
return fmt.Errorf("Required field %v not found", field)
Expand All @@ -40,7 +40,7 @@ func validateRequiredSlices(obj *unstructured.Unstructured, fieldsList [][]strin
for _, fields := range fieldsList {
field, found, err := unstructured.NestedSlice(obj.Object, fields...)
if err != nil {
return fmt.Errorf("Error checking for required field %v: %v", field, err)
return fmt.Errorf("Error checking for required field %v: %w", field, err)
}
if !found {
return fmt.Errorf("Required field %v not found", field)
Expand All @@ -55,7 +55,7 @@ func validateAppProtectPolicy(policy *unstructured.Unstructured) error {

err := validateRequiredFields(policy, appProtectPolicyRequiredFields)
if err != nil {
return fmt.Errorf("Error validating App Protect Policy %v: %v", polName, err)
return fmt.Errorf("Error validating App Protect Policy %v: %w", polName, err)
}

return nil
Expand All @@ -66,14 +66,16 @@ func validateAppProtectLogConf(logConf *unstructured.Unstructured) error {
lcName := logConf.GetName()
err := validateRequiredFields(logConf, appProtectLogConfRequiredFields)
if err != nil {
return fmt.Errorf("Error validating App Protect Log Configuration %v: %v", lcName, err)
return fmt.Errorf("Error validating App Protect Log Configuration %v: %w", lcName, err)
}

return nil
}

var logDstEx = regexp.MustCompile(`(?:syslog:server=((?:\d{1,3}\.){3}\d{1,3}|localhost):\d{1,5})|stderr|(?:\/[\S]+)+`)
var logDstFileEx = regexp.MustCompile(`(?:\/[\S]+)+`)
var (
logDstEx = regexp.MustCompile(`(?:syslog:server=((?:\d{1,3}\.){3}\d{1,3}|localhost):\d{1,5})|stderr|(?:\/[\S]+)+`)
logDstFileEx = regexp.MustCompile(`(?:\/[\S]+)+`)
)

// ValidateAppProtectLogDestination validates destination for log configuration
func ValidateAppProtectLogDestination(dstAntn string) error {
Expand Down Expand Up @@ -131,7 +133,7 @@ func validateAppProtectUserSig(userSig *unstructured.Unstructured) error {
sigName := userSig.GetName()
err := validateRequiredSlices(userSig, appProtectUserSigRequiredSlices)
if err != nil {
return fmt.Errorf("Error validating App Protect User Signature %v: %v", sigName, err)
return fmt.Errorf("Error validating App Protect User Signature %v: %w", sigName, err)
}

return nil
Expand Down
38 changes: 19 additions & 19 deletions internal/k8s/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -1866,7 +1866,7 @@ func (lbc *LoadBalancerController) updateVirtualServersStatusFromEvents() error
events, err := lbc.client.CoreV1().Events(vs.Namespace).List(context.TODO(),
meta_v1.ListOptions{FieldSelector: fmt.Sprintf("involvedObject.name=%v,involvedObject.uid=%v", vs.Name, vs.UID)})
if err != nil {
allErrs = append(allErrs, fmt.Errorf("error trying to get events for VirtualServer %v/%v: %v", vs.Namespace, vs.Name, err))
allErrs = append(allErrs, fmt.Errorf("error trying to get events for VirtualServer %v/%v: %w", vs.Namespace, vs.Name, err))
break
}

Expand Down Expand Up @@ -1908,7 +1908,7 @@ func (lbc *LoadBalancerController) updateVirtualServerRoutesStatusFromEvents() e
events, err := lbc.client.CoreV1().Events(vsr.Namespace).List(context.TODO(),
meta_v1.ListOptions{FieldSelector: fmt.Sprintf("involvedObject.name=%v,involvedObject.uid=%v", vsr.Name, vsr.UID)})
if err != nil {
allErrs = append(allErrs, fmt.Errorf("error trying to get events for VirtualServerRoute %v/%v: %v", vsr.Namespace, vsr.Name, err))
allErrs = append(allErrs, fmt.Errorf("error trying to get events for VirtualServerRoute %v/%v: %w", vsr.Namespace, vsr.Name, err))
break
}

Expand Down Expand Up @@ -1973,7 +1973,7 @@ func (lbc *LoadBalancerController) updateTransportServersStatusFromEvents() erro
events, err := lbc.client.CoreV1().Events(ts.Namespace).List(context.TODO(),
meta_v1.ListOptions{FieldSelector: fmt.Sprintf("involvedObject.name=%v,involvedObject.uid=%v", ts.Name, ts.UID)})
if err != nil {
allErrs = append(allErrs, fmt.Errorf("error trying to get events for TransportServer %v/%v: %v", ts.Namespace, ts.Name, err))
allErrs = append(allErrs, fmt.Errorf("error trying to get events for TransportServer %v/%v: %w", ts.Namespace, ts.Name, err))
break
}

Expand Down Expand Up @@ -2199,14 +2199,14 @@ func (lbc *LoadBalancerController) getAppProtectLogConfAndDst(ing *networking.In
for _, logDst := range logDsts {
err := appprotect.ValidateAppProtectLogDestination(logDst)
if err != nil {
return apLogs, fmt.Errorf("Error Validating App Protect Destination Config for Ingress %v: %v", ing.Name, err)
return apLogs, fmt.Errorf("Error Validating App Protect Destination Config for Ingress %v: %w", ing.Name, err)
}
}

for i, logConfNsN := range logConfNsNs {
logConf, err := lbc.appProtectConfiguration.GetAppResource(appprotect.LogConfGVK.Kind, logConfNsN)
if err != nil {
return apLogs, fmt.Errorf("Error retrieving App Protect Log Config for Ingress %v: %v", ing.Name, err)
return apLogs, fmt.Errorf("Error retrieving App Protect Log Config for Ingress %v: %w", ing.Name, err)
}
apLogs = append(apLogs, configs.AppProtectLog{
LogConf: logConf,
Expand All @@ -2222,7 +2222,7 @@ func (lbc *LoadBalancerController) getAppProtectPolicy(ing *networking.Ingress)

apPolicy, err = lbc.appProtectConfiguration.GetAppResource(appprotect.PolicyGVK.Kind, polNsN)
if err != nil {
return nil, fmt.Errorf("Error retrieving App Protect Policy for Ingress %v: %v ", ing.Name, err)
return nil, fmt.Errorf("Error retrieving App Protect Policy for Ingress %v: %w", ing.Name, err)
}

return apPolicy, nil
Expand Down Expand Up @@ -2476,7 +2476,7 @@ func (lbc *LoadBalancerController) getPolicies(policies []conf_v1.PolicyReferenc

policyObj, exists, err := lbc.policyLister.GetByKey(policyKey)
if err != nil {
errors = append(errors, fmt.Errorf("Failed to get policy %s: %v", policyKey, err))
errors = append(errors, fmt.Errorf("Failed to get policy %s: %w", policyKey, err))
continue
}

Expand All @@ -2489,7 +2489,7 @@ func (lbc *LoadBalancerController) getPolicies(policies []conf_v1.PolicyReferenc

err = validation.ValidatePolicy(policy, lbc.isNginxPlus, lbc.enablePreviewPolicies, lbc.appProtectEnabled)
if err != nil {
errors = append(errors, fmt.Errorf("Policy %s is invalid: %v", policyKey, err))
errors = append(errors, fmt.Errorf("Policy %s is invalid: %w", policyKey, err))
continue
}

Expand Down Expand Up @@ -2601,7 +2601,7 @@ func (lbc *LoadBalancerController) addWAFPolicyRefs(

apPolicy, err := lbc.appProtectConfiguration.GetAppResource(appprotect.PolicyGVK.Kind, apPolKey)
if err != nil {
return fmt.Errorf("WAF policy %q is invalid: %v", apPolKey, err)
return fmt.Errorf("WAF policy %q is invalid: %w", apPolKey, err)
}
apPolRef[apPolKey] = apPolicy
}
Expand All @@ -2614,7 +2614,7 @@ func (lbc *LoadBalancerController) addWAFPolicyRefs(

logConf, err := lbc.appProtectConfiguration.GetAppResource(appprotect.LogConfGVK.Kind, logConfKey)
if err != nil {
return fmt.Errorf("WAF policy %q is invalid: %v", logConfKey, err)
return fmt.Errorf("WAF policy %q is invalid: %w", logConfKey, err)
}
logConfRef[logConfKey] = logConf
}
Expand Down Expand Up @@ -2717,7 +2717,7 @@ func (lbc *LoadBalancerController) createTransportServerEx(transportServer *conf
func (lbc *LoadBalancerController) getEndpointsForUpstream(namespace string, upstreamService string, upstreamPort uint16) (endps []podEndpoint, isExternal bool, err error) {
svc, err := lbc.getServiceForUpstream(namespace, upstreamService, upstreamPort)
if err != nil {
return nil, false, fmt.Errorf("Error getting service %v: %v", upstreamService, err)
return nil, false, fmt.Errorf("Error getting service %v: %w", upstreamService, err)
}

backend := &networking.IngressBackend{
Expand All @@ -2727,7 +2727,7 @@ func (lbc *LoadBalancerController) getEndpointsForUpstream(namespace string, ups

endps, isExternal, err = lbc.getEndpointsForIngressBackend(backend, svc)
if err != nil {
return nil, false, fmt.Errorf("Error retrieving endpoints for the service %v: %v", upstreamService, err)
return nil, false, fmt.Errorf("Error retrieving endpoints for the service %v: %w", upstreamService, err)
}

return endps, isExternal, err
Expand All @@ -2736,7 +2736,7 @@ func (lbc *LoadBalancerController) getEndpointsForUpstream(namespace string, ups
func (lbc *LoadBalancerController) getEndpointsForSubselector(namespace string, upstream conf_v1.Upstream) (endps []podEndpoint, err error) {
svc, err := lbc.getServiceForUpstream(namespace, upstream.Service, upstream.Port)
if err != nil {
return nil, fmt.Errorf("Error getting service %v: %v", upstream.Service, err)
return nil, fmt.Errorf("Error getting service %v: %w", upstream.Service, err)
}

var targetPort int32
Expand All @@ -2745,7 +2745,7 @@ func (lbc *LoadBalancerController) getEndpointsForSubselector(namespace string,
if port.Port == int32(upstream.Port) {
targetPort, err = lbc.getTargetPort(port, svc)
if err != nil {
return nil, fmt.Errorf("Error determining target port for port %v in service %v: %v", upstream.Port, svc.Name, err)
return nil, fmt.Errorf("Error determining target port for port %v in service %v: %w", upstream.Port, svc.Name, err)
}
break
}
Expand All @@ -2757,7 +2757,7 @@ func (lbc *LoadBalancerController) getEndpointsForSubselector(namespace string,

endps, err = lbc.getEndpointsForServiceWithSubselector(targetPort, upstream.Subselector, svc)
if err != nil {
return nil, fmt.Errorf("Error retrieving endpoints for the service %v: %v", upstream.Service, err)
return nil, fmt.Errorf("Error retrieving endpoints for the service %v: %w", upstream.Service, err)
}

return endps, err
Expand All @@ -2766,7 +2766,7 @@ func (lbc *LoadBalancerController) getEndpointsForSubselector(namespace string,
func (lbc *LoadBalancerController) getEndpointsForServiceWithSubselector(targetPort int32, subselector map[string]string, svc *api_v1.Service) (endps []podEndpoint, err error) {
pods, err := lbc.podLister.ListByNamespace(svc.Namespace, labels.Merge(svc.Spec.Selector, subselector).AsSelector())
if err != nil {
return nil, fmt.Errorf("Error getting pods in namespace %v that match the selector %v: %v", svc.Namespace, labels.Merge(svc.Spec.Selector, subselector), err)
return nil, fmt.Errorf("Error getting pods in namespace %v that match the selector %v: %w", svc.Namespace, labels.Merge(svc.Spec.Selector, subselector), err)
}

svcEps, err := lbc.endpointLister.GetServiceEndpoints(svc)
Expand Down Expand Up @@ -2904,7 +2904,7 @@ func (lbc *LoadBalancerController) getEndpointsForPort(endps api_v1.Endpoints, i
if (ingSvcPort.Type == intstr.Int && port.Port == int32(ingSvcPort.IntValue())) || (ingSvcPort.Type == intstr.String && port.Name == ingSvcPort.String()) {
targetPort, err = lbc.getTargetPort(port, svc)
if err != nil {
return nil, fmt.Errorf("Error determining target port for port %v in Ingress: %v", ingSvcPort, err)
return nil, fmt.Errorf("Error determining target port for port %v in Ingress: %w", ingSvcPort, err)
}
break
}
Expand Down Expand Up @@ -2988,7 +2988,7 @@ func (lbc *LoadBalancerController) getTargetPort(svcPort api_v1.ServicePort, svc

pods, err := lbc.podLister.ListByNamespace(svc.Namespace, labels.Set(svc.Spec.Selector).AsSelector())
if err != nil {
return 0, fmt.Errorf("Error getting pod information: %v", err)
return 0, fmt.Errorf("Error getting pod information: %w", err)
}

if len(pods) == 0 {
Expand All @@ -2999,7 +2999,7 @@ func (lbc *LoadBalancerController) getTargetPort(svcPort api_v1.ServicePort, svc

portNum, err := findPort(pod, svcPort)
if err != nil {
return 0, fmt.Errorf("Error finding named port %v in pod %s: %v", svcPort, pod.Name, err)
return 0, fmt.Errorf("Error finding named port %v in pod %s: %w", svcPort, pod.Name, err)
}

return portNum, nil
Expand Down
6 changes: 3 additions & 3 deletions internal/k8s/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -767,8 +767,8 @@ func TestGetPolicies(t *testing.T) {
if !reflect.DeepEqual(result, expectedPolicies) {
t.Errorf("lbc.getPolicies() returned \n%v but \nexpected %v", result, expectedPolicies)
}
if !reflect.DeepEqual(errors, expectedErrors) {
t.Errorf("lbc.getPolicies() returned \n%v but expected \n%v", errors, expectedErrors)
if diff := cmp.Diff(expectedErrors, errors, cmp.Comparer(errorComparer)); diff != "" {
t.Errorf("lbc.getPolicies() mismatch (-want +got):\n%s", diff)
}
}

Expand Down Expand Up @@ -1173,7 +1173,7 @@ func TestFindPoliciesForSecret(t *testing.T) {

func errorComparer(e1, e2 error) bool {
if e1 == nil || e2 == nil {
return e1 == e2
return errors.Is(e1, e2)
}

return e1.Error() == e2.Error()
Expand Down
2 changes: 1 addition & 1 deletion internal/k8s/secrets/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ var (

func errorComparer(e1, e2 error) bool {
if e1 == nil || e2 == nil {
return e1 == e2
return errors.Is(e1, e2)
}

return e1.Error() == e2.Error()
Expand Down
4 changes: 2 additions & 2 deletions internal/k8s/secrets/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func ValidateTLSSecret(secret *api_v1.Secret) error {

_, err := tls.X509KeyPair(secret.Data[api_v1.TLSCertKey], secret.Data[api_v1.TLSPrivateKeyKey])
if err != nil {
return fmt.Errorf("Failed to validate TLS cert and key: %v", err)
return fmt.Errorf("Failed to validate TLS cert and key: %w", err)
}

return nil
Expand Down Expand Up @@ -80,7 +80,7 @@ func ValidateCASecret(secret *api_v1.Secret) error {

_, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("Failed to validate certificate: %v", err)
return fmt.Errorf("Failed to validate certificate: %w", err)
}

return nil
Expand Down