diff --git a/.golangci.yaml b/.golangci.yaml index 56ae1590e55..d9be8c84573 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -71,6 +71,10 @@ linters: - G404 # Use of weak random number generator (use crypto/rand) - G101 # Potential hardcoded credentials (returns false positives) - G306 # Expect WriteFile permissions to be 0600 or less + # gosec is currently producing a lot of false-positives on taint analysis. + # see https://github.com/securego/gosec/issues/1500 + - G704 + - G705 misspell: ignore-rules: - creater diff --git a/Makefile b/Makefile index f96af026d74..147a936ec91 100644 --- a/Makefile +++ b/Makefile @@ -51,7 +51,7 @@ YAML_PATCH_BIN := yaml-patch YAML_PATCH := $(TOOLS_DIR)/$(YAML_PATCH_BIN)-$(YAML_PATCH_VER) export YAML_PATCH # so hack scripts can use it -GOLANGCI_LINT_VER := 2.6.0 +GOLANGCI_LINT_VER := 2.10.1 GOLANGCI_LINT_BIN := golangci-lint GOLANGCI_LINT := $(TOOLS_GOBIN_DIR)/$(GOLANGCI_LINT_BIN)-$(GOLANGCI_LINT_VER) GOLANGCI_LINT_FLAGS ?= diff --git a/cmd/cache-server/main.go b/cmd/cache-server/main.go index 49c0ab6b42a..654c8ab90fd 100644 --- a/cmd/cache-server/main.go +++ b/cmd/cache-server/main.go @@ -37,7 +37,7 @@ import ( func main() { rootDir := flag.String("root-directory", ".kcp-cache", "Path to the root directory where all files required by this server will be stored") - var cacheServerFlags, remainingFlags []string //nolint:prealloc + var cacheServerFlags, remainingFlags []string for _, arg := range os.Args[1:] { if strings.HasPrefix(arg, "--root-directory") { cacheServerFlags = append(cacheServerFlags, arg) diff --git a/cmd/kcp-front-proxy/options/options.go b/cmd/kcp-front-proxy/options/options.go index 36e8cf73bfb..1dd94ea899c 100644 --- a/cmd/kcp-front-proxy/options/options.go +++ b/cmd/kcp-front-proxy/options/options.go @@ -58,9 +58,5 @@ func (o *Options) Complete() error { } func (o *Options) Validate() []error { - var errs []error - - errs = append(errs, o.Proxy.Validate()...) - - return errs + return o.Proxy.Validate() } diff --git a/cmd/kcp/options/options.go b/cmd/kcp/options/options.go index c9f68f8be03..a99c06bdfab 100644 --- a/cmd/kcp/options/options.go +++ b/cmd/kcp/options/options.go @@ -85,7 +85,7 @@ func (o *Options) Complete(ctx context.Context) (*CompletedOptions, error) { } func (o *CompletedOptions) Validate() []error { - errs := []error{} + errs := []error{} //nolint:prealloc errs = append(errs, o.Generic.Validate()...) errs = append(errs, o.Server.Validate()...) diff --git a/hack/tools.checksums b/hack/tools.checksums index b7e179aaf3c..78813e5c8ee 100644 --- a/hack/tools.checksums +++ b/hack/tools.checksums @@ -1,9 +1,9 @@ controller-gen|GOARCH=amd64;GOOS=linux|21e5f3239666fc0c5e2d23c2a3a83fd655af40a969ede7a118b86832c35a829f controller-gen|GOARCH=arm64;GOOS=darwin|2ca28be7185d9279ed82e3355529b0543938f392cb812add3f25a62196ed7441 controller-gen|GOARCH=arm64;GOOS=linux|a1a1f758435d05933c4b2f8c292f8ab2448e81a02c45f14dbd81c10e87ec4b20 -golangci-lint|GOARCH=amd64;GOOS=linux|f0cdf40b6c161524898d79cad40fa92d7fde7d4a5ecfa07360937160cb61fb2b -golangci-lint|GOARCH=arm64;GOOS=darwin|2a2c09731f02f890aec506c2558c5eb67613aaf268806aa66956ee63858647fb -golangci-lint|GOARCH=arm64;GOOS=linux|be2ea9fc5ecf9a64b7d1291a3b62694edbff3b3d29fe566a3e43ef2e89d4556d +golangci-lint|GOARCH=amd64;GOOS=linux|8a01a08dad47a14824d7d0f14af07c7144105fc079386c9c31fbe85f08f91643 +golangci-lint|GOARCH=arm64;GOOS=darwin|5fd0b6a09353eb0101d3ae81d5e3cf4707b77210c66fb92ae152d7280d959419 +golangci-lint|GOARCH=arm64;GOOS=linux|2ed9cf2ad070dabc7947ba34cdc5142910be830306f063719898bc8fb44a7074 gotestsum|GOARCH=amd64;GOOS=linux|2e505a9368568aa7422e0a90ef77acc8807c0d3272ab81c7a69e3e8688d1cf65 gotestsum|GOARCH=arm64;GOOS=darwin|020be8d14358c7ac4155e296436057cf4b1f1232f8f8f3d71f22a0e7a5504340 gotestsum|GOARCH=arm64;GOOS=linux|2f8517768c2831750cb372e379404a059dbd20f2b1f79bcc235c4cab4540cb10 diff --git a/pkg/admission/apiexport/admission.go b/pkg/admission/apiexport/admission.go index 4a11c91b204..f8c66fcd249 100644 --- a/pkg/admission/apiexport/admission.go +++ b/pkg/admission/apiexport/admission.go @@ -168,7 +168,7 @@ func validateOverhangingResourceSchemas(_ context.Context, _ admission.Attribute // converted to v1alpha2. if _, ok := ae.Annotations[apisv1alpha2.ResourceSchemasAnnotation]; ok { // validate if we can decode overhanging resource schemas. If not, we will fail. - var overhanging []apisv1alpha2.ResourceSchema + var overhanging []apisv1alpha2.ResourceSchema //nolint:prealloc if err := json.Unmarshal([]byte(ae.Annotations[apisv1alpha2.ResourceSchemasAnnotation]), &overhanging); err != nil { return field.Invalid(field.NewPath("metadata").Child("annotations").Key(apisv1alpha2.ResourceSchemasAnnotation), ae.Annotations[apisv1alpha2.ResourceSchemasAnnotation], "failed to decode overhanging resource schemas") } diff --git a/pkg/authentication/index.go b/pkg/authentication/index.go index 4733cf22f62..220f9f9fc60 100644 --- a/pkg/authentication/index.go +++ b/pkg/authentication/index.go @@ -76,7 +76,7 @@ func (c *state) UpsertWorkspaceType(shard string, wst *tenancyv1alpha1.Workspace clusterName := logicalcluster.From(wst) - authenticators := []authenticatorKey{} + authenticators := make([]authenticatorKey, 0, len(wst.Spec.AuthenticationConfigurations)) for _, authConfig := range wst.Spec.AuthenticationConfigurations { authenticators = append(authenticators, authenticatorKey{ cluster: clusterName, diff --git a/pkg/authorization/workspace_content_authorizer_test.go b/pkg/authorization/workspace_content_authorizer_test.go index de6df7216dc..cf73b1408af 100644 --- a/pkg/authorization/workspace_content_authorizer_test.go +++ b/pkg/authorization/workspace_content_authorizer_test.go @@ -329,13 +329,14 @@ func TestWorkspaceContentAuthorizer(t *testing.T) { globalKubeClient := kcpfakeclient.NewSimpleClientset() // TODO(sttts): add some global fixtures local := kcpkubernetesinformers.NewSharedInformerFactory(localKubeClient, controller.NoResyncPeriodFunc()) global := kcpkubernetesinformers.NewSharedInformerFactory(globalKubeClient, controller.NoResyncPeriodFunc()) - var syncs []cache.InformerSynced - for _, inf := range []cache.SharedIndexInformer{ + informers := []cache.SharedIndexInformer{ local.Rbac().V1().ClusterRoles().Informer(), local.Rbac().V1().ClusterRoleBindings().Informer(), global.Rbac().V1().ClusterRoles().Informer(), global.Rbac().V1().ClusterRoleBindings().Informer(), - } { + } + syncs := make([]cache.InformerSynced, 0, len(informers)) + for _, inf := range informers { go inf.Run(ctx.Done()) syncs = append(syncs, inf.HasSynced) } diff --git a/pkg/cache/server/options/options.go b/pkg/cache/server/options/options.go index 4b0618e7adc..5b25e2613ed 100644 --- a/pkg/cache/server/options/options.go +++ b/pkg/cache/server/options/options.go @@ -55,7 +55,7 @@ type CompletedOptions struct { } func (o *CompletedOptions) Validate() []error { - errors := []error{} + errors := []error{} //nolint:prealloc errors = append(errors, o.ServerRunOptions.Validate()...) errors = append(errors, o.Etcd.Validate()...) errors = append(errors, o.SecureServing.Validate()...) diff --git a/pkg/features/kcp_features.go b/pkg/features/kcp_features.go index 991a63b3746..375fae53291 100644 --- a/pkg/features/kcp_features.go +++ b/pkg/features/kcp_features.go @@ -106,7 +106,7 @@ func featureSpecAtEmulationVersion(v featuregate.VersionedSpecs, emulationVersio } func (f *kcpFeatureGate) String() string { - pairs := []string{} + pairs := make([]string, 0, len(defaultVersionedGenericControlPlaneFeatureGates)) emulatedVersion := utilfeature.DefaultMutableFeatureGate.EmulationVersion() for featureName, versionedSpecs := range defaultVersionedGenericControlPlaneFeatureGates { diff --git a/pkg/informer/informer.go b/pkg/informer/informer.go index 088bd750ca7..3f8a909ddd1 100644 --- a/pkg/informer/informer.go +++ b/pkg/informer/informer.go @@ -19,6 +19,7 @@ package informer import ( "context" "fmt" + "slices" "sort" "strings" "sync" @@ -427,9 +428,7 @@ func (d *GenericDiscoveringDynamicSharedInformerFactory[Informer, Lister, Generi handlers := d.handlers.Load().([]GVREventHandler) - newHandlers := make([]GVREventHandler, len(handlers)) - copy(newHandlers, handlers) - + newHandlers := slices.Clone(handlers) newHandlers = append(newHandlers, handler) d.handlers.Store(newHandlers) @@ -616,7 +615,7 @@ func gvrsToDiscoveryData(gvrs map[schema.GroupVersionResource]GVRPartialMetadata } for group, resources := range gvResources { - var versions []metav1.GroupVersionForDiscovery + versions := make([]metav1.GroupVersionForDiscovery, 0, len(resources)) versionedResources := make(map[string][]metav1.APIResource) for version, apiResource := range resources { diff --git a/pkg/network/dialer_linux.go b/pkg/network/dialer_linux.go index 134ab975a8d..5d248dc153b 100644 --- a/pkg/network/dialer_linux.go +++ b/pkg/network/dialer_linux.go @@ -51,7 +51,7 @@ func wrapDialContext(dc DialContext) DialContext { if err != nil { return conn, err } - if err := setDefaultSocketOptions(int(tcpFD.Fd())); err != nil { + if err := setDefaultSocketOptions(int(tcpFD.Fd())); err != nil { //nolint:gosec // Not much we can do here. The syscalls only accept ints. return conn, err } } diff --git a/pkg/reconciler/apis/logicalclustercleanup/logicalclustercleanup_controller_test.go b/pkg/reconciler/apis/logicalclustercleanup/logicalclustercleanup_controller_test.go index bf55870d9f8..34e27a140ff 100644 --- a/pkg/reconciler/apis/logicalclustercleanup/logicalclustercleanup_controller_test.go +++ b/pkg/reconciler/apis/logicalclustercleanup/logicalclustercleanup_controller_test.go @@ -164,8 +164,11 @@ func (b *bindingBuilder) WithName(name string) *bindingBuilder { } func (b *bindingBuilder) WithBoundResources(boundResources ...string) *bindingBuilder { + if len(boundResources)%2 != 0 { + panic("bound resources slice of unexpected length") + } for i := 0; i < len(boundResources); i += 2 { - group, resource := boundResources[i], boundResources[i+1] + group, resource := boundResources[i], boundResources[i+1] //nolint:gosec // Bounds is checked with the modulo above b.Status.BoundResources = append(b.Status.BoundResources, apisv1alpha2.BoundAPIResource{ Group: group, Resource: resource, diff --git a/pkg/server/config.go b/pkg/server/config.go index f1ee1bd0548..c2ce0bfca9b 100644 --- a/pkg/server/config.go +++ b/pkg/server/config.go @@ -566,7 +566,7 @@ func NewConfig(ctx context.Context, opts kcpserveroptions.CompletedOptions) (*Co // DynamicRESTMapper is initialized here, but it starts to be populated only once its controller starts. c.DynamicRESTMapper = dynamicrestmapper.NewDynamicRESTMapper() - admissionPluginInitializers := []admission.PluginInitializer{ + admissionPluginInitializers := []admission.PluginInitializer{ //nolint:prealloc kcpadmissioninitializers.NewKcpInformersInitializer(c.KcpSharedInformerFactory, c.CacheKcpSharedInformerFactory), kcpadmissioninitializers.NewKubeInformersInitializer(c.KubeSharedInformerFactory, c.CacheKubeSharedInformerFactory), kcpadmissioninitializers.NewKubeClusterClientInitializer(c.KubeClusterClient), diff --git a/pkg/virtual/framework/dynamic/apiserver/openapi.go b/pkg/virtual/framework/dynamic/apiserver/openapi.go index 44831d1e691..d0c4e525552 100644 --- a/pkg/virtual/framework/dynamic/apiserver/openapi.go +++ b/pkg/virtual/framework/dynamic/apiserver/openapi.go @@ -355,7 +355,7 @@ func addSpecs(service *handler3.OpenAPIService, routeSpecs map[string][]*spec3.O } func apiConfigurationKey(apiDefs apidefinition.APIDefinitionSet) (string, error) { - var buf bytes.Buffer + buf := &bytes.Buffer{} keys := make([]schema.GroupVersionResource, 0, len(apiDefs)) for k := range apiDefs { @@ -375,12 +375,12 @@ func apiConfigurationKey(apiDefs apidefinition.APIDefinitionSet) (string, error) } if !firstAPIDef { - buf.WriteRune(';') + buf.WriteByte(';') } buf.WriteString(apiDefSchema.Name) - buf.WriteRune(':') - buf.WriteString(fmt.Sprintf("%X", sha512.Sum512(bs))) + buf.WriteByte(':') + fmt.Fprintf(buf, "%X", sha512.Sum512(bs)) firstAPIDef = false } diff --git a/pkg/virtual/framework/wrappers/rbac/merging.go b/pkg/virtual/framework/wrappers/rbac/merging.go index 894a6fe1f38..4449ac74f05 100644 --- a/pkg/virtual/framework/wrappers/rbac/merging.go +++ b/pkg/virtual/framework/wrappers/rbac/merging.go @@ -130,7 +130,7 @@ func (l *mergedRoleLister) List(selector labels.Selector) (ret []*rbacv1.Role, e } func (l *mergedRoleLister) Roles(namespace string) rbaclisters.RoleNamespaceLister { - aggregatedListers := make([]rbaclisters.RoleNamespaceLister, 0) + aggregatedListers := make([]rbaclisters.RoleNamespaceLister, 0, len(l.listers)) for _, inf := range l.listers { aggregatedListers = append(aggregatedListers, inf.Roles(namespace)) } @@ -207,7 +207,7 @@ func (l *mergedRoleBindingLister) Get(name string) (*rbacv1.RoleBinding, error) } func (l *mergedRoleBindingLister) RoleBindings(namespace string) rbaclisters.RoleBindingNamespaceLister { - aggregatedListers := make([]rbaclisters.RoleBindingNamespaceLister, 0) + aggregatedListers := make([]rbaclisters.RoleBindingNamespaceLister, 0, len(l.listers)) for _, inf := range l.listers { aggregatedListers = append(aggregatedListers, inf.RoleBindings(namespace)) } diff --git a/pkg/virtual/options/options.go b/pkg/virtual/options/options.go index 90e8b404239..a6c9c66ce9b 100644 --- a/pkg/virtual/options/options.go +++ b/pkg/virtual/options/options.go @@ -50,7 +50,7 @@ func NewOptions() *Options { } func (o *Options) Validate() []error { - var errs []error + var errs []error //nolint:prealloc errs = append(errs, o.APIExport.Validate(virtualWorkspacesFlagPrefix)...) errs = append(errs, o.InitializingWorkspaces.Validate(virtualWorkspacesFlagPrefix)...) diff --git a/staging/src/github.com/kcp-dev/cli/pkg/bind/plugin/bind.go b/staging/src/github.com/kcp-dev/cli/pkg/bind/plugin/bind.go index 6fe6c72f651..249eea74972 100644 --- a/staging/src/github.com/kcp-dev/cli/pkg/bind/plugin/bind.go +++ b/staging/src/github.com/kcp-dev/cli/pkg/bind/plugin/bind.go @@ -243,7 +243,7 @@ func (b *BindOptions) newAPIBinding(preferredAPIBindingVersion string) (apishelp return nil, fmt.Errorf("%s is not supported by this plugin", preferredAPIBindingVersion) } - claims := []apisv1alpha2.AcceptablePermissionClaim{} + claims := make([]apisv1alpha2.AcceptablePermissionClaim, 0, len(b.acceptedPermissionClaims)+len(b.rejectedPermissionClaims)) claims = append(claims, b.acceptedPermissionClaims...) claims = append(claims, b.rejectedPermissionClaims...) diff --git a/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-client-gen/generators/client_generator.go b/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-client-gen/generators/client_generator.go index a831564c296..70ea24145f6 100644 --- a/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-client-gen/generators/client_generator.go +++ b/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-client-gen/generators/client_generator.go @@ -144,7 +144,7 @@ func targetForGroup(gv clientgentypes.GroupVersion, typeList []*types.Type, clie // GeneratorsFunc returns a list of generators. Each generator makes a // single file. GeneratorsFunc: func(c *generator.Context) (generators []generator.Generator) { - generators = []generator.Generator{ + generators = []generator.Generator{ //nolint:prealloc // Always generate a "doc.go" file. generator.GoGenerator{OutputFilename: "doc.go"}, } diff --git a/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-client-gen/generators/fake/fake_client_generator.go b/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-client-gen/generators/fake/fake_client_generator.go index 3ff7920486a..d9744c3adb1 100644 --- a/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-client-gen/generators/fake/fake_client_generator.go +++ b/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-client-gen/generators/fake/fake_client_generator.go @@ -48,7 +48,7 @@ func TargetForGroup(gv clientgentypes.GroupVersion, typeList []*types.Type, clie // GeneratorsFunc returns a list of generators. Each generator makes a // single file. GeneratorsFunc: func(c *generator.Context) (generators []generator.Generator) { - generators = []generator.Generator{ + generators = []generator.Generator{ //nolint:prealloc // Always generate a "doc.go" file. generator.GoGenerator{OutputFilename: "doc.go"}, } diff --git a/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-informer-gen/generators/generic.go b/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-informer-gen/generators/generic.go index b60c7b0fa85..a200c2466a7 100644 --- a/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-informer-gen/generators/generic.go +++ b/staging/src/github.com/kcp-dev/code-generator/cmd/cluster-informer-gen/generators/generic.go @@ -90,7 +90,7 @@ func (v *version) Compare(other *version) int { func (g *genericGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error { sw := generator.NewSnippetWriter(w, c, "{{", "}}") - groups := []group{} + groups := make([]group, 0, len(g.groupVersions)) schemeGVs := make(map[*version]*types.Type) orderer := namer.Orderer{Namer: namer.NewPrivateNamer(0)} diff --git a/staging/src/github.com/kcp-dev/sdk/apis/apis/fuzzer/fuzzer.go b/staging/src/github.com/kcp-dev/sdk/apis/apis/fuzzer/fuzzer.go index 07044ed0f31..b7bdcf0edf9 100644 --- a/staging/src/github.com/kcp-dev/sdk/apis/apis/fuzzer/fuzzer.go +++ b/staging/src/github.com/kcp-dev/sdk/apis/apis/fuzzer/fuzzer.go @@ -76,8 +76,8 @@ func Funcs(codecs runtimeserializer.CodecFactory) []any { group := nonEmptyString(c.String) resource := nonEmptyString(c.String) identityHash := nonEmptyString(c.String) - verbs := []string{} numVerbs := c.Intn(5) + 1 // the lower bound is 0, but 0 verbs is not a valid combination + verbs := make([]string, 0, numVerbs) for range numVerbs { verbs = append(verbs, nonEmptyString(c.String)) } @@ -190,8 +190,8 @@ func Funcs(codecs runtimeserializer.CodecFactory) []any { group := nonEmptyString(c.String) resource := nonEmptyString(c.String) identityHash := nonEmptyString(c.String) - verbs := []string{} numVerbs := c.Intn(5) + 1 // the lower bound is 0, but 0 verbs is not a valid combination + verbs := make([]string, 0, numVerbs) for range numVerbs { verbs = append(verbs, nonEmptyString(c.String)) } @@ -210,7 +210,7 @@ func Funcs(codecs runtimeserializer.CodecFactory) []any { selector.MatchLabels = labels default: numExpressions := c.Intn(5) + 1 - expressions := make([]metav1.LabelSelectorRequirement, numExpressions) + expressions := make([]metav1.LabelSelectorRequirement, 0, numExpressions) for range numExpressions { expressions = append(expressions, metav1.LabelSelectorRequirement{ Key: nonEmptyString(c.String), @@ -246,8 +246,8 @@ func Funcs(codecs runtimeserializer.CodecFactory) []any { group := nonEmptyString(c.String) resource := nonEmptyString(c.String) identityHash := nonEmptyString(c.String) - verbs := []string{} numVerbs := c.Intn(5) + 1 // the lower bound is 0, but 0 verbs is not a valid combination + verbs := make([]string, 0, numVerbs) for range numVerbs { verbs = append(verbs, nonEmptyString(c.String)) } @@ -266,7 +266,7 @@ func Funcs(codecs runtimeserializer.CodecFactory) []any { selector.MatchLabels = labels default: numExpressions := c.Intn(5) + 1 - expressions := make([]metav1.LabelSelectorRequirement, numExpressions) + expressions := make([]metav1.LabelSelectorRequirement, 0, numExpressions) for range numExpressions { expressions = append(expressions, metav1.LabelSelectorRequirement{ Key: nonEmptyString(c.String), @@ -296,8 +296,8 @@ func Funcs(codecs runtimeserializer.CodecFactory) []any { group := nonEmptyString(c.String) resource := nonEmptyString(c.String) identityHash := nonEmptyString(c.String) - verbs := []string{} numVerbs := c.Intn(5) + 1 // the lower bound is 0, but 0 verbs is not a valid combination + verbs := make([]string, 0, numVerbs) for range numVerbs { verbs = append(verbs, nonEmptyString(c.String)) } diff --git a/staging/src/github.com/kcp-dev/sdk/apis/apis/v1alpha1/crd_to_apiresourceschema.go b/staging/src/github.com/kcp-dev/sdk/apis/apis/v1alpha1/crd_to_apiresourceschema.go index e2fcec1917f..7760ea8d008 100644 --- a/staging/src/github.com/kcp-dev/sdk/apis/apis/v1alpha1/crd_to_apiresourceschema.go +++ b/staging/src/github.com/kcp-dev/sdk/apis/apis/v1alpha1/crd_to_apiresourceschema.go @@ -33,7 +33,7 @@ func CRDToAPIResourceSchema(crd *apiextensionsv1.CustomResourceDefinition, prefi name := prefix + "." + crd.Name if msgs := validation.IsDNS1123Subdomain(name); len(msgs) > 0 { - var errs []error + errs := make([]error, 0, len(msgs)) for _, msg := range msgs { errs = append(errs, field.Invalid(field.NewPath("metadata", "name"), name, msg)) diff --git a/staging/src/github.com/kcp-dev/sdk/apis/apis/v1alpha2/validation_test.go b/staging/src/github.com/kcp-dev/sdk/apis/apis/v1alpha2/validation_test.go index af2eecb4e9a..b8f6cd5eb82 100644 --- a/staging/src/github.com/kcp-dev/sdk/apis/apis/v1alpha2/validation_test.go +++ b/staging/src/github.com/kcp-dev/sdk/apis/apis/v1alpha2/validation_test.go @@ -168,7 +168,7 @@ func TestValidateAPIBindingPermissionClaims(t *testing.T) { got := ValidateAPIBindingPermissionClaims(tc.permissionClaims, field.NewPath("spec", "permissionClaims")) // Convert FieldErrors into a string slice - errs := []string{} + errs := make([]string, 0, len(got)) for _, err := range got { errs = append(errs, err.Error()) } diff --git a/staging/src/github.com/kcp-dev/sdk/testing/server/metrics.go b/staging/src/github.com/kcp-dev/sdk/testing/server/metrics.go index a4fb1b7abf6..176457f4da3 100644 --- a/staging/src/github.com/kcp-dev/sdk/testing/server/metrics.go +++ b/staging/src/github.com/kcp-dev/sdk/testing/server/metrics.go @@ -113,7 +113,7 @@ func ScrapeMetrics(ctx context.Context, cfg *rest.Config, promUrl, promCfgDir, j type scrapeConfig struct { JobName string `yaml:"job_name,omitempty"` ScrapeInterval string `yaml:"scrape_interval,omitempty"` - BearerToken string `yaml:"bearer_token,omitempty"` + BearerToken string `yaml:"bearer_token,omitempty"` //nolint:gosec // Field has to be exported for the decoder. TlsConfig tlsConfig `yaml:"tls_config,omitempty"` Scheme string `yaml:"scheme,omitempty"` StaticConfigs []staticConfigs `yaml:"static_configs,omitempty"` @@ -128,8 +128,9 @@ func ScrapeMetrics(ctx context.Context, cfg *rest.Config, promUrl, promCfgDir, j return err } defer f.Close() + fd := int(f.Fd()) //nolint:gosec // the conversion uintpr -> int is fine here // lock config file exclusively, blocks all other producers until unlocked or process (test) exits - err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX) + err = syscall.Flock(fd, syscall.LOCK_EX) if err != nil { return err } @@ -165,7 +166,7 @@ func ScrapeMetrics(ctx context.Context, cfg *rest.Config, promUrl, promCfgDir, j if err != nil { return err } - return syscall.Flock(int(f.Fd()), syscall.LOCK_UN) + return syscall.Flock(fd, syscall.LOCK_UN) }() if err != nil { return err @@ -196,7 +197,7 @@ func CleanupScrapeMetrics(ctx context.Context, promUrl, promCfgDir, jobNamePrefi type scrapeConfig struct { JobName string `yaml:"job_name,omitempty"` ScrapeInterval string `yaml:"scrape_interval,omitempty"` - BearerToken string `yaml:"bearer_token,omitempty"` + BearerToken string `yaml:"bearer_token,omitempty"` //nolint:gosec // Field has to be exported for the decoder. TlsConfig tlsConfig `yaml:"tls_config,omitempty"` Scheme string `yaml:"scheme,omitempty"` StaticConfigs []staticConfigs `yaml:"static_configs,omitempty"` @@ -217,12 +218,13 @@ func CleanupScrapeMetrics(ctx context.Context, promUrl, promCfgDir, jobNamePrefi defer f.Close() // lock config file exclusively - err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX) + fd := int(f.Fd()) //nolint:gosec // the conversion uintpr -> int is fine here + err = syscall.Flock(fd, syscall.LOCK_EX) if err != nil { return err } defer func() { - _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN) + _ = syscall.Flock(fd, syscall.LOCK_UN) }() promCfg := config{} diff --git a/test/e2e/apibinding/apibinding_test.go b/test/e2e/apibinding/apibinding_test.go index bd0bfab581c..c88d3d7bbb7 100644 --- a/test/e2e/apibinding/apibinding_test.go +++ b/test/e2e/apibinding/apibinding_test.go @@ -377,7 +377,7 @@ func TestAPIBinding(t *testing.T) { } verifyVirtualWorkspaceURLs := func(serviceProviderClusterName logicalcluster.Name) { - var expectedURLs []string + expectedURLs := make([]string, 0, len(shardVirtualWorkspaceURLs)) for _, urlString := range sets.List[string](shardVirtualWorkspaceURLs) { u, err := url.Parse(urlString) require.NoError(t, err, "error parsing %q", urlString) @@ -392,7 +392,7 @@ func TestAPIBinding(t *testing.T) { t.Logf("Unexpected error getting APIExportEndpointSlice %s|%s: %v", serviceProviderClusterName.Path(), exportName, err) } - var actualURLs []string + actualURLs := make([]string, 0, len(apiExportEndpointSlice.Status.APIExportEndpoints)) for _, u := range apiExportEndpointSlice.Status.APIExportEndpoints { actualURLs = append(actualURLs, u.URL) } diff --git a/test/e2e/authentication/workspace_test.go b/test/e2e/authentication/workspace_test.go index f76937a71c6..47e139e38d2 100644 --- a/test/e2e/authentication/workspace_test.go +++ b/test/e2e/authentication/workspace_test.go @@ -289,7 +289,7 @@ func TestUserScope(t *testing.T) { userName = "peter" userEmail = "peter@example.com" userGroups = []string{"developers", "admins"} - expectedGroups = []string{"system:authenticated"} + expectedGroups = []string{"system:authenticated"} //nolint:prealloc expectedExtras = map[string]authenticationv1.ExtraValue{ // authentication.kcp.io/scopes from the extra mapping has // been scrubbed and only the expected cluster: is set @@ -591,7 +591,7 @@ func TestWorkspaceOIDCTokenReview(t *testing.T) { userName = "peter" userEmail = "peter@example.com" userGroups = []string{"developers", "admins"} - expectedGroups = []string{"system:authenticated"} + expectedGroups = []string{"system:authenticated"} //nolint:prealloc ) for _, group := range userGroups { diff --git a/test/e2e/fixtures/authfixtures/authfixtures.go b/test/e2e/fixtures/authfixtures/authfixtures.go index eb59ed2957b..f06bda8b10c 100644 --- a/test/e2e/fixtures/authfixtures/authfixtures.go +++ b/test/e2e/fixtures/authfixtures/authfixtures.go @@ -32,7 +32,7 @@ import ( ) func CreateWorkspaceType(t *testing.T, ctx context.Context, client kcpclientset.ClusterInterface, workspace logicalcluster.Path, name string, authConfigNames ...string) string { - configs := []tenancyv1alpha1.AuthenticationConfigurationReference{} + configs := make([]tenancyv1alpha1.AuthenticationConfigurationReference, 0, len(authConfigNames)) for _, name := range authConfigNames { configs = append(configs, tenancyv1alpha1.AuthenticationConfigurationReference{ Name: name, diff --git a/test/e2e/framework/kcp.go b/test/e2e/framework/kcp.go index 7dd5a9c3e10..6ac3516bd1e 100644 --- a/test/e2e/framework/kcp.go +++ b/test/e2e/framework/kcp.go @@ -35,9 +35,8 @@ func init() { DefaultTokenAuthFile = filepath.Join(repo, "test", "e2e", "framework", "auth-tokens.csv") - var args []string - args = append(args, "--token-auth-file", DefaultTokenAuthFile) //nolint:gocritic // no. - args = append(args, "--feature-gates=WorkspaceMounts=true,CacheAPIs=true,WorkspaceAuthentication=true") - - kcptesting.InitSharedKcpServer(kcptestingserver.WithCustomArguments(args...)) + kcptesting.InitSharedKcpServer(kcptestingserver.WithCustomArguments( + "--token-auth-file", DefaultTokenAuthFile, + "--feature-gates=WorkspaceMounts=true,CacheAPIs=true,WorkspaceAuthentication=true", + )) } diff --git a/test/e2e/homeworkspaces/home_workspaces_test.go b/test/e2e/homeworkspaces/home_workspaces_test.go index 007f45c52fb..ab580a796e1 100644 --- a/test/e2e/homeworkspaces/home_workspaces_test.go +++ b/test/e2e/homeworkspaces/home_workspaces_test.go @@ -39,10 +39,10 @@ func TestUserHomeWorkspaces(t *testing.T) { t.Parallel() framework.Suite(t, "control-plane") - var serverArgs []string - serverArgs = append(serverArgs, "--token-auth-file", framework.DefaultTokenAuthFile) //nolint:gocritic // no. - serverArgs = append(serverArgs, "--home-workspaces-home-creator-groups=team-1") - server := kcptesting.PrivateKcpServer(t, kcptestingserver.WithCustomArguments(serverArgs...)) + server := kcptesting.PrivateKcpServer(t, kcptestingserver.WithCustomArguments( + "--token-auth-file", framework.DefaultTokenAuthFile, + "--home-workspaces-home-creator-groups=team-1", + )) ctx, cancelFunc := context.WithCancel(context.Background()) t.Cleanup(cancelFunc) diff --git a/test/e2e/proxy/proxy_test.go b/test/e2e/proxy/proxy_test.go index 85ad6ad1949..bdd66bc9c02 100644 --- a/test/e2e/proxy/proxy_test.go +++ b/test/e2e/proxy/proxy_test.go @@ -121,7 +121,7 @@ func TestMappingWithClusterContext(t *testing.T) { expectedScope = "cluster:" + teamCluster expectedClusterName = teamCluster expectedUsername = "oidc:" + email - expectedGroups = []string{"system:authenticated"} + expectedGroups = []string{"system:authenticated"} //nolint:prealloc ) for _, group := range groups { diff --git a/test/e2e/virtual/apiexport/binding_test.go b/test/e2e/virtual/apiexport/binding_test.go index da40325155f..17fd26690a2 100644 --- a/test/e2e/virtual/apiexport/binding_test.go +++ b/test/e2e/virtual/apiexport/binding_test.go @@ -1059,7 +1059,7 @@ func testSecretMapWithLabels(num int, labels map[string]string) *corev1.Secret { } func permissionClaimsToAcceptable(permissionClaims []apisv1alpha2.PermissionClaim, modifiers ...func([]apisv1alpha2.AcceptablePermissionClaim)) []apisv1alpha2.AcceptablePermissionClaim { - acceptablePermissionClaims := []apisv1alpha2.AcceptablePermissionClaim{} + acceptablePermissionClaims := make([]apisv1alpha2.AcceptablePermissionClaim, 0, len(permissionClaims)) for _, pc := range permissionClaims { acceptablePermissionClaims = append(acceptablePermissionClaims, apisv1alpha2.AcceptablePermissionClaim{ ScopedPermissionClaim: apisv1alpha2.ScopedPermissionClaim{ diff --git a/test/e2e/virtualresources/cachedresources/vr_cachedresources_test.go b/test/e2e/virtualresources/cachedresources/vr_cachedresources_test.go index ebc27045e70..4e1e2490b79 100644 --- a/test/e2e/virtualresources/cachedresources/vr_cachedresources_test.go +++ b/test/e2e/virtualresources/cachedresources/vr_cachedresources_test.go @@ -293,7 +293,7 @@ func TestCachedResources(t *testing.T) { resourceCounters := map[string]*int32{ "sheriffs": ptr.To[int32](0), } - var watchStopFuncs []func() + watchStopFuncs := make([]func(), 0, len(apiExportVWClientConfigs)*len(resourceCounters)) defer func() { for _, stop := range watchStopFuncs { stop()