From 3013d14a4163403d13531604fe09824101e4c78f Mon Sep 17 00:00:00 2001 From: Carlo Teubner Date: Thu, 19 Dec 2024 23:08:54 +0000 Subject: [PATCH] golangci-lint: add intrange & update code Add the 'intrange' linter, which enforces usage of the hip new-ish "range over int" feature in Go. Signed-off-by: Carlo Teubner --- .golangci.yml | 1 + cmd/spire-server/cli/entry/show_test.go | 2 +- pkg/agent/attestor/workload/workload.go | 2 +- pkg/agent/client/client_test.go | 4 ++-- pkg/agent/client/nodeconn_test.go | 4 ++-- pkg/agent/manager/cache/lru_cache_test.go | 12 +++++----- pkg/agent/manager/manager_test.go | 2 +- pkg/common/catalog/catalog_test.go | 2 +- .../internal/structpretty/structpretty.go | 2 +- .../diskcertmanager/cert_manager_test.go | 8 +++---- pkg/common/plugin/sshpop/handshake_test.go | 2 +- pkg/common/protoutil/masks.go | 2 +- pkg/common/selector/set_utils.go | 4 ++-- .../server/datastore/wrapper_test.go | 4 ++-- pkg/server/api/agent/v1/service_test.go | 2 +- pkg/server/api/bundle/v1/service_test.go | 2 +- pkg/server/api/entry/v1/service_test.go | 8 +++---- pkg/server/authorizedentries/cache_test.go | 8 +++---- .../bundle/pubmanager/pubmanager_test.go | 2 +- pkg/server/ca/manager/journal_test.go | 4 ++-- pkg/server/ca/manager/manager.go | 2 +- .../cache/entrycache/fullcache_ds_test.go | 10 ++++----- pkg/server/cache/entrycache/fullcache_test.go | 22 +++++++++---------- pkg/server/datastore/sqlstore/sqlstore.go | 2 +- .../datastore/sqlstore/sqlstore_test.go | 16 +++++++------- pkg/server/endpoints/endpoints_test.go | 4 ++-- pkg/server/endpoints/entryfetcher_test.go | 2 +- .../credentialcomposer/uniqueid/plugin.go | 2 +- .../plugin/keymanager/gcpkms/client_fake.go | 2 +- .../certmanager/certmanager.go | 2 +- test/spiretest/assertions.go | 2 +- test/util/race.go | 4 ++-- 32 files changed, 74 insertions(+), 73 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 9306540caf..56e651d79c 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -21,6 +21,7 @@ linters: - nakedret - unconvert - unparam + - intrange - whitespace - gocritic - nolintlint diff --git a/cmd/spire-server/cli/entry/show_test.go b/cmd/spire-server/cli/entry/show_test.go index d2fee9b325..84cd90854d 100644 --- a/cmd/spire-server/cli/entry/show_test.go +++ b/cmd/spire-server/cli/entry/show_test.go @@ -445,7 +445,7 @@ func getEntries(count int) []*types.Entry { } e := []*types.Entry{} - for i := 0; i < count; i++ { + for i := range count { e = append(e, entries[i]) } diff --git a/pkg/agent/attestor/workload/workload.go b/pkg/agent/attestor/workload/workload.go index 3525c47f50..1ff65b42c5 100644 --- a/pkg/agent/attestor/workload/workload.go +++ b/pkg/agent/attestor/workload/workload.go @@ -66,7 +66,7 @@ func (wla *attestor) Attest(ctx context.Context, pid int) ([]*common.Selector, e // Collect the results selectors := []*common.Selector{} - for i := 0; i < len(plugins); i++ { + for range plugins { select { case s := <-sChan: selectors = append(selectors, s...) diff --git a/pkg/agent/client/client_test.go b/pkg/agent/client/client_test.go index 32ddae38e0..81aab8154b 100644 --- a/pkg/agent/client/client_test.go +++ b/pkg/agent/client/client_test.go @@ -660,7 +660,7 @@ func TestFetchReleaseWaitsForFetchUpdatesToFinish(t *testing.T) { func TestNewNodeClientRelease(t *testing.T) { client, _ := createClient(t) - for i := 0; i < 3; i++ { + for range 3 { // Create agent client and release _, r, err := client.newAgentClient(ctx) require.NoError(t, err) @@ -697,7 +697,7 @@ func TestNewNodeClientRelease(t *testing.T) { func TestNewNodeInternalClientRelease(t *testing.T) { client, _ := createClient(t) - for i := 0; i < 3; i++ { + for range 3 { // Create agent client _, conn, err := client.newAgentClient(ctx) require.NoError(t, err) diff --git a/pkg/agent/client/nodeconn_test.go b/pkg/agent/client/nodeconn_test.go index 892092588d..4b14fa1053 100644 --- a/pkg/agent/client/nodeconn_test.go +++ b/pkg/agent/client/nodeconn_test.go @@ -64,7 +64,7 @@ func TestNewNodeMany(t *testing.T) { firstRelease := false go func() { - for i := 0; i < 100; i++ { + for range 100 { nodeConn.AddRef() if !firstRelease { nodeConn.Release() @@ -75,7 +75,7 @@ func TestNewNodeMany(t *testing.T) { }() go func() { - for i := 0; i < 100; i++ { + for range 100 { nodeConn.Release() } close(waitForReleases) diff --git a/pkg/agent/manager/cache/lru_cache_test.go b/pkg/agent/manager/cache/lru_cache_test.go index 70b953446f..c251dd415c 100644 --- a/pkg/agent/manager/cache/lru_cache_test.go +++ b/pkg/agent/manager/cache/lru_cache_test.go @@ -1251,7 +1251,7 @@ func BenchmarkLRUCacheGlobalNotification(b *testing.B) { Bundles: bundlesV1, RegistrationEntries: make(map[string]*common.RegistrationEntry, numEntries), } - for i := 0; i < numEntries; i++ { + for i := range numEntries { entryID := fmt.Sprintf("00000000-0000-0000-0000-%012d", i) updateEntries.RegistrationEntries[entryID] = &common.RegistrationEntry{ EntryId: entryID, @@ -1262,7 +1262,7 @@ func BenchmarkLRUCacheGlobalNotification(b *testing.B) { } cache.UpdateEntries(updateEntries, nil) - for i := 0; i < numWorkloads; i++ { + for i := range numWorkloads { selectors := distinctSelectors(i, selectorsPerWorkload) cache.NewSubscriber(selectors) } @@ -1271,7 +1271,7 @@ func BenchmarkLRUCacheGlobalNotification(b *testing.B) { b.ResetTimer() b.ReportAllocs() - for i := 0; i < b.N; i++ { + for i := range b.N { if i%2 == 0 { updateEntries.Bundles = bundlesV2 } else { @@ -1299,7 +1299,7 @@ func createUpdateEntries(numEntries int, bundles map[spiffeid.TrustDomain]*spiff RegistrationEntries: make(map[string]*common.RegistrationEntry, numEntries), } - for i := 0; i < numEntries; i++ { + for i := range numEntries { entryID := fmt.Sprintf("00000000-0000-0000-0000-%012d", i) updateEntries.RegistrationEntries[entryID] = &common.RegistrationEntry{ EntryId: entryID, @@ -1335,7 +1335,7 @@ func subscribeToWorkloadUpdates(t *testing.T, cache *LRUCache, selectors []*comm func distinctSelectors(id, n int) []*common.Selector { out := make([]*common.Selector, 0, n) - for i := 0; i < n; i++ { + for i := range n { out = append(out, &common.Selector{ Type: "test", Value: fmt.Sprintf("id:%d:n:%d", id, i), @@ -1436,7 +1436,7 @@ func makeFederatesWith(bundles ...*Bundle) []string { func createTestEntries(count int) []*common.RegistrationEntry { var entries []*common.RegistrationEntry - for i := 0; i < count; i++ { + for i := range count { entry := makeRegistrationEntry(fmt.Sprintf("e%d", i), fmt.Sprintf("s%d", i)) entries = append(entries, entry) } diff --git a/pkg/agent/manager/manager_test.go b/pkg/agent/manager/manager_test.go index f566155534..8a561dae1e 100644 --- a/pkg/agent/manager/manager_test.go +++ b/pkg/agent/manager/manager_test.go @@ -455,7 +455,7 @@ func TestSVIDRotation(t *testing.T) { defer closer() // Loop, we should not detect SVID rotations - for i := 0; i < 10; i++ { + for range 10 { s := m.GetCurrentCredentials() svid = s.SVID require.True(t, svidsEqual(svid, baseSVID)) diff --git a/pkg/common/catalog/catalog_test.go b/pkg/common/catalog/catalog_test.go index badc35061e..c336cfa33c 100644 --- a/pkg/common/catalog/catalog_test.go +++ b/pkg/common/catalog/catalog_test.go @@ -317,7 +317,7 @@ func testPlugin(t *testing.T, pluginPath string) { t.Run("no maximum", func(t *testing.T) { testLoad(t, pluginPath, loadTest{ mutateConfig: func(config *catalog.Config) { - for i := 0; i < 10; i++ { + for range 10 { config.PluginConfigs = append(config.PluginConfigs, config.PluginConfigs[0]) } }, diff --git a/pkg/common/cliprinter/internal/structpretty/structpretty.go b/pkg/common/cliprinter/internal/structpretty/structpretty.go index 99bb37a883..a9e15e038f 100644 --- a/pkg/common/cliprinter/internal/structpretty/structpretty.go +++ b/pkg/common/cliprinter/internal/structpretty/structpretty.go @@ -55,7 +55,7 @@ func printStruct(msg any, stdout, stderr io.Writer) error { } builder := new(strings.Builder) - for i := 0; i < msgType.NumField(); i++ { + for i := range msgType.NumField() { fieldType := msgType.Field(i) fieldValue := msgValue.Field(i) diff --git a/pkg/common/diskcertmanager/cert_manager_test.go b/pkg/common/diskcertmanager/cert_manager_test.go index 71d76cbef4..cb6b54e8f1 100644 --- a/pkg/common/diskcertmanager/cert_manager_test.go +++ b/pkg/common/diskcertmanager/cert_manager_test.go @@ -221,7 +221,7 @@ func TestTLSConfig(t *testing.T) { t.Run("update cert file with an invalid cert start error log loop", func(t *testing.T) { writeFile(t, certFilePath, []byte("invalid-cert")) - for i := 0; i < 5; i++ { + for range 5 { clk.Add(10 * time.Millisecond) } @@ -254,7 +254,7 @@ func TestTLSConfig(t *testing.T) { writeFile(t, keyFilePath, []byte("invalid-key")) - for i := 0; i < 5; i++ { + for range 5 { clk.Add(10 * time.Millisecond) } @@ -302,7 +302,7 @@ func TestTLSConfig(t *testing.T) { t.Run("delete cert files start error log loop", func(t *testing.T) { removeFile(t, keyFilePath) - for i := 0; i < 5; i++ { + for range 5 { clk.Add(10 * time.Millisecond) } @@ -319,7 +319,7 @@ func TestTLSConfig(t *testing.T) { removeFile(t, certFilePath) - for i := 0; i < 5; i++ { + for range 5 { clk.Add(10 * time.Millisecond) } diff --git a/pkg/common/plugin/sshpop/handshake_test.go b/pkg/common/plugin/sshpop/handshake_test.go index 1999eb1bd9..a95f9f6382 100644 --- a/pkg/common/plugin/sshpop/handshake_test.go +++ b/pkg/common/plugin/sshpop/handshake_test.go @@ -238,7 +238,7 @@ func marshalAttestationData(t *testing.T, cert []byte) []byte { func TestIssueChallengeUniqueness(t *testing.T) { _, s := newTestHandshake(t) challenges := make(map[string]struct{}) - for i := 0; i < 10000; i++ { + for range 10000 { s.state = stateAttestationDataVerified challenge, err := s.IssueChallenge() require.NoError(t, err) diff --git a/pkg/common/protoutil/masks.go b/pkg/common/protoutil/masks.go index 91ce3455ff..0f684ed31b 100644 --- a/pkg/common/protoutil/masks.go +++ b/pkg/common/protoutil/masks.go @@ -22,7 +22,7 @@ var ( func MakeAllTrueMask(m proto.Message) proto.Message { v := reflect.ValueOf(proto.Clone(m)).Elem() t := v.Type() - for i := 0; i < v.NumField(); i++ { + for i := range v.NumField() { ft := t.Field(i) fv := v.Field(i) // Skip the protobuf internal fields or those that aren't bools diff --git a/pkg/common/selector/set_utils.go b/pkg/common/selector/set_utils.go index e7d4b23c94..4a64f944d2 100644 --- a/pkg/common/selector/set_utils.go +++ b/pkg/common/selector/set_utils.go @@ -74,9 +74,9 @@ func powerSet(s *set, c chan Set) { // Walk through the binary, and append // "enabled" elements to the working set - for position := 0; position < len(binary); position++ { + for position := range binary { // Read the binary right to left - negPosition := (len(binary) - position - 1) + negPosition := len(binary) - position - 1 if binary[negPosition] == "1" { set.Add(sarr[position]) } diff --git a/pkg/common/telemetry/server/datastore/wrapper_test.go b/pkg/common/telemetry/server/datastore/wrapper_test.go index 79c1a87f8e..222904d05e 100644 --- a/pkg/common/telemetry/server/datastore/wrapper_test.go +++ b/pkg/common/telemetry/server/datastore/wrapper_test.go @@ -29,7 +29,7 @@ func TestWithMetrics(t *testing.T) { methodNames := make(map[string]struct{}) wv := reflect.ValueOf(w) wt := reflect.TypeOf(w) - for i := 0; i < wt.NumMethod(); i++ { + for i := range wt.NumMethod() { methodNames[wt.Method(i).Name] = struct{}{} } @@ -270,7 +270,7 @@ func TestWithMetrics(t *testing.T) { } out := methodValue.Call(args) require.Len(t, out, numOut) - for i := 0; i < numOut-1; i++ { + for i := range numOut - 1 { mv := methodValue.Type().Out(i) switch v := reflect.ValueOf(mv); v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: diff --git a/pkg/server/api/agent/v1/service_test.go b/pkg/server/api/agent/v1/service_test.go index b834ff7397..63c9af57e1 100644 --- a/pkg/server/api/agent/v1/service_test.go +++ b/pkg/server/api/agent/v1/service_test.go @@ -218,7 +218,7 @@ func TestCountAgents(t *testing.T) { test := setupServiceTest(t, 0) defer test.Cleanup() - for i := 0; i < int(tt.count); i++ { + for i := range int(tt.count) { now := time.Now() _, err := test.ds.CreateAttestedNode(ctx, &common.AttestedNode{ SpiffeId: ids[i].String(), diff --git a/pkg/server/api/bundle/v1/service_test.go b/pkg/server/api/bundle/v1/service_test.go index 86ce239281..3d85fa1945 100644 --- a/pkg/server/api/bundle/v1/service_test.go +++ b/pkg/server/api/bundle/v1/service_test.go @@ -1698,7 +1698,7 @@ func TestCountBundles(t *testing.T) { test := setupServiceTest(t) defer test.Cleanup() - for i := 0; i < int(tt.count); i++ { + for i := range int(tt.count) { createBundle(t, test, tds[i].IDString()) } diff --git a/pkg/server/api/entry/v1/service_test.go b/pkg/server/api/entry/v1/service_test.go index b8bb18d7e0..019b0e4a03 100644 --- a/pkg/server/api/entry/v1/service_test.go +++ b/pkg/server/api/entry/v1/service_test.go @@ -147,7 +147,7 @@ func TestCountEntries(t *testing.T) { test := setupServiceTest(t, ds) defer test.Cleanup() - for i := 0; i < int(tt.count); i++ { + for i := range int(tt.count) { _, err := test.ds.CreateRegistrationEntry(ctx, &common.RegistrationEntry{ ParentId: spiffeid.RequireFromSegments(td, fmt.Sprintf("parent%d", i)).String(), SpiffeId: spiffeid.RequireFromSegments(td, fmt.Sprintf("child%d", i)).String(), @@ -3322,7 +3322,7 @@ func FuzzSyncAuthorizedStreams(f *testing.F) { const maxEntries = 40 var entries []*types.Entry - for i := 0; i < maxEntries; i++ { + for i := range maxEntries { entries = append(entries, &types.Entry{Id: strconv.Itoa(i), RevisionNumber: 1}) } @@ -3374,7 +3374,7 @@ func FuzzSyncAuthorizedStreams(f *testing.F) { // The number of entries exceeded the page size. Expect one or more // pages of entry revisions. var actualIDs []string - for page := 0; page < calculatePageCount(totalEntries)-1; page++ { + for range calculatePageCount(totalEntries) - 1 { resp := recvNoError(t, stream) require.Equal(t, len(resp.EntryRevisions), entryPageSize) require.Zero(t, resp.Entries) @@ -3397,7 +3397,7 @@ func FuzzSyncAuthorizedStreams(f *testing.F) { require.NoError(t, stream.Send(&entryv1.SyncAuthorizedEntriesRequest{Ids: staleIDs})) actualIDs = actualIDs[:0] - for page := 0; page < calculatePageCount(len(staleIDs))-1; page++ { + for range calculatePageCount(len(staleIDs)) - 1 { resp = recvNoError(t, stream) require.Equal(t, len(resp.Entries), entryPageSize) require.Zero(t, resp.EntryRevisions) diff --git a/pkg/server/authorizedentries/cache_test.go b/pkg/server/authorizedentries/cache_test.go index f16c9d8b08..360008ca76 100644 --- a/pkg/server/authorizedentries/cache_test.go +++ b/pkg/server/authorizedentries/cache_test.go @@ -358,7 +358,7 @@ func BenchmarkGetAuthorizedEntriesInMemory(b *testing.B) { staticSelector2 := &types.Selector{Type: "static", Value: "static-2"} const numAgents = 50000 - for i := 0; i < numAgents; i++ { + for i := range numAgents { test.withAgent(spiffeid.RequireFromPathf(td, "/agent-%d", i), staticSelector1) } @@ -382,7 +382,7 @@ func BenchmarkGetAuthorizedEntriesInMemory(b *testing.B) { }, ) - for i := 0; i < 300; i++ { + for i := range 300 { test.withEntries(&types.Entry{ Id: fmt.Sprintf("alias1-workload-%d", i), SpiffeId: &types.SPIFFEID{ @@ -396,7 +396,7 @@ func BenchmarkGetAuthorizedEntriesInMemory(b *testing.B) { }) } - for i := 0; i < 300; i++ { + for i := range 300 { test.withEntries(&types.Entry{ Id: fmt.Sprintf("alias2-workload-%d", i), SpiffeId: &types.SPIFFEID{ @@ -412,7 +412,7 @@ func BenchmarkGetAuthorizedEntriesInMemory(b *testing.B) { cache := test.hydrate(b) b.ResetTimer() - for i := 0; i < b.N; i++ { + for range b.N { cache.GetAuthorizedEntries(test.pickAgent()) } } diff --git a/pkg/server/bundle/pubmanager/pubmanager_test.go b/pkg/server/bundle/pubmanager/pubmanager_test.go index e61c98b2d0..0a68798ff4 100644 --- a/pkg/server/bundle/pubmanager/pubmanager_test.go +++ b/pkg/server/bundle/pubmanager/pubmanager_test.go @@ -182,7 +182,7 @@ type managerTest struct { } func (test *managerTest) waitForPublishResult(ctx context.Context, t *testing.T, expectedResults publishResults) { - for i := 0; i < len(expectedResults); i++ { + for range expectedResults { select { case bpe := <-test.m.hooks.publishResultCh: expectedBPEvent, ok := expectedResults[bpe.pluginName] diff --git a/pkg/server/ca/manager/journal_test.go b/pkg/server/ca/manager/journal_test.go index 40f725b130..cb9e3fee4b 100644 --- a/pkg/server/ca/manager/journal_test.go +++ b/pkg/server/ca/manager/journal_test.go @@ -192,7 +192,7 @@ func TestX509CAOverflow(t *testing.T) { journal := test.loadJournal(t) - for i := 0; i < (journalCap + 1); i++ { + for range journalCap + 1 { now = now.Add(time.Minute) err := journal.AppendX509CA(ctx, "A", now, &ca.X509CA{ Signer: kmKeys["X509-CA-A"], @@ -313,7 +313,7 @@ func TestJWTKeyOverflow(t *testing.T) { journal := test.loadJournal(t) - for i := 0; i < (journalCap + 1); i++ { + for range journalCap + 1 { now = now.Add(time.Minute) err := journal.AppendJWTKey(ctx, "B", now, &ca.JWTKey{ Signer: kmKeys["JWT-Signer-B"], diff --git a/pkg/server/ca/manager/manager.go b/pkg/server/ca/manager/manager.go index 4aa631c41c..0240697fee 100644 --- a/pkg/server/ca/manager/manager.go +++ b/pkg/server/ca/manager/manager.go @@ -736,7 +736,7 @@ func (m *Manager) notify(ctx context.Context, event string, advise bool, pre fun } var allErrs errs.Group - for i := 0; i < len(notifiers); i++ { + for range notifiers { // don't select on the ctx here as we can rely on the plugins to // respond to context cancellation and return an error. if err := <-errsCh; err != nil { diff --git a/pkg/server/cache/entrycache/fullcache_ds_test.go b/pkg/server/cache/entrycache/fullcache_ds_test.go index 5ee5aae52e..147ee322b5 100644 --- a/pkg/server/cache/entrycache/fullcache_ds_test.go +++ b/pkg/server/cache/entrycache/fullcache_ds_test.go @@ -37,7 +37,7 @@ func TestEntryIteratorDS(t *testing.T) { {Type: "doesn't", Value: "matter"}, } entriesToCreate := make([]*common.RegistrationEntry, numEntries) - for i := 0; i < numEntries; i++ { + for i := range numEntries { entriesToCreate[i] = &common.RegistrationEntry{ ParentId: parentID, SpiffeId: spiffeIDPrefix + strconv.Itoa(i), @@ -57,7 +57,7 @@ func TestEntryIteratorDS(t *testing.T) { it := makeEntryIteratorDS(ds) var entries []*types.Entry - for i := 0; i < numEntries; i++ { + for range numEntries { assert.True(t, it.Next(ctx)) require.NoError(t, it.Err()) @@ -73,7 +73,7 @@ func TestEntryIteratorDS(t *testing.T) { t.Run("datastore error", func(t *testing.T) { it := makeEntryIteratorDS(ds) - for i := 0; i < int(listEntriesRequestPageSize); i++ { + for range listEntriesRequestPageSize { assert.True(t, it.Next(ctx)) require.NoError(t, it.Err()) } @@ -105,7 +105,7 @@ func TestAgentIteratorDS(t *testing.T) { expectedSelectors := api.ProtoFromSelectors(selectors) expectedAgents := make([]Agent, numAgents) - for i := 0; i < numAgents; i++ { + for i := range numAgents { iterStr := strconv.Itoa(i) agentID, err := spiffeid.FromString("spiffe://example.org/spire/agent/agent" + iterStr) require.NoError(t, err) @@ -129,7 +129,7 @@ func TestAgentIteratorDS(t *testing.T) { t.Run("multiple pages", func(t *testing.T) { it := makeAgentIteratorDS(ds) agents := make([]Agent, numAgents) - for i := 0; i < numAgents; i++ { + for i := range numAgents { assert.True(t, it.Next(ctx)) assert.NoError(t, it.Err()) agents[i] = it.Agent() diff --git a/pkg/server/cache/entrycache/fullcache_test.go b/pkg/server/cache/entrycache/fullcache_test.go index 19122edc4e..3b2c34f7c8 100644 --- a/pkg/server/cache/entrycache/fullcache_test.go +++ b/pkg/server/cache/entrycache/fullcache_test.go @@ -53,7 +53,7 @@ func TestCache(t *testing.T) { const serverID = "spiffe://example.org/spire/server" const numEntries = 5 entryIDs := make([]string, numEntries) - for i := 0; i < numEntries; i++ { + for i := range numEntries { entryIDURI := url.URL{ Scheme: spiffeScheme, Host: trustDomain, @@ -340,7 +340,7 @@ func TestFullCacheExcludesNodeSelectorMappedEntriesForExpiredAgents(t *testing.T const numAliasEntries = 3 aliasEntryIDs := make([]string, numAliasEntries) - for i := 0; i < numAliasEntries; i++ { + for i := range numAliasEntries { entryURI := &url.URL{ Scheme: spiffeScheme, Host: trustDomain, @@ -369,13 +369,13 @@ func TestFullCacheExcludesNodeSelectorMappedEntriesForExpiredAgents(t *testing.T } aliasEntries := make([]*common.RegistrationEntry, numAliasEntries) - for i := 0; i < numAliasEntries; i++ { + for i := range numAliasEntries { aliasEntries[i] = createRegistrationEntry(ctx, t, ds, aliasEntriesToCreate[i]) } const numWorkloadEntries = 5 workloadEntryIDs := make([]string, numWorkloadEntries) - for i := 0; i < numWorkloadEntries; i++ { + for i := range numWorkloadEntries { entryURI := &url.URL{ Scheme: spiffeScheme, Host: trustDomain, @@ -421,7 +421,7 @@ func TestFullCacheExcludesNodeSelectorMappedEntriesForExpiredAgents(t *testing.T } workloadEntries := make([]*common.RegistrationEntry, numWorkloadEntries) - for i := 0; i < numWorkloadEntries; i++ { + for i := range numWorkloadEntries { workloadEntries[i] = createRegistrationEntry(ctx, t, ds, workloadEntriesToCreate[i]) } @@ -470,7 +470,7 @@ func TestBuildIteratorError(t *testing.T) { func BenchmarkBuildInMemory(b *testing.B) { allEntries, agents := buildBenchmarkData() b.ResetTimer() - for i := 0; i < b.N; i++ { + for range b.N { _, err := Build(context.Background(), makeEntryIterator(allEntries), makeAgentIterator(agents)) if err != nil { b.Fatal(err) @@ -483,7 +483,7 @@ func BenchmarkGetAuthorizedEntriesInMemory(b *testing.B) { cache, err := Build(context.Background(), makeEntryIterator(allEntries), makeAgentIterator(agents)) require.NoError(b, err) b.ResetTimer() - for i := 0; i < b.N; i++ { + for i := range b.N { cache.GetAuthorizedEntries(agents[i%len(agents)].ID) } } @@ -518,7 +518,7 @@ func BenchmarkBuildSQL(b *testing.B) { } b.ResetTimer() - for i := 0; i < b.N; i++ { + for range b.N { _, err := BuildFromDataStore(ctx, ds) if err != nil { b.Fatal(err) @@ -680,7 +680,7 @@ func buildBenchmarkData() ([]*types.Entry, []Agent) { const numAgents = 50000 agents := make([]Agent, 0, numAgents) - for i := 0; i < numAgents; i++ { + for i := range numAgents { agents = append(agents, Agent{ ID: makeAgentID(i), Selectors: []*types.Selector{ @@ -717,7 +717,7 @@ func buildBenchmarkData() ([]*types.Entry, []Agent) { } var workloadEntries1 []*types.Entry - for i := 0; i < 300; i++ { + for i := range 300 { workloadEntries1 = append(workloadEntries1, &types.Entry{ Id: fmt.Sprintf("workload%d", i), SpiffeId: &types.SPIFFEID{ @@ -732,7 +732,7 @@ func buildBenchmarkData() ([]*types.Entry, []Agent) { } var workloadEntries2 []*types.Entry - for i := 0; i < 300; i++ { + for i := range 300 { workloadEntries2 = append(workloadEntries2, &types.Entry{ Id: fmt.Sprintf("workload%d", i), SpiffeId: &types.SPIFFEID{ diff --git a/pkg/server/datastore/sqlstore/sqlstore.go b/pkg/server/datastore/sqlstore/sqlstore.go index 76c4f3ed5c..f3e38d2a55 100644 --- a/pkg/server/datastore/sqlstore/sqlstore.go +++ b/pkg/server/datastore/sqlstore/sqlstore.go @@ -3453,7 +3453,7 @@ func indent(builder *strings.Builder, indentation int) { case 5: builder.WriteString("\t\t\t\t\t") default: - for i := 0; i < indentation; i++ { + for range indentation { builder.WriteString("\t") } } diff --git a/pkg/server/datastore/sqlstore/sqlstore_test.go b/pkg/server/datastore/sqlstore/sqlstore_test.go index e0d11ab020..40700d42f6 100644 --- a/pkg/server/datastore/sqlstore/sqlstore_test.go +++ b/pkg/server/datastore/sqlstore/sqlstore_test.go @@ -1726,7 +1726,7 @@ func (s *PluginSuite) TestListNodeSelectors() { const attestationDataType = "fake_nodeattestor" nonExpiredAttNodes := make([]*common.AttestedNode, numNonExpiredAttNodes) now := time.Now() - for i := 0; i < numNonExpiredAttNodes; i++ { + for i := range numNonExpiredAttNodes { nonExpiredAttNodes[i] = &common.AttestedNode{ SpiffeId: fmt.Sprintf("spiffe://example.org/non-expired-node-%d", i), AttestationDataType: attestationDataType, @@ -1739,7 +1739,7 @@ func (s *PluginSuite) TestListNodeSelectors() { const numExpiredAttNodes = 2 expiredAttNodes := make([]*common.AttestedNode, numExpiredAttNodes) - for i := 0; i < numExpiredAttNodes; i++ { + for i := range numExpiredAttNodes { expiredAttNodes[i] = &common.AttestedNode{ SpiffeId: fmt.Sprintf("spiffe://example.org/expired-node-%d", i), AttestationDataType: attestationDataType, @@ -1770,7 +1770,7 @@ func (s *PluginSuite) TestListNodeSelectors() { } nonExpiredSelectorsMap := make(map[string][]*common.Selector, numNonExpiredAttNodes) - for i := 0; i < numNonExpiredAttNodes; i++ { + for i := range numNonExpiredAttNodes { spiffeID := nonExpiredAttNodes[i].SpiffeId nonExpiredSelectorsMap[spiffeID] = selectorMap[spiffeID] } @@ -1824,10 +1824,10 @@ func (s *PluginSuite) TestSetNodeSelectorsUnderLoad() { resultCh := make(chan error, numWorkers) nextID := int32(0) - for i := 0; i < numWorkers; i++ { + for range numWorkers { go func() { id := fmt.Sprintf("ID%d", atomic.AddInt32(&nextID, 1)) - for j := 0; j < 10; j++ { + for range 10 { err := s.ds.SetNodeSelectors(ctx, id, selectors) if err != nil { resultCh <- err @@ -1837,7 +1837,7 @@ func (s *PluginSuite) TestSetNodeSelectorsUnderLoad() { }() } - for i := 0; i < numWorkers; i++ { + for range numWorkers { s.Require().NoError(<-resultCh) } } @@ -4892,7 +4892,7 @@ func (s *PluginSuite) TestUpdateFederationRelationship() { } func (s *PluginSuite) TestMigration() { - for schemaVersion := 0; schemaVersion < latestSchemaVersion; schemaVersion++ { + for schemaVersion := range latestSchemaVersion { s.T().Run(fmt.Sprintf("migration_from_schema_version_%d", schemaVersion), func(t *testing.T) { require := require.New(t) dbName := fmt.Sprintf("v%d.sqlite3", schemaVersion) @@ -5245,7 +5245,7 @@ func (s *PluginSuite) TestConfigure() { // begin many queries simultaneously numQueries := 100 var rowsList []*sql.Rows - for i := 0; i < numQueries; i++ { + for range numQueries { rows, err := db.Query("SELECT * FROM bundles") require.NoError(t, err) rowsList = append(rowsList, rows) diff --git a/pkg/server/endpoints/endpoints_test.go b/pkg/server/endpoints/endpoints_test.go index aee6ee95fd..6557dc7126 100644 --- a/pkg/server/endpoints/endpoints_test.go +++ b/pkg/server/endpoints/endpoints_test.go @@ -1022,7 +1022,7 @@ func testAuthorization(ctx context.Context, t *testing.T, client any, expectedAu cv := reflect.ValueOf(client) ct := cv.Type() - for i := 0; i < ct.NumMethod(); i++ { + for i := range ct.NumMethod() { mv := cv.Method(i) methodName := ct.Method(i).Name t.Run(methodName, func(t *testing.T) { @@ -1065,7 +1065,7 @@ func assertServiceUnavailable(ctx context.Context, t *testing.T, client any) { cv := reflect.ValueOf(client) ct := cv.Type() - for i := 0; i < ct.NumMethod(); i++ { + for i := range ct.NumMethod() { mv := cv.Method(i) methodName := ct.Method(i).Name t.Run(methodName, func(t *testing.T) { diff --git a/pkg/server/endpoints/entryfetcher_test.go b/pkg/server/endpoints/entryfetcher_test.go index 0e92f70190..5262f72676 100644 --- a/pkg/server/endpoints/entryfetcher_test.go +++ b/pkg/server/endpoints/entryfetcher_test.go @@ -224,7 +224,7 @@ func TestRunRebuildCacheTask(t *testing.T) { func setupExpectedEntriesData(t *testing.T, agentID spiffeid.ID) []*types.Entry { const numEntries = 2 entryIDs := make([]spiffeid.ID, numEntries) - for i := 0; i < numEntries; i++ { + for i := range numEntries { entryIDs[i] = spiffeid.RequireFromPathf(trustDomain, "/%d", i) } diff --git a/pkg/server/plugin/credentialcomposer/uniqueid/plugin.go b/pkg/server/plugin/credentialcomposer/uniqueid/plugin.go index 30cd1319a1..7d30d6e153 100644 --- a/pkg/server/plugin/credentialcomposer/uniqueid/plugin.go +++ b/pkg/server/plugin/credentialcomposer/uniqueid/plugin.go @@ -65,7 +65,7 @@ func (p *Plugin) ComposeWorkloadX509SVID(_ context.Context, req *credentialcompo // Add the attribute if it does not already exist. Otherwise, replace the old value. found := false - for i := 0; i < len(attributes.Subject.ExtraNames); i++ { + for i := range len(attributes.Subject.ExtraNames) { if attributes.Subject.ExtraNames[i].Oid == uniqueID.Oid { attributes.Subject.ExtraNames[i] = uniqueID found = true diff --git a/pkg/server/plugin/keymanager/gcpkms/client_fake.go b/pkg/server/plugin/keymanager/gcpkms/client_fake.go index bdda4ecc56..32dde6bdc3 100644 --- a/pkg/server/plugin/keymanager/gcpkms/client_fake.go +++ b/pkg/server/plugin/keymanager/gcpkms/client_fake.go @@ -338,7 +338,7 @@ func (k *fakeKMSClient) setGetPublicKeySequentialErrs(fakeError error, count int k.mu.Lock() defer k.mu.Unlock() fakeErrors := make([]error, count) - for i := 0; i < count; i++ { + for i := range count { fakeErrors[i] = fakeError } k.getPublicKeyErrs = fakeErrors diff --git a/pkg/server/plugin/upstreamauthority/certmanager/certmanager.go b/pkg/server/plugin/upstreamauthority/certmanager/certmanager.go index 3c93a775bf..db5e1df451 100644 --- a/pkg/server/plugin/upstreamauthority/certmanager/certmanager.go +++ b/pkg/server/plugin/upstreamauthority/certmanager/certmanager.go @@ -190,7 +190,7 @@ func (p *Plugin) MintX509CAAndSubscribe(request *upstreamauthorityv1.MintX509CAR // Poll the CertificateRequest until it is signed. If not signed after 300 // polls, error. obj := client.ObjectKey{Name: cr.GetName(), Namespace: cr.GetNamespace()} - for i := 0; true; i++ { + for i := 0; ; i++ { if i == 60*5 { // ~1.25 mins log.Error("Failed to wait for CertificateRequest to become ready in time") return status.Error(codes.Internal, "request did not become ready in time") diff --git a/test/spiretest/assertions.go b/test/spiretest/assertions.go index 39b3044dd9..9761ed5b80 100644 --- a/test/spiretest/assertions.go +++ b/test/spiretest/assertions.go @@ -123,7 +123,7 @@ func AssertProtoListEqual(tb testing.TB, expected, actual any) bool { if !assert.Equal(tb, ev.Len(), av.Len(), "expected %d elements in list; got %d", ev.Len(), av.Len()) { return false } - for i := 0; i < ev.Len(); i++ { + for i := range ev.Len() { e := ev.Index(i).Interface().(proto.Message) a := av.Index(i).Interface().(proto.Message) if !AssertProtoEqual(tb, e, a, "proto %d in list is not equal", i) { diff --git a/test/util/race.go b/test/util/race.go index dd1504a169..b1e3856806 100644 --- a/test/util/race.go +++ b/test/util/race.go @@ -22,10 +22,10 @@ func RaceTest(t *testing.T, fn func(*testing.T)) { // complete before this method returns. All subtests // will be run in parallel t.Run("group", func(t *testing.T) { - for i := 0; i < raceTestNumThreads; i++ { + for i := range raceTestNumThreads { t.Run(fmt.Sprintf("thread %v", i), func(t *testing.T) { t.Parallel() - for i := 0; i < raceTestNumLoops; i++ { + for range raceTestNumLoops { fn(t) } })