diff --git a/.golangci.yaml b/.golangci.yaml index 07a59209..cc2c9bc0 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -6,21 +6,12 @@ linters: presets: [comments, common-false-positives, legacy, std-error-handling] rules: - linters: - - bodyclose - - errcheck - errchkjson - forbidigo - - gocritic - gosec - - govet - musttag - nilerr - - noctx - - predeclared - - staticcheck - - unconvert - unparam - - usestdlibvars text: .* paths: [third_party$, builtin$, examples$] warn-unused: true diff --git a/api/common.go b/api/common.go index 043c6e8e..030ff1cd 100644 --- a/api/common.go +++ b/api/common.go @@ -26,5 +26,5 @@ func (t Time) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - return []byte(jsonStr), nil + return jsonStr, nil } diff --git a/cmd/root.go b/cmd/root.go index f707ac24..5c2fef59 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -67,7 +67,7 @@ func setFlagsFromEnv(prefix string, fs *pflag.FlagSet) { } // remove trailing _ to reduce common errors with the prefix, i.e. people setting it to MY_PROG_ cleanPrefix := strings.TrimSuffix(prefix, "_") - name := fmt.Sprintf("%s_%s", cleanPrefix, strings.Replace(strings.ToUpper(f.Name), "-", "_", -1)) + name := fmt.Sprintf("%s_%s", cleanPrefix, strings.ReplaceAll(strings.ToUpper(f.Name), "-", "_")) if e, ok := os.LookupEnv(name); ok { _ = f.Value.Set(e) } diff --git a/pkg/agent/config.go b/pkg/agent/config.go index 252e3ff2..6bd1e12a 100644 --- a/pkg/agent/config.go +++ b/pkg/agent/config.go @@ -232,7 +232,9 @@ func InitAgentCmdFlags(c *cobra.Command, cfg *AgentCmdFlags) { false, fmt.Sprintf("Turns on the %s mode. The flag --credentials-file must also be passed.", JetstackSecureOAuth), ) - c.PersistentFlags().MarkHidden("venafi-cloud") + if err := c.PersistentFlags().MarkHidden("venafi-cloud"); err != nil { + panic(err) + } c.PersistentFlags().StringVarP( &cfg.ClientID, "client-id", @@ -247,7 +249,7 @@ func InitAgentCmdFlags(c *cobra.Command, cfg *AgentCmdFlags) { "private-key-path", "", "", - fmt.Sprintf("To be used in conjunction with --client-id. The path to the private key file for the service account."), + "To be used in conjunction with --client-id. The path to the private key file for the service account.", ) c.PersistentFlags().BoolVarP( &cfg.OneShot, @@ -334,7 +336,9 @@ func InitAgentCmdFlags(c *cobra.Command, cfg *AgentCmdFlags) { false, "Deprecated. No longer has an effect.", ) - c.PersistentFlags().MarkDeprecated("disable-compression", "no longer has an effect") + if err := c.PersistentFlags().MarkDeprecated("disable-compression", "no longer has an effect"); err != nil { + panic(err) + } // This is a hidden feature flag we use to build the "Machine Hub" feature // gradually without impacting customers. Once the feature is GA, we will @@ -345,7 +349,9 @@ func InitAgentCmdFlags(c *cobra.Command, cfg *AgentCmdFlags) { false, "Enables the MachineHub mode. The agent will push data to CyberArk MachineHub.", ) - c.PersistentFlags().MarkHidden("machine-hub") + if err := c.PersistentFlags().MarkHidden("machine-hub"); err != nil { + panic(err) + } } @@ -531,8 +537,8 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags) // Validation of `venafi-cloud.upload_path`. { var uploadPath string - switch { - case res.TLSPKMode == VenafiCloudKeypair: + switch res.TLSPKMode { // nolint:exhaustive + case VenafiCloudKeypair: if cfg.VenafiCloud == nil || cfg.VenafiCloud.UploadPath == "" { errs = multierror.Append(errs, fmt.Errorf("the venafi-cloud.upload_path field is required when using the %s mode", res.TLSPKMode)) break // Skip to the end of the switch statement. @@ -544,7 +550,7 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags) } uploadPath = cfg.VenafiCloud.UploadPath - case res.TLSPKMode == VenafiCloudVenafiConnection: + case VenafiCloudVenafiConnection: // The venafi-cloud.upload_path was initially meant to let users // configure HTTP proxies, but it has never been used since HTTP // proxies don't rewrite paths. Thus, we've disabled the ability to @@ -577,18 +583,18 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags) if res.TLSPKMode != Off { var clusterID string var organizationID string // Only used by the old jetstack-secure mode. - switch { - case res.TLSPKMode == VenafiCloudKeypair: + switch res.TLSPKMode { // nolint:exhaustive + case VenafiCloudKeypair: if cfg.ClusterID == "" { errs = multierror.Append(errs, fmt.Errorf("cluster_id is required in %s mode", res.TLSPKMode)) } clusterID = cfg.ClusterID - case res.TLSPKMode == VenafiCloudVenafiConnection: + case VenafiCloudVenafiConnection: if cfg.ClusterID == "" { errs = multierror.Append(errs, fmt.Errorf("cluster_id is required in %s mode", res.TLSPKMode)) } clusterID = cfg.ClusterID - case res.TLSPKMode == JetstackSecureOAuth || res.TLSPKMode == JetstackSecureAPIToken: + case JetstackSecureOAuth, JetstackSecureAPIToken: if cfg.OrganizationID == "" { errs = multierror.Append(errs, fmt.Errorf("organization_id is required")) } @@ -637,7 +643,7 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags) } // Validation of --install-namespace. - var installNS string = flags.InstallNS + installNS := flags.InstallNS if flags.InstallNS == "" { var err error installNS, err = getInClusterNamespace() @@ -650,7 +656,7 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags) // Validation of --venafi-connection and --venafi-connection-namespace. if res.TLSPKMode == VenafiCloudVenafiConnection { res.VenConnName = flags.VenConnName - var venConnNS string = flags.VenConnNS + venConnNS := flags.VenConnNS if flags.VenConnNS == "" { venConnNS = installNS } @@ -714,8 +720,8 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie var preflightClient client.Client metadata := &api.AgentMetadata{Version: version.PreflightVersion, ClusterID: cfg.ClusterID} - switch { - case cfg.TLSPKMode == JetstackSecureOAuth: + switch cfg.TLSPKMode { + case JetstackSecureOAuth: // Note that there are no command line flags to configure the // JetstackSecureOAuth mode. credsBytes, err := readCredentialsFile(flagCredentialsPath) @@ -734,7 +740,7 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie if err != nil { errs = multierror.Append(errs, err) } - case cfg.TLSPKMode == VenafiCloudKeypair: + case VenafiCloudKeypair: var creds client.Credentials if flagClientID != "" && flagCredentialsPath != "" { @@ -750,14 +756,15 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie break } - if flagClientID != "" && flagPrivateKeyPath != "" { + switch { + case flagClientID != "" && flagPrivateKeyPath != "": // If --client-id and --private-key-path are passed, then // --credentials-file is ignored. creds = &client.VenafiSvcAccountCredentials{ ClientID: flagClientID, PrivateKeyFile: flagPrivateKeyPath, } - } else if flagCredentialsPath != "" { + case flagCredentialsPath != "": credsBytes, err := readCredentialsFile(flagCredentialsPath) if err != nil { errs = multierror.Append(errs, multierror.Prefix(err, "credentials file:")) @@ -768,7 +775,7 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie errs = multierror.Append(errs, multierror.Prefix(err, "credentials file:")) break // Don't continue with the client since creds is invalid. } - } else { + default: return nil, fmt.Errorf("programmer mistake: --client-id and --private-key-path or --credentials-file must have been provided") } @@ -777,7 +784,7 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie if err != nil { errs = multierror.Append(errs, err) } - case cfg.TLSPKMode == VenafiCloudVenafiConnection: + case VenafiCloudVenafiConnection: var restCfg *rest.Config restCfg, err := kubeconfig.LoadRESTConfig("") if err != nil { @@ -789,13 +796,13 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie if err != nil { errs = multierror.Append(errs, err) } - case cfg.TLSPKMode == JetstackSecureAPIToken: + case JetstackSecureAPIToken: var err error preflightClient, err = client.NewAPITokenClient(metadata, flagAPIToken, cfg.Server) if err != nil { errs = multierror.Append(errs, err) } - case cfg.TLSPKMode == Off: + case Off: // No client needed in this mode. default: panic(fmt.Errorf("programmer mistake: auth mode not implemented: %s", cfg.TLSPKMode)) diff --git a/pkg/client/client_oauth.go b/pkg/client/client_oauth.go index b8f3f5bd..dfac5da9 100644 --- a/pkg/client/client_oauth.go +++ b/pkg/client/client_oauth.go @@ -186,7 +186,7 @@ func (c *OAuthClient) renewAccessToken(ctx context.Context) error { payload.Set("audience", audience) payload.Set("username", c.credentials.UserID) payload.Set("password", c.credentials.UserSecret) - req, err := http.NewRequestWithContext(ctx, "POST", tokenURL, strings.NewReader(payload.Encode())) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(payload.Encode())) if err != nil { return errors.WithStack(err) } diff --git a/pkg/client/client_venafi_cloud.go b/pkg/client/client_venafi_cloud.go index 780f58b9..1a729458 100644 --- a/pkg/client/client_venafi_cloud.go +++ b/pkg/client/client_venafi_cloud.go @@ -71,7 +71,7 @@ type ( } accessTokenInformation struct { - AccessToken string `json:"access_token"` //base 64 encoded token + AccessToken string `json:"access_token"` // base 64 encoded token Type string `json:"token_type"` // always be “bearer” for now ExpiresIn int64 `json:"expires_in"` // number of seconds after which the access token will expire } diff --git a/pkg/datagatherer/k8s/cache.go b/pkg/datagatherer/k8s/cache.go index e64f13c5..5ecc1fac 100644 --- a/pkg/datagatherer/k8s/cache.go +++ b/pkg/datagatherer/k8s/cache.go @@ -56,14 +56,14 @@ func onAdd(log logr.Logger, obj interface{}, dgCache *cache.Cache) { // onUpdate handles the informer update events, replacing the old object with the new one // if it's present in the data gatherer's cache, (if the object isn't present, it gets added). // The cache key is the uid of the object -func onUpdate(log logr.Logger, old, new interface{}, dgCache *cache.Cache) { - item, ok := old.(cacheResource) +func onUpdate(log logr.Logger, oldObj, newObj interface{}, dgCache *cache.Cache) { + item, ok := oldObj.(cacheResource) if ok { - cacheObject := updateCacheGatheredResource(string(item.GetUID()), new, dgCache) + cacheObject := updateCacheGatheredResource(string(item.GetUID()), newObj, dgCache) dgCache.Set(string(item.GetUID()), cacheObject, cache.DefaultExpiration) return } - logCacheUpdateFailure(log, old, "update") + logCacheUpdateFailure(log, oldObj, "update") } // onDelete handles the informer deletion events, updating the object's properties with the deletion diff --git a/pkg/datagatherer/k8s/cache_test.go b/pkg/datagatherer/k8s/cache_test.go index a8616b89..5f4fe793 100644 --- a/pkg/datagatherer/k8s/cache_test.go +++ b/pkg/datagatherer/k8s/cache_test.go @@ -52,7 +52,9 @@ func TestOnAddCache(t *testing.T) { getObject("v1", "Service", "testservice", "testns", false), getObject("foobar/v1", "NotFoo", "notfoo", "testns", false), }, - eventFunc: func(log logr.Logger, old, new interface{}, dgCache *cache.Cache) { onDelete(log, old, dgCache) }, + eventFunc: func(log logr.Logger, oldObj, newObj interface{}, dgCache *cache.Cache) { + onDelete(log, oldObj, dgCache) + }, expected: []*api.GatheredResource{ makeGatheredResource( getObject("foobar/v1", "Foo", "testfoo", "testns", false), diff --git a/pkg/datagatherer/k8s/dynamic.go b/pkg/datagatherer/k8s/dynamic.go index 3df1c003..810f9854 100644 --- a/pkg/datagatherer/k8s/dynamic.go +++ b/pkg/datagatherer/k8s/dynamic.go @@ -76,27 +76,27 @@ func (c *ConfigDynamic) UnmarshalYAML(unmarshal func(interface{}) error) error { // validate validates the configuration. func (c *ConfigDynamic) validate() error { - var errors []string + var errs []string if len(c.ExcludeNamespaces) > 0 && len(c.IncludeNamespaces) > 0 { - errors = append(errors, "cannot set excluded and included namespaces") + errs = append(errs, "cannot set excluded and included namespaces") } if c.GroupVersionResource.Resource == "" { - errors = append(errors, "invalid configuration: GroupVersionResource.Resource cannot be empty") + errs = append(errs, "invalid configuration: GroupVersionResource.Resource cannot be empty") } for i, selectorString := range c.FieldSelectors { if selectorString == "" { - errors = append(errors, fmt.Sprintf("invalid field selector %d: must not be empty", i)) + errs = append(errs, fmt.Sprintf("invalid field selector %d: must not be empty", i)) } _, err := fields.ParseSelector(selectorString) if err != nil { - errors = append(errors, fmt.Sprintf("invalid field selector %d: %s", i, err)) + errs = append(errs, fmt.Sprintf("invalid field selector %d: %s", i, err)) } } - if len(errors) > 0 { - return fmt.Errorf(strings.Join(errors, ", ")) + if len(errs) > 0 { + return errors.New(strings.Join(errs, ", ")) } return nil @@ -221,8 +221,8 @@ func (c *ConfigDynamic) newDataGathererWithClient(ctx context.Context, cl dynami AddFunc: func(obj interface{}) { onAdd(log, obj, dgCache) }, - UpdateFunc: func(old, new interface{}) { - onUpdate(log, old, new, dgCache) + UpdateFunc: func(oldObj, newObj interface{}) { + onUpdate(log, oldObj, newObj, dgCache) }, DeleteFunc: func(obj interface{}) { onDelete(log, obj, dgCache) @@ -329,7 +329,7 @@ func (g *DataGathererDynamic) Fetch() (interface{}, int, error) { fetchNamespaces = []string{metav1.NamespaceAll} } - //delete expired items from the cache + // delete expired items from the cache g.cache.DeleteExpired() for _, item := range g.cache.Items() { // filter cache items by namespace @@ -371,11 +371,15 @@ func redactList(list []*api.GatheredResource, excludeAnnotKeys, excludeLabelKeys for _, gvk := range gvks { // secret object if gvk.Kind == "Secret" && (gvk.Group == "core" || gvk.Group == "") { - Select(SecretSelectedFields, resource) + if err := Select(SecretSelectedFields, resource); err != nil { + return err + } // route object } else if gvk.Kind == "Route" && gvk.Group == "route.openshift.io" { - Select(RouteSelectedFields, resource) + if err := Select(RouteSelectedFields, resource); err != nil { + return err + } } } diff --git a/pkg/datagatherer/k8s/dynamic_test.go b/pkg/datagatherer/k8s/dynamic_test.go index c421fcfb..58827a6a 100644 --- a/pkg/datagatherer/k8s/dynamic_test.go +++ b/pkg/datagatherer/k8s/dynamic_test.go @@ -23,7 +23,6 @@ import ( "k8s.io/client-go/dynamic/dynamicinformer" "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/informers" - "k8s.io/client-go/kubernetes" fakeclientset "k8s.io/client-go/kubernetes/fake" k8scache "k8s.io/client-go/tools/cache" @@ -668,17 +667,18 @@ func TestDynamicGatherer_Fetch(t *testing.T) { factory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(cl, 10*time.Minute, metav1.NamespaceAll, nil) resourceInformer := factory.ForResource(tc.config.GroupVersionResource) testInformer := resourceInformer.Informer() - testInformer.AddEventHandler(k8scache.ResourceEventHandlerFuncs{ + _, err = testInformer.AddEventHandler(k8scache.ResourceEventHandlerFuncs{ DeleteFunc: func(obj interface{}) { defer wg.Done() time.Sleep(100 * time.Millisecond) }, - UpdateFunc: func(old, new interface{}) { + UpdateFunc: func(oldObj, newObj interface{}) { defer wg.Done() time.Sleep(100 * time.Millisecond) }, }) - //start test Informer + require.NoError(t, err) + // start test Informer factory.Start(ctx.Done()) k8scache.WaitForCacheSync(ctx.Done(), testInformer.HasSynced) @@ -719,8 +719,8 @@ func TestDynamicGatherer_Fetch(t *testing.T) { for ns, update := range tc.updateObjects { wg.Add(1) - new := update.(*unstructured.Unstructured) - _, err := cl.Resource(tc.config.GroupVersionResource).Namespace(ns).Update(ctx, new, metav1.UpdateOptions{}) + newObj := update.(*unstructured.Unstructured) + _, err := cl.Resource(tc.config.GroupVersionResource).Namespace(ns).Update(ctx, newObj, metav1.UpdateOptions{}) if err != nil { t.Fatalf("unexpected client update error: %+v", err) } @@ -968,8 +968,7 @@ func TestDynamicGathererNativeResources_Fetch(t *testing.T) { var wg sync.WaitGroup ctx := context.Background() - var clientset kubernetes.Interface - clientset = fakeclientset.NewSimpleClientset(tc.addObjects...) + clientset := fakeclientset.NewSimpleClientset(tc.addObjects...) // init the datagatherer's informer with the client dg, err := tc.config.newDataGathererWithClient(ctx, nil, clientset) @@ -985,18 +984,19 @@ func TestDynamicGathererNativeResources_Fetch(t *testing.T) { informers.WithNamespace(metav1.NamespaceAll), informers.WithTweakListOptions(func(options *metav1.ListOptions) {})) testInformer := factory.Core().V1().Pods().Informer() - testInformer.AddEventHandler(k8scache.ResourceEventHandlerFuncs{ + _, err = testInformer.AddEventHandler(k8scache.ResourceEventHandlerFuncs{ DeleteFunc: func(obj interface{}) { defer wg.Done() time.Sleep(100 * time.Millisecond) }, - UpdateFunc: func(old, new interface{}) { + UpdateFunc: func(oldObj, newObj interface{}) { defer wg.Done() time.Sleep(100 * time.Millisecond) }, }) + require.NoError(t, err) - //start test Informer + // start test Informer factory.Start(ctx.Done()) k8scache.WaitForCacheSync(ctx.Done(), testInformer.HasSynced) dgd := dg.(*DataGathererDynamic) @@ -1035,8 +1035,8 @@ func TestDynamicGathererNativeResources_Fetch(t *testing.T) { for ns, update := range tc.updateObjects { wg.Add(1) - new := update.(*corev1.Pod) - _, err := clientset.CoreV1().Pods(ns).Update(ctx, new, metav1.UpdateOptions{}) + newObj := update.(*corev1.Pod) + _, err := clientset.CoreV1().Pods(ns).Update(ctx, newObj, metav1.UpdateOptions{}) if err != nil { t.Fatalf("unexpected client update error: %+v", err) } diff --git a/pkg/datagatherer/k8s/fieldfilter.go b/pkg/datagatherer/k8s/fieldfilter.go index f3f34c89..ed39acb3 100644 --- a/pkg/datagatherer/k8s/fieldfilter.go +++ b/pkg/datagatherer/k8s/fieldfilter.go @@ -80,10 +80,8 @@ func Select(fields []FieldPath, resource *unstructured.Unstructured) error { } // Redact removes the supplied fields from the resource -func Redact(fields []FieldPath, resource *unstructured.Unstructured) error { +func Redact(fields []FieldPath, resource *unstructured.Unstructured) { for _, field := range fields { unstructured.RemoveNestedField(resource.Object, field...) } - - return nil } diff --git a/pkg/datagatherer/k8s/fieldfilter_test.go b/pkg/datagatherer/k8s/fieldfilter_test.go index b518f3ee..e5ee1e9c 100644 --- a/pkg/datagatherer/k8s/fieldfilter_test.go +++ b/pkg/datagatherer/k8s/fieldfilter_test.go @@ -175,8 +175,7 @@ func TestRedactSecret(t *testing.T) { {"data", "tls.key"}, } - err := Redact(fieldsToRedact, resource) - require.NoError(t, err) + Redact(fieldsToRedact, resource) bytes, err := json.MarshalIndent(resource, "", " ") require.NoError(t, err) @@ -217,8 +216,7 @@ func TestRedactPod(t *testing.T) { {"metadata", "managedFields"}, } - err := Redact(fieldsToRedact, resource) - require.NoError(t, err) + Redact(fieldsToRedact, resource) bytes, err := json.MarshalIndent(resource, "", " ") require.NoError(t, err) @@ -248,8 +246,7 @@ func TestRedactMissingField(t *testing.T) { {"missing"}, } - err := Redact(fieldsToRedact, resource) - require.NoError(t, err) + Redact(fieldsToRedact, resource) bytes, err := json.MarshalIndent(resource, "", " ") require.NoError(t, err) diff --git a/pkg/echo/echo_test.go b/pkg/echo/echo_test.go index b023ae5e..91a7f1ec 100644 --- a/pkg/echo/echo_test.go +++ b/pkg/echo/echo_test.go @@ -2,6 +2,7 @@ package echo import ( "bytes" + "context" "encoding/json" "net/http" "net/http/httptest" @@ -60,7 +61,7 @@ func TestEchoServerRequestResponse(t *testing.T) { } // generate a request to test the handler containing the JSON data as a body - req, err := http.NewRequest(sampleUpload.method, "http://example.com/api/v1/datareadings", bytes.NewBuffer(requestBodyJSON)) + req, err := http.NewRequestWithContext(context.TODO(), sampleUpload.method, "http://example.com/api/v1/datareadings", bytes.NewBuffer(requestBodyJSON)) if err != nil { t.Fatalf("[%s]\nfailed to generate request to test echo server: %s", sampleUpload.description, err) } diff --git a/pkg/internal/cyberark/identity/identity.go b/pkg/internal/cyberark/identity/identity.go index 726792b0..da2d648a 100644 --- a/pkg/internal/cyberark/identity/identity.go +++ b/pkg/internal/cyberark/identity/identity.go @@ -299,7 +299,7 @@ func (c *Client) doStartAuthentication(ctx context.Context, username string) (ad defer httpResponse.Body.Close() - if httpResponse.StatusCode != 200 { + if httpResponse.StatusCode != http.StatusOK { err := fmt.Errorf("got unexpected status code %s from request to start authentication in CyberArk Identity API", httpResponse.Status) if httpResponse.StatusCode >= 500 || httpResponse.StatusCode < 400 { return response, err @@ -410,7 +410,7 @@ func (c *Client) doAdvanceAuthentication(ctx context.Context, username string, p // Important: Even login failures can produce a 200 status code, so this // check won't catch all failures - if httpResponse.StatusCode != 200 { + if httpResponse.StatusCode != http.StatusOK { err := fmt.Errorf("got unexpected status code %s from request to advance authentication in CyberArk Identity API", httpResponse.Status) if httpResponse.StatusCode >= 500 || httpResponse.StatusCode < 400 { return err diff --git a/pkg/internal/cyberark/identity/mock.go b/pkg/internal/cyberark/identity/mock.go index cb65e0ad..df73afd7 100644 --- a/pkg/internal/cyberark/identity/mock.go +++ b/pkg/internal/cyberark/identity/mock.go @@ -115,7 +115,7 @@ func (mis *mockIdentityServer) handleStartAuthentication(w http.ResponseWriter, if err := checkRequestHeaders(r); err != nil { w.WriteHeader(http.StatusForbidden) - _, _ = w.Write([]byte(fmt.Sprintf(`{"message":"issues with headers sent to mock server: %s"}`, err.Error()))) + fmt.Fprintf(w, `{"message":"issues with headers sent to mock server: %s"}`, err.Error()) return } @@ -126,7 +126,7 @@ func (mis *mockIdentityServer) handleStartAuthentication(w http.ResponseWriter, if err := decoder.Decode(&reqBody); err != nil { w.WriteHeader(http.StatusInternalServerError) - _, _ = w.Write([]byte(fmt.Sprintf(`{"message":"failed to unmarshal request body: %s"}`, err))) + fmt.Fprintf(w, `{"message":"failed to unmarshal request body: %s"}`, err) return } @@ -172,7 +172,7 @@ func (mis *mockIdentityServer) handleAdvanceAuthentication(w http.ResponseWriter if err := checkRequestHeaders(r); err != nil { w.WriteHeader(http.StatusForbidden) - _, _ = w.Write([]byte(fmt.Sprintf(`{"message":"issues with headers sent to mock server: %s"}`, err.Error()))) + fmt.Fprintf(w, `{"message":"issues with headers sent to mock server: %s"}`, err.Error()) } decoder := json.NewDecoder(r.Body) @@ -182,7 +182,7 @@ func (mis *mockIdentityServer) handleAdvanceAuthentication(w http.ResponseWriter if err := decoder.Decode(&advanceBody); err != nil { w.WriteHeader(http.StatusInternalServerError) - _, _ = w.Write([]byte(fmt.Sprintf(`{"message":"failed to unmarshal request body: %s"}`, err))) + fmt.Fprintf(w, `{"message":"failed to unmarshal request body: %s"}`, err) return } diff --git a/pkg/internal/cyberark/servicediscovery/discovery.go b/pkg/internal/cyberark/servicediscovery/discovery.go index 3e6b658d..41facba6 100644 --- a/pkg/internal/cyberark/servicediscovery/discovery.go +++ b/pkg/internal/cyberark/servicediscovery/discovery.go @@ -97,10 +97,10 @@ func (c *Client) DiscoverIdentityAPIURL(ctx context.Context, subdomain string) ( defer resp.Body.Close() - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK { // a 404 error is returned with an empty JSON body "{}" if the subdomain is unknown; at the time of writing, we haven't observed // any other errors and so we can't special case them - if resp.StatusCode == 404 { + if resp.StatusCode == http.StatusNotFound { return "", fmt.Errorf("got an HTTP 404 response from service discovery; maybe the subdomain %q is incorrect or does not exist?", subdomain) } diff --git a/pkg/logs/logs.go b/pkg/logs/logs.go index 903b8f86..ce7c1ea9 100644 --- a/pkg/logs/logs.go +++ b/pkg/logs/logs.go @@ -77,7 +77,7 @@ func AddFlags(fs *pflag.FlagSet) { features.AddFlag(&tfs) tfs.VisitAll(func(f *pflag.Flag) { if !visibleFlagNames.Has(f.Name) { - tfs.MarkHidden(f.Name) + _ = tfs.MarkHidden(f.Name) } // The original usage string includes details about how diff --git a/pkg/logs/logs_test.go b/pkg/logs/logs_test.go index b474fa33..c4f27a5f 100644 --- a/pkg/logs/logs_test.go +++ b/pkg/logs/logs_test.go @@ -410,7 +410,7 @@ level=INFO msg="this is a happy log that should show as INFO" source=agent for _, line := range strings.Split(given, "\n") { // Simulate the current agent's logs. - logger.Printf(line) + logger.Printf(line) // nolint:staticcheck } assert.Equal(t, expect, gotBuf.String()) diff --git a/pkg/testutil/envtest.go b/pkg/testutil/envtest.go index 62b26d7c..149368f5 100644 --- a/pkg/testutil/envtest.go +++ b/pkg/testutil/envtest.go @@ -203,19 +203,20 @@ func FakeVenafiCloud(t *testing.T) (_ *httptest.Server, _ *x509.Certificate, set apiKey := r.Header.Get("Tppl-Api-Key") if accessToken != "VALID_ACCESS_TOKEN" && apiKey != "VALID_API_KEY" { w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte(`{"error":"expected header 'Authorization: Bearer VALID_ACCESS_TOKEN' or 'tppl-api-key: VALID_API_KEY', but got Authorization=` + r.Header.Get("Authorization") + ` and tppl-api-key=` + r.Header.Get("Tppl-Api-Key"))) + _, _ = w.Write([]byte(`{"error":"expected header 'Authorization: Bearer VALID_ACCESS_TOKEN' or 'tppl-api-key: VALID_API_KEY', but got Authorization=` + r.Header.Get("Authorization") + ` and tppl-api-key=` + r.Header.Get("Tppl-Api-Key"))) return } - if r.URL.Path == "/v1/tlspk/upload/clusterdata/no" { + switch r.URL.Path { + case "/v1/tlspk/upload/clusterdata/no": if r.URL.Query().Get("name") != "test cluster name" { w.WriteHeader(http.StatusBadRequest) _, _ = w.Write([]byte(`{"error":"unexpected name query param in the test server: ` + r.URL.Query().Get("name") + `, expected: 'test cluster name'"}`)) return } _, _ = w.Write([]byte(`{"status":"ok","organization":"756db001-280e-11ee-84fb-991f3177e2d0"}`)) - } else if r.URL.Path == "/v1/useraccounts" { + case "/v1/useraccounts": _, _ = w.Write([]byte(`{"user": {"username": "user","id": "76a126f0-280e-11ee-84fb-991f3177e2d0"}}`)) - } else { + default: w.WriteHeader(http.StatusInternalServerError) _, _ = w.Write([]byte(`{"error":"unexpected path in the test server","path":"` + r.URL.Path + `"}`)) } @@ -236,15 +237,16 @@ func FakeTPP(t testing.TB) (*httptest.Server, *x509.Certificate) { accessToken := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") - if r.URL.Path == "/vedsdk/Identity/Self" { + switch r.URL.Path { + case "/vedsdk/Identity/Self": if accessToken != "VALID_ACCESS_TOKEN" { w.WriteHeader(http.StatusUnauthorized) return } _, _ = w.Write([]byte(`{"Identities":[{"Name":"TEST"}]}`)) - } else if r.URL.Path == "/vedsdk/certificates/checkpolicy" { + case "/vedsdk/certificates/checkpolicy": _, _ = w.Write([]byte(`{"Policy":{"Subject":{"Organization":{"Value": "test-org"}}}}`)) - } else { + default: w.WriteHeader(http.StatusInternalServerError) _, _ = w.Write([]byte(`{"error":"unexpected path in the test server","path":"` + r.URL.Path + `"}`)) }