Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?=
Expand Down
2 changes: 1 addition & 1 deletion cmd/cache-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 1 addition & 5 deletions cmd/kcp-front-proxy/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
2 changes: 1 addition & 1 deletion cmd/kcp/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()...)
Expand Down
6 changes: 3 additions & 3 deletions hack/tools.checksums
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion pkg/admission/apiexport/admission.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/authentication/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 4 additions & 3 deletions pkg/authorization/workspace_content_authorizer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/cache/server/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()...)
Expand Down
2 changes: 1 addition & 1 deletion pkg/features/kcp_features.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
7 changes: 3 additions & 4 deletions pkg/informer/informer.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package informer
import (
"context"
"fmt"
"slices"
"sort"
"strings"
"sync"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion pkg/network/dialer_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
8 changes: 4 additions & 4 deletions pkg/virtual/framework/dynamic/apiserver/openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/virtual/framework/wrappers/rbac/merging.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down Expand Up @@ -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))
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/virtual/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)...)
Expand Down
2 changes: 1 addition & 1 deletion staging/src/github.com/kcp-dev/cli/pkg/bind/plugin/bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)}
Expand Down
12 changes: 6 additions & 6 deletions staging/src/github.com/kcp-dev/sdk/apis/apis/fuzzer/fuzzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down Expand Up @@ -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))
}
Expand All @@ -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),
Expand Down Expand Up @@ -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))
}
Expand All @@ -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),
Expand Down Expand Up @@ -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))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down
14 changes: 8 additions & 6 deletions staging/src/github.com/kcp-dev/sdk/testing/server/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand All @@ -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
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"`
Expand All @@ -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{}
Expand Down
Loading