From ff374ff7fd2a6cc8de89ef10a816902b2d66a07d Mon Sep 17 00:00:00 2001 From: Zac Bergquist Date: Sun, 22 Jun 2025 04:53:52 -0600 Subject: [PATCH] Modernize lib/auth and lib/utils (#55976) --- lib/auth/access_request_test.go | 28 ++-- lib/auth/access_test.go | 54 +++---- .../accessmonitoringrulesv1/service_test.go | 5 +- lib/auth/accountrecovery.go | 4 +- lib/auth/accountrecovery_test.go | 1 - lib/auth/apiserver.go | 56 +++---- lib/auth/apiserver_test.go | 1 - lib/auth/auth.go | 10 +- lib/auth/auth_login_test.go | 12 +- lib/auth/auth_test.go | 24 ++- lib/auth/auth_with_roles.go | 4 +- lib/auth/auth_with_roles_test.go | 147 ++++++++---------- lib/auth/authclient/http_client.go | 4 +- lib/auth/bot.go | 2 +- lib/auth/bot_test.go | 4 +- .../clusterconfig/clusterconfigv1/service.go | 6 +- lib/auth/db_test.go | 1 - lib/auth/dbobject/dbobjectv1/service_test.go | 6 +- .../dbobjectimportrulev1/service_test.go | 6 +- .../discoveryconfigv1/service_test.go | 10 +- lib/auth/github.go | 2 +- lib/auth/grpcserver_test.go | 51 +++--- lib/auth/init.go | 7 +- lib/auth/init_test.go | 4 +- .../integration/integrationv1/service_test.go | 3 +- .../join/boundkeypair/boundkeypair_test.go | 2 +- lib/auth/join/oracle/oracle.go | 4 +- lib/auth/join_azure_devops_test.go | 4 +- lib/auth/join_bitbucket_test.go | 4 +- lib/auth/join_bound_keypair_test.go | 34 ++-- lib/auth/join_circleci_test.go | 6 +- lib/auth/join_gcp_test.go | 2 +- lib/auth/join_github_test.go | 6 +- lib/auth/join_gitlab_test.go | 2 +- lib/auth/join_iam_test.go | 4 +- lib/auth/join_spacelift_test.go | 6 +- lib/auth/join_terraformcloud_test.go | 10 +- lib/auth/join_tpm_test.go | 6 +- lib/auth/keystore/aws_kms_test.go | 2 +- lib/auth/keystore/gcp_kms_test.go | 4 +- lib/auth/keystore/keystore_test.go | 2 +- lib/auth/keystore/pkcs11.go | 12 +- .../kubewaitingcontainerv1/service_test.go | 3 +- .../machineidv1/bot_instance_service_test.go | 20 ++- lib/auth/machineid/machineidv1/bot_service.go | 5 +- .../machineid/machineidv1/machineidv1_test.go | 62 ++++---- .../spiffe_federation_service_test.go | 14 +- .../machineid/workloadidentityv1/decision.go | 5 +- .../workloadidentityv1/decision_test.go | 4 +- .../workloadidentityv1/expression/proto.go | 2 +- .../workloadidentityv1_test.go | 70 ++++----- lib/auth/middleware.go | 10 +- lib/auth/middleware_test.go | 2 +- lib/auth/mocku2f/webauthn.go | 4 +- lib/auth/moderation/session_access.go | 2 +- lib/auth/moderation/session_access_test.go | 1 - lib/auth/password_test.go | 2 +- lib/auth/periodic_test.go | 4 +- lib/auth/presence/presencev1/service_test.go | 36 ++--- .../stableunixusers/stableunixusers_test.go | 3 +- lib/auth/state/identity.go | 6 +- lib/auth/tls_test.go | 33 ++-- lib/auth/touchid/api.go | 9 +- lib/auth/touchid/api_test.go | 3 +- lib/auth/touchid/attempt.go | 2 +- lib/auth/transport_credentials_test.go | 14 +- lib/auth/trust/trustv1/service_test.go | 12 +- lib/auth/trustedcluster.go | 3 +- lib/auth/trustedcluster_test.go | 2 +- .../userprovisioningv2/service_test.go | 4 +- lib/auth/users/usersv1/service_test.go | 11 +- lib/auth/usertoken.go | 7 +- lib/auth/usertoken_test.go | 1 - lib/auth/webauthn/attestation.go | 2 +- lib/auth/webauthn/attestation_test.go | 48 +++--- lib/auth/webauthn/login_test.go | 14 +- lib/auth/webauthntypes/proto.go | 2 +- lib/auth/webauthntypes/webauthn.go | 2 +- lib/utils/addr.go | 4 +- lib/utils/algorithms.go | 4 +- lib/utils/archive_test.go | 2 +- lib/utils/aws/endpoint/resolver_test.go | 2 +- lib/utils/circular_buffer_test.go | 2 +- lib/utils/cli.go | 2 +- lib/utils/concurrentqueue/queue.go | 2 +- lib/utils/concurrentqueue/queue_test.go | 10 +- lib/utils/copy.go | 12 -- lib/utils/diagnostics/latency/monitor_test.go | 4 +- lib/utils/disk.go | 2 +- lib/utils/envutils/environment_test.go | 4 +- lib/utils/fanoutbuffer/buffer.go | 2 +- lib/utils/fanoutbuffer/buffer_test.go | 15 +- lib/utils/fields.go | 4 +- lib/utils/fields_test.go | 2 +- lib/utils/fncache_test.go | 34 ++-- lib/utils/fs.go | 4 +- lib/utils/gcp/gcp_test.go | 14 +- lib/utils/genmap/genmap_test.go | 13 +- lib/utils/host/hostusers.go | 2 +- lib/utils/hostid/hostid_test.go | 2 +- lib/utils/hostid/hostid_unix.go | 2 +- lib/utils/inmemory_fs.go | 2 +- lib/utils/interval/duration_test.go | 4 +- lib/utils/interval/interval_test.go | 10 +- lib/utils/interval/multi.go | 9 +- lib/utils/interval/multi_test.go | 20 +-- lib/utils/iterators_test.go | 5 +- lib/utils/jsontools.go | 22 +-- lib/utils/jsontools_test.go | 4 +- lib/utils/linking.go | 2 +- lib/utils/loadbalancer.go | 5 +- lib/utils/log/formatter_test.go | 4 +- lib/utils/log/slog_handler_test.go | 4 +- lib/utils/mcputils/id_tracker_test.go | 2 +- lib/utils/mcputils/protocol.go | 4 +- lib/utils/mcputils/protocol_test.go | 4 +- lib/utils/net.go | 2 +- lib/utils/oidc/issuer_test.go | 4 +- lib/utils/parse/parse_test.go | 4 +- lib/utils/proxyconn.go | 2 +- lib/utils/replace.go | 9 +- lib/utils/roundrobin_test.go | 4 +- lib/utils/slice.go | 6 +- lib/utils/slice_test.go | 2 +- lib/utils/socks/socks.go | 2 +- lib/utils/sortcache/sortcache_test.go | 8 +- lib/utils/spreadwork/spreadwork.go | 5 +- lib/utils/testutils/testhelpers.go | 2 +- lib/utils/testutils/testutils.go | 4 +- lib/utils/timeout_test.go | 2 +- lib/utils/typical/cached_parser_test.go | 6 +- lib/utils/typical/parser_test.go | 4 +- lib/utils/uds/socketpair_unix_test.go | 4 +- lib/utils/utils.go | 9 +- lib/utils/utils_test.go | 18 +-- lib/utils/ver_test.go | 2 - 136 files changed, 599 insertions(+), 731 deletions(-) diff --git a/lib/auth/access_request_test.go b/lib/auth/access_request_test.go index e280d1e8122..20d3ceb69af 100644 --- a/lib/auth/access_request_test.go +++ b/lib/auth/access_request_test.go @@ -263,8 +263,7 @@ func TestAccessRequestResourceRBACLimits(t *testing.T) { require.NoError(t, err) defer tlsServer.Close() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() staticRole, err := types.NewRole(staticRoleName, types.RoleSpecV6{ Allow: types.RoleConditions{ @@ -382,8 +381,7 @@ func TestListAccessRequests(t *testing.T) { require.NoError(t, err) defer tlsServer.Close() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() userA, userB := "lister-a", "lister-b" roleA, roleB := userA+"-role", userB+"-role" @@ -435,7 +433,7 @@ func TestListAccessRequests(t *testing.T) { // verify sort order). var orderedIDs []string - for i := 0; i < requestsPerUser; i++ { + for range requestsPerUser { clock.Advance(time.Second) reqA, err := services.NewAccessRequest(userA, rroleA) require.NoError(t, err) @@ -444,7 +442,7 @@ func TestListAccessRequests(t *testing.T) { orderedIDs = append(orderedIDs, rr.GetName()) } - for i := 0; i < requestsPerUser; i++ { + for range requestsPerUser { clock.Advance(time.Second) reqB, err := services.NewAccessRequest(userB, rroleB) require.NoError(t, err) @@ -865,7 +863,6 @@ func testSingleAccessRequests(t *testing.T, testPack *accessRequestTestPack) { }, } for _, tc := range testCases { - tc := tc t.Run(tc.desc, func(t *testing.T) { t.Parallel() requester := TestUser(tc.requester) @@ -1297,7 +1294,6 @@ func testMultiAccessRequests(t *testing.T, testPack *accessRequestTestPack) { expectAccessRequests: []string{adminRequest.GetName()}, }, } { - tc := tc t.Run(tc.desc, func(t *testing.T) { t.Parallel() client := requesterClient @@ -1734,7 +1730,6 @@ func TestUpdateAccessRequestWithAdditionalReviewers(t *testing.T) { } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() mem, err := memory.New(memory.Config{}) @@ -1775,7 +1770,7 @@ func TestAssumeStartTime_CreateAccessRequestV2(t *testing.T) { { name: "too far in the future", startTime: s.invalidMaxedAssumeStartTime, - errCheck: func(tt require.TestingT, err error, i ...interface{}) { + errCheck: func(tt require.TestingT, err error, i ...any) { require.True(t, trace.IsBadParameter(err), "expected bad parameter, got %v", err) require.ErrorContains(t, err, "assume start time is too far in the future") }, @@ -1783,7 +1778,7 @@ func TestAssumeStartTime_CreateAccessRequestV2(t *testing.T) { { name: "after access expiry time", startTime: s.invalidExpiredAssumeStartTime, - errCheck: func(tt require.TestingT, err error, i ...interface{}) { + errCheck: func(tt require.TestingT, err error, i ...any) { require.True(t, trace.IsBadParameter(err), "expected bad parameter, got %v", err) require.ErrorContains(t, err, "assume start time must be prior to access expiry time") }, @@ -1791,7 +1786,6 @@ func TestAssumeStartTime_CreateAccessRequestV2(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { req, err := services.NewAccessRequest(s.requesterUserName, "admins") require.NoError(t, err) @@ -1815,7 +1809,7 @@ func TestAssumeStartTime_SubmitAccessReview(t *testing.T) { { name: "too far in the future", startTime: s.invalidMaxedAssumeStartTime, - errCheck: func(tt require.TestingT, err error, i ...interface{}) { + errCheck: func(tt require.TestingT, err error, i ...any) { require.True(t, trace.IsBadParameter(err), "expected bad parameter, got %v", err) require.ErrorContains(t, err, "assume start time is too far in the future") }, @@ -1823,7 +1817,7 @@ func TestAssumeStartTime_SubmitAccessReview(t *testing.T) { { name: "after access expiry time", startTime: s.invalidExpiredAssumeStartTime, - errCheck: func(tt require.TestingT, err error, i ...interface{}) { + errCheck: func(tt require.TestingT, err error, i ...any) { require.True(t, trace.IsBadParameter(err), "expected bad parameter, got %v", err) require.ErrorContains(t, err, "assume start time must be prior to access expiry time") }, @@ -1842,7 +1836,6 @@ func TestAssumeStartTime_SubmitAccessReview(t *testing.T) { }, } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { review.Review.AssumeStartTime = &tc.startTime resp, err := s.testPack.tlsServer.AuthServer.AuthServer.SubmitAccessReview(ctx, review) @@ -1866,7 +1859,7 @@ func TestAssumeStartTime_SetAccessRequestState(t *testing.T) { { name: "too far in the future", startTime: s.invalidMaxedAssumeStartTime, - errCheck: func(tt require.TestingT, err error, i ...interface{}) { + errCheck: func(tt require.TestingT, err error, i ...any) { require.True(t, trace.IsBadParameter(err), "expected bad parameter, got %v", err) require.ErrorContains(t, err, "assume start time is too far in the future") }, @@ -1874,7 +1867,7 @@ func TestAssumeStartTime_SetAccessRequestState(t *testing.T) { { name: "after access expiry time", startTime: s.invalidExpiredAssumeStartTime, - errCheck: func(tt require.TestingT, err error, i ...interface{}) { + errCheck: func(tt require.TestingT, err error, i ...any) { require.True(t, trace.IsBadParameter(err), "expected bad parameter, got %v", err) require.ErrorContains(t, err, "assume start time must be prior to access expiry time") }, @@ -1890,7 +1883,6 @@ func TestAssumeStartTime_SetAccessRequestState(t *testing.T) { State: types.RequestState_APPROVED, } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { update.AssumeStartTime = &tc.startTime err := s.testPack.tlsServer.Auth().SetAccessRequestState(ctx, update) diff --git a/lib/auth/access_test.go b/lib/auth/access_test.go index fff75218693..220bc050e75 100644 --- a/lib/auth/access_test.go +++ b/lib/auth/access_test.go @@ -243,7 +243,7 @@ func TestCreateRole(t *testing.T) { name: "create role denied", userRole: newRole(t, "urole", nil, types.RoleConditions{}, types.RoleConditions{}), createRole: newRole(t, "create", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -252,7 +252,7 @@ func TestCreateRole(t *testing.T) { userRole: newRole(t, "urole", nil, rcWithRoleRule(types.VerbCreate), types.RoleConditions{}), startingRole: newRole(t, "create", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), createRole: newRole(t, "create", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAlreadyExists(err)) }, }, @@ -261,7 +261,7 @@ func TestCreateRole(t *testing.T) { userRole: newRole(t, "urole", nil, types.RoleConditions{}, types.RoleConditions{}), startingRole: newRole(t, "create", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), createRole: newRole(t, "create", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -290,14 +290,13 @@ func TestCreateRole(t *testing.T) { ).String(), ), types.RoleConditions{}), createRole: newRole(t, "create", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() ctx := context.Background() @@ -359,7 +358,7 @@ func TestUpdateRole(t *testing.T) { userRole: newRole(t, "urole", nil, types.RoleConditions{}, types.RoleConditions{}), startingRole: newRole(t, "update", nil, types.RoleConditions{}, types.RoleConditions{}), updateRole: newRole(t, "update", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -367,7 +366,7 @@ func TestUpdateRole(t *testing.T) { name: "update role not found", userRole: newRole(t, "urole", nil, rcWithRoleRule(types.VerbUpdate), types.RoleConditions{}), updateRole: newRole(t, "update", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { // This returns a compare failed instead of a NotFound. In the interests of not breaking anything, // I'll maintain this for now. require.True(t, trace.IsCompareFailed(err)) @@ -377,7 +376,7 @@ func TestUpdateRole(t *testing.T) { name: "update role not found with access denied", userRole: newRole(t, "urole", nil, types.RoleConditions{}, types.RoleConditions{}), updateRole: newRole(t, "update", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -410,7 +409,7 @@ func TestUpdateRole(t *testing.T) { ), types.RoleConditions{}), startingRole: newRole(t, "update", nil, types.RoleConditions{}, types.RoleConditions{}), updateRole: newRole(t, "update", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -426,7 +425,7 @@ func TestUpdateRole(t *testing.T) { updateRole: newRole(t, "update", map[string]string{ "label": "value", }, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -442,14 +441,13 @@ func TestUpdateRole(t *testing.T) { "label": "value", }, types.RoleConditions{}, types.RoleConditions{}), updateRole: newRole(t, "update", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() ctx := context.Background() @@ -521,7 +519,7 @@ func TestUpsertRole(t *testing.T) { userRole: newRole(t, "urole", nil, types.RoleConditions{}, types.RoleConditions{}), startingRole: newRole(t, "upsert", nil, types.RoleConditions{}, types.RoleConditions{}), upsertRole: newRole(t, "upsert", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -554,7 +552,7 @@ func TestUpsertRole(t *testing.T) { ), types.RoleConditions{}), startingRole: newRole(t, "upsert", nil, types.RoleConditions{}, types.RoleConditions{}), upsertRole: newRole(t, "upsert", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -570,7 +568,7 @@ func TestUpsertRole(t *testing.T) { upsertRole: newRole(t, "upsert", map[string]string{ "label": "value", }, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -586,14 +584,13 @@ func TestUpsertRole(t *testing.T) { "label": "value", }, types.RoleConditions{}, types.RoleConditions{}), upsertRole: newRole(t, "upsert", nil, rcWithRoleRule(services.RW()...), types.RoleConditions{}), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() ctx := context.Background() @@ -658,7 +655,7 @@ func TestGetRole(t *testing.T) { userRole: newRole(t, "urole", nil, types.RoleConditions{}, types.RoleConditions{}), roleToCreate: newRole(t, "get", nil, types.RoleConditions{}, types.RoleConditions{}), roleToGet: "get", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -666,7 +663,7 @@ func TestGetRole(t *testing.T) { name: "get role does not exist", userRole: newRole(t, "urole", nil, rcWithRoleRule(types.VerbRead), types.RoleConditions{}), roleToGet: "get", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsNotFound(err)) }, }, @@ -675,7 +672,7 @@ func TestGetRole(t *testing.T) { userRole: newRole(t, "urole", nil, types.RoleConditions{}, types.RoleConditions{}), roleToCreate: newRole(t, "get", nil, types.RoleConditions{}, types.RoleConditions{}), roleToGet: "get", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -706,14 +703,13 @@ func TestGetRole(t *testing.T) { ), types.RoleConditions{}), roleToCreate: newRole(t, "get", nil, types.RoleConditions{}, types.RoleConditions{}), roleToGet: "get", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() ctx := context.Background() @@ -786,7 +782,7 @@ func TestGetRoles(t *testing.T) { name: "get roles access denied", userRole: newRole(t, "urole", nil, types.RoleConditions{}, types.RoleConditions{}), rolesToCreate: allRoles(), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -818,14 +814,13 @@ func TestGetRoles(t *testing.T) { ).String(), ), types.RoleConditions{}), rolesToCreate: allRoles(), - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() ctx := context.Background() @@ -1040,7 +1035,7 @@ func TestDeleteRole(t *testing.T) { userRole: newRole(t, "urole", nil, types.RoleConditions{}, types.RoleConditions{}), roleToCreate: newRole(t, "delete", nil, types.RoleConditions{}, types.RoleConditions{}), roleToDelete: "delete", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -1048,7 +1043,7 @@ func TestDeleteRole(t *testing.T) { name: "delete role does not exist", userRole: newRole(t, "urole", nil, rcWithRoleRule(types.VerbDelete), types.RoleConditions{}), roleToDelete: "delete", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsNotFound(err)) }, }, @@ -1057,7 +1052,7 @@ func TestDeleteRole(t *testing.T) { userRole: newRole(t, "urole", nil, types.RoleConditions{}, types.RoleConditions{}), roleToCreate: newRole(t, "delete", nil, types.RoleConditions{}, types.RoleConditions{}), roleToDelete: "delete", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, @@ -1085,14 +1080,13 @@ func TestDeleteRole(t *testing.T) { ), types.RoleConditions{}), roleToCreate: newRole(t, "delete", nil, types.RoleConditions{}, types.RoleConditions{}), roleToDelete: "delete", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err)) }, }, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() ctx := context.Background() diff --git a/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service_test.go b/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service_test.go index 4cb93064394..8594f6d054c 100644 --- a/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service_test.go +++ b/lib/auth/accessmonitoringrules/accessmonitoringrulesv1/service_test.go @@ -41,7 +41,7 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) { clusterName := "test-cluster" requireTraceErrorFn := func(traceFn func(error) bool) require.ErrorAssertionFunc { - return func(tt require.TestingT, err error, i ...interface{}) { + return func(tt require.TestingT, err error, i ...any) { require.True(t, traceFn(err), "received an un-expected error: %v", err) } } @@ -126,7 +126,7 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) { }}}, }, Setup: func(t *testing.T, _ string) { - for i := 0; i < 10; i++ { + for range 10 { _, err := localClient.CreateAccessMonitoringRule(ctx, sampleAccessMonitoringRuleFn(uuid.NewString())) require.NoError(t, err) } @@ -292,7 +292,6 @@ func TestAccessMonitoringRuleCRUD(t *testing.T) { } for _, tc := range tt { - tc := tc t.Run(tc.Name, func(t *testing.T) { localCtx := authorizerForDummyUser(t, ctx, tc.Role, localClient) diff --git a/lib/auth/accountrecovery.go b/lib/auth/accountrecovery.go index 1c38a1d64bb..c085dac9388 100644 --- a/lib/auth/accountrecovery.go +++ b/lib/auth/accountrecovery.go @@ -163,7 +163,7 @@ func (a *Server) verifyRecoveryCode(ctx context.Context, username string, recove ctx, "Account recovery codes not found for user, using fake hashes to mitigate timing attacks", "user", username, ) - for i := 0; i < numOfRecoveryCodes; i++ { + for i := range numOfRecoveryCodes { hashedCodes[i].HashedCode = fakeRecoveryCodeHash } } else { @@ -521,7 +521,7 @@ func (a *Server) isAccountRecoveryAllowed(ctx context.Context) error { func generateRecoveryCodes() ([]string, error) { tokenList := make([]string, 0, numOfRecoveryCodes) - for i := 0; i < numOfRecoveryCodes; i++ { + for range numOfRecoveryCodes { wordIDs := make([]uint16, numWordsInRecoveryCode) if err := binary.Read(rand.Reader, binary.NativeEndian, wordIDs); err != nil { return nil, trace.Wrap(err) diff --git a/lib/auth/accountrecovery_test.go b/lib/auth/accountrecovery_test.go index 0ab77ddb4fa..e6d6f133482 100644 --- a/lib/auth/accountrecovery_test.go +++ b/lib/auth/accountrecovery_test.go @@ -1080,7 +1080,6 @@ func TestGetAccountRecoveryToken(t *testing.T) { } for _, c := range cases { - c := c t.Run(c.name, func(t *testing.T) { t.Parallel() diff --git a/lib/auth/apiserver.go b/lib/auth/apiserver.go index f86d1e22a81..5f9351f89b5 100644 --- a/lib/auth/apiserver.go +++ b/lib/auth/apiserver.go @@ -177,10 +177,10 @@ var httpMigratedHandler = httplib.MakeHandler(func( }) // HandlerWithAuthFunc is http handler with passed auth context -type HandlerWithAuthFunc func(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) +type HandlerWithAuthFunc func(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) func (s *APIServer) WithAuth(handler HandlerWithAuthFunc) httprouter.Handle { - return httplib.MakeHandler(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) { + return httplib.MakeHandler(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) (any, error) { // HTTPS server expects auth context to be set by the auth middleware authContext, err := s.Authorizer.Authorize(r.Context()) if err != nil { @@ -212,7 +212,7 @@ type presenceForAPIServer interface { } // upsertServer is a common utility function -func (s *APIServer) upsertServer(auth presenceForAPIServer, role types.SystemRole, r *http.Request, p httprouter.Params) (interface{}, error) { +func (s *APIServer) upsertServer(auth presenceForAPIServer, role types.SystemRole, r *http.Request, p httprouter.Params) (any, error) { var req upsertServerRawReq if err := httplib.ReadJSON(r, &req); err != nil { return nil, trace.Wrap(err) @@ -265,7 +265,7 @@ func (s *APIServer) upsertServer(auth presenceForAPIServer, role types.SystemRol } // keepAliveNode updates node TTL in the backend -func (s *APIServer) keepAliveNode(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) keepAliveNode(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { var handle types.KeepAlive if err := httplib.ReadJSON(r, &handle); err != nil { return nil, trace.Wrap(err) @@ -277,12 +277,12 @@ func (s *APIServer) keepAliveNode(auth *ServerWithRoles, w http.ResponseWriter, } // upsertProxy is called by remote SSH nodes when they ping back into the auth service -func (s *APIServer) upsertProxy(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) upsertProxy(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { return s.upsertServer(auth, types.RoleProxy, r, p) } // getProxies returns registered proxies -func (s *APIServer) getProxies(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) getProxies(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { servers, err := auth.GetProxies() if err != nil { return nil, trace.Wrap(err) @@ -291,7 +291,7 @@ func (s *APIServer) getProxies(auth *ServerWithRoles, w http.ResponseWriter, r * } // deleteAllProxies deletes all proxies -func (s *APIServer) deleteAllProxies(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) deleteAllProxies(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { err := auth.DeleteAllProxies() if err != nil { return nil, trace.Wrap(err) @@ -300,7 +300,7 @@ func (s *APIServer) deleteAllProxies(auth *ServerWithRoles, w http.ResponseWrite } // deleteProxy deletes proxy -func (s *APIServer) deleteProxy(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) deleteProxy(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { name := p.ByName("name") if name == "" { return nil, trace.BadParameter("missing proxy name") @@ -313,12 +313,12 @@ func (s *APIServer) deleteProxy(auth *ServerWithRoles, w http.ResponseWriter, r } // upsertAuthServer is called by remote Auth servers when they ping back into the auth service -func (s *APIServer) upsertAuthServer(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) upsertAuthServer(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { return s.upsertServer(auth, types.RoleAuth, r, p) } // getAuthServers returns registered auth servers -func (s *APIServer) getAuthServers(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) getAuthServers(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { servers, err := auth.GetAuthServers() if err != nil { return nil, trace.Wrap(err) @@ -326,7 +326,7 @@ func (s *APIServer) getAuthServers(auth *ServerWithRoles, w http.ResponseWriter, return marshalServers(servers, version) } -func marshalServers(servers []types.Server, version string) (interface{}, error) { +func marshalServers(servers []types.Server, version string) (any, error) { items := make([]json.RawMessage, len(servers)) for i, server := range servers { data, err := services.MarshalServer(server, services.WithVersion(version), services.PreserveRevision()) @@ -338,7 +338,7 @@ func marshalServers(servers []types.Server, version string) (interface{}, error) return items, nil } -func (s *APIServer) validateTrustedCluster(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) validateTrustedCluster(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { var validateRequestRaw authclient.ValidateTrustedClusterRequestRaw if err := httplib.ReadJSON(r, &validateRequestRaw); err != nil { return nil, trace.Wrap(err) @@ -362,7 +362,7 @@ func (s *APIServer) validateTrustedCluster(auth *ServerWithRoles, w http.Respons return validateResponseRaw, nil } -func (s *APIServer) deleteWebSession(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) deleteWebSession(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { user, sessionID := p.ByName("user"), p.ByName("sid") err := auth.WebSessions().Delete(r.Context(), types.DeleteWebSessionRequest{ User: user, @@ -374,7 +374,7 @@ func (s *APIServer) deleteWebSession(auth *ServerWithRoles, w http.ResponseWrite return message(fmt.Sprintf("session %q for user %q deleted", sessionID, user)), nil } -func (s *APIServer) getWebSession(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) getWebSession(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { user, sid := p.ByName("user"), p.ByName("sid") sess, err := auth.GetWebSessionInfo(r.Context(), user, sid) if err != nil { @@ -383,7 +383,7 @@ func (s *APIServer) getWebSession(auth *ServerWithRoles, w http.ResponseWriter, return rawMessage(services.MarshalWebSession(sess, services.WithVersion(version))) } -func (s *APIServer) createWebSession(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) createWebSession(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { var req authclient.WebSessionReq if err := httplib.ReadJSON(r, &req); err != nil { return nil, trace.Wrap(err) @@ -405,7 +405,7 @@ func (s *APIServer) createWebSession(auth *ServerWithRoles, w http.ResponseWrite return rawMessage(services.MarshalWebSession(sess, services.WithVersion(version))) } -func (s *APIServer) authenticateWebUser(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) authenticateWebUser(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { var req authclient.AuthenticateUserRequest if err := httplib.ReadJSON(r, &req); err != nil { return nil, trace.Wrap(err) @@ -418,7 +418,7 @@ func (s *APIServer) authenticateWebUser(auth *ServerWithRoles, w http.ResponseWr return rawMessage(services.MarshalWebSession(sess, services.WithVersion(version))) } -func (s *APIServer) authenticateSSHUser(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) authenticateSSHUser(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { var req authclient.AuthenticateSSHRequest if err := httplib.ReadJSON(r, &req); err != nil { return nil, trace.Wrap(err) @@ -427,7 +427,7 @@ func (s *APIServer) authenticateSSHUser(auth *ServerWithRoles, w http.ResponseWr return auth.AuthenticateSSHUser(r.Context(), req) } -func rawMessage(data []byte, err error) (interface{}, error) { +func rawMessage(data []byte, err error) (any, error) { if err != nil { return nil, trace.Wrap(err) } @@ -468,7 +468,7 @@ validateGithubAuthRequest validates Github auth callback redirect Success response: githubAuthRawResponse */ -func (s *APIServer) validateGithubAuthCallback(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) validateGithubAuthCallback(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { var req validateGithubAuthCallbackReq if err := httplib.ReadJSON(r, &req); err != nil { return nil, trace.Wrap(err) @@ -534,7 +534,7 @@ func (*APIServer) getNamespace(_ *ServerWithRoles, _ http.ResponseWriter, _ *htt }, nil } -func (s *APIServer) getClusterName(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) getClusterName(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { cn, err := auth.GetClusterName(r.Context()) if err != nil { return nil, trace.Wrap(err) @@ -548,7 +548,7 @@ type upsertTunnelConnectionRawReq struct { } // upsertTunnelConnection updates or inserts tunnel connection -func (s *APIServer) upsertTunnelConnection(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) upsertTunnelConnection(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { var req upsertTunnelConnectionRawReq if err := httplib.ReadJSON(r, &req); err != nil { return nil, trace.Wrap(err) @@ -564,7 +564,7 @@ func (s *APIServer) upsertTunnelConnection(auth *ServerWithRoles, w http.Respons } // getTunnelConnections returns a list of tunnel connections from a cluster -func (s *APIServer) getTunnelConnections(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) getTunnelConnections(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { conns, err := auth.GetTunnelConnections(p.ByName("cluster")) if err != nil { return nil, trace.Wrap(err) @@ -581,7 +581,7 @@ func (s *APIServer) getTunnelConnections(auth *ServerWithRoles, w http.ResponseW } // getAllTunnelConnections returns a list of tunnel connections from a cluster -func (s *APIServer) getAllTunnelConnections(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) getAllTunnelConnections(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { conns, err := auth.GetAllTunnelConnections() if err != nil { return nil, trace.Wrap(err) @@ -598,7 +598,7 @@ func (s *APIServer) getAllTunnelConnections(auth *ServerWithRoles, w http.Respon } // deleteTunnelConnection deletes tunnel connection by name -func (s *APIServer) deleteTunnelConnection(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) deleteTunnelConnection(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { err := auth.DeleteTunnelConnection(p.ByName("cluster"), p.ByName("conn")) if err != nil { return nil, trace.Wrap(err) @@ -607,7 +607,7 @@ func (s *APIServer) deleteTunnelConnection(auth *ServerWithRoles, w http.Respons } // deleteTunnelConnections deletes all tunnel connections for cluster -func (s *APIServer) deleteTunnelConnections(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) deleteTunnelConnections(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { err := auth.DeleteTunnelConnections(p.ByName("cluster")) if err != nil { return nil, trace.Wrap(err) @@ -616,7 +616,7 @@ func (s *APIServer) deleteTunnelConnections(auth *ServerWithRoles, w http.Respon } // deleteAllTunnelConnections deletes all tunnel connections -func (s *APIServer) deleteAllTunnelConnections(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { +func (s *APIServer) deleteAllTunnelConnections(auth *ServerWithRoles, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (any, error) { err := auth.DeleteAllTunnelConnections() if err != nil { return nil, trace.Wrap(err) @@ -624,6 +624,6 @@ func (s *APIServer) deleteAllTunnelConnections(auth *ServerWithRoles, w http.Res return message("ok"), nil } -func message(msg string) map[string]interface{} { - return map[string]interface{}{"message": msg} +func message(msg string) map[string]any { + return map[string]any{"message": msg} } diff --git a/lib/auth/apiserver_test.go b/lib/auth/apiserver_test.go index b330f20a3d1..9ea6fbbaf58 100644 --- a/lib/auth/apiserver_test.go +++ b/lib/auth/apiserver_test.go @@ -106,7 +106,6 @@ func TestUpsertServer(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.desc, func(t *testing.T) { t.Parallel() // Set up backend to upsert servers into. diff --git a/lib/auth/auth.go b/lib/auth/auth.go index d581521065e..0f2e428134a 100644 --- a/lib/auth/auth.go +++ b/lib/auth/auth.go @@ -1729,10 +1729,7 @@ func (a *Server) doInstancePeriodics(ctx context.Context) { // on the side of slowness, which is preferable for this kind of periodic. instanceRate := slowRate if ci := a.inventory.ConnectedInstances(); ci > 0 { - localDynamicRate := dynamicPeriod / time.Duration(ci) - if localDynamicRate < fastRate { - localDynamicRate = fastRate - } + localDynamicRate := max(dynamicPeriod/time.Duration(ci), fastRate) if localDynamicRate < instanceRate { instanceRate = localDynamicRate @@ -4787,6 +4784,7 @@ func (a *Server) GenerateHostCerts(ctx context.Context, req *proto.HostCertsRequ if err != nil { return nil, trace.Wrap(err) } + req.AdditionalPrincipals = utils.ReplaceInSlice( req.AdditionalPrincipals, defaults.AnyAddress, @@ -4910,7 +4908,7 @@ func (a *Server) GenerateHostCerts(ctx context.Context, req *proto.HostCertsRequ PublicKey: cryptoPubKey, Subject: subject, NotAfter: a.clock.Now().UTC().Add(defaults.CATTL), - DNSNames: append([]string{}, req.AdditionalPrincipals...), + DNSNames: slices.Clone(req.AdditionalPrincipals), } // API requests need to specify a DNS name, which must be present in the certificate's DNS Names. @@ -7702,7 +7700,7 @@ func mergeKeySets(a, b types.CAKeySet) types.CAKeySet { func (a *Server) addAdditionalTrustedKeysAtomic(ctx context.Context, ca types.CertAuthority, newKeys types.CAKeySet, needsUpdate func(types.CertAuthority) (bool, error)) error { const maxIterations = 64 - for i := 0; i < maxIterations; i++ { + for range maxIterations { if update, err := needsUpdate(ca); err != nil || !update { return trace.Wrap(err) } diff --git a/lib/auth/auth_login_test.go b/lib/auth/auth_login_test.go index 24a2e31ab91..60b31a3f9dc 100644 --- a/lib/auth/auth_login_test.go +++ b/lib/auth/auth_login_test.go @@ -197,7 +197,6 @@ func TestServer_CreateAuthenticateChallenge_authPreference(t *testing.T) { }, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() @@ -289,7 +288,6 @@ func TestCreateAuthenticateChallenge_WithUserCredentials(t *testing.T) { } for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() res, err := srv.Auth().CreateAuthenticateChallenge(ctx, &proto.CreateAuthenticateChallengeRequest{ @@ -382,7 +380,6 @@ func TestCreateAuthenticateChallenge_WithRecoveryStartToken(t *testing.T) { } for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() res, err := srv.Auth().CreateAuthenticateChallenge(ctx, tc.getRequest()) @@ -598,7 +595,6 @@ func TestCreateAuthenticateChallenge_mfaVerification(t *testing.T) { }, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() @@ -704,7 +700,6 @@ func TestCreateRegisterChallenge(t *testing.T) { }, } for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() res, err := srv.Auth().CreateRegisterChallenge(ctx, &proto.CreateRegisterChallengeRequest{ @@ -1074,7 +1069,6 @@ func TestServer_AuthenticateUser_mfaDevices(t *testing.T) { {name: "OK Webauthn device", solveChallenge: mfa.WebDev.SolveAuthn}, } for _, test := range tests { - test := test // makeRun is used to test both SSH and Web login by switching the // authenticate function. makeRun := func(authenticate func(*Server, authclient.AuthenticateUserRequest) error) func(t *testing.T) { @@ -1807,7 +1801,7 @@ func TestServer_Authenticate_headless(t *testing.T) { update: func(ha *types.HeadlessAuthentication, mfa *types.MFADevice) { ha.State = types.HeadlessAuthenticationState_HEADLESS_AUTHENTICATION_STATE_APPROVED }, - assertError: func(t require.TestingT, err error, i ...interface{}) { + assertError: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err), "expected access denied error but got %v", err) }, }, { @@ -1816,13 +1810,13 @@ func TestServer_Authenticate_headless(t *testing.T) { update: func(ha *types.HeadlessAuthentication, mfa *types.MFADevice) { ha.State = types.HeadlessAuthenticationState_HEADLESS_AUTHENTICATION_STATE_DENIED }, - assertError: func(t require.TestingT, err error, i ...interface{}) { + assertError: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsAccessDenied(err), "expected access denied error but got %v", err) }, }, { name: "NOK timeout", timeout: 100 * time.Millisecond, - assertError: func(t require.TestingT, err error, i ...interface{}) { + assertError: func(t require.TestingT, err error, i ...any) { require.ErrorIs(t, err, context.DeadlineExceeded) }, }, diff --git a/lib/auth/auth_test.go b/lib/auth/auth_test.go index 1c0803c10a7..979d4ddc6b6 100644 --- a/lib/auth/auth_test.go +++ b/lib/auth/auth_test.go @@ -1144,8 +1144,7 @@ func TestLocalControlStream(t *testing.T) { const serverID = "test-server" t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() s := newAuthSuite(t) @@ -2249,7 +2248,6 @@ func TestServer_AugmentWebSessionCertificates(t *testing.T) { }, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() @@ -2902,7 +2900,7 @@ func TestGenerateUserCertWithHardwareKeySupport(t *testing.T) { cap: types.AuthPreferenceSpecV2{ RequireMFAType: types.RequireMFAType_HARDWARE_KEY_TOUCH, }, - assertErr: func(t require.TestingT, err error, i ...interface{}) { + assertErr: func(t require.TestingT, err error, i ...any) { require.Error(t, err, "expected private key policy error but got %v", err) require.True(t, keys.IsPrivateKeyPolicyError(err), "expected private key policy error but got %v", err) }, @@ -2915,7 +2913,7 @@ func TestGenerateUserCertWithHardwareKeySupport(t *testing.T) { PrivateKeyPolicy: keys.PrivateKeyPolicyHardwareKey, SerialNumber: 12345678, }, - assertErr: func(t require.TestingT, err error, i ...interface{}) { + assertErr: func(t require.TestingT, err error, i ...any) { require.Error(t, err, "expected private key policy error but got %v", err) require.True(t, keys.IsPrivateKeyPolicyError(err), "expected private key policy error but got %v", err) }, @@ -2948,7 +2946,7 @@ func TestGenerateUserCertWithHardwareKeySupport(t *testing.T) { PrivateKeyPolicy: keys.PrivateKeyPolicyHardwareKeyTouch, SerialNumber: 1234, }, - assertErr: func(t require.TestingT, err error, i ...interface{}) { + assertErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsBadParameter(err), "expected bad parameter error but got %v", err) require.ErrorContains(t, err, "unknown hardware key") }, @@ -2982,7 +2980,7 @@ func TestGenerateUserCertWithHardwareKeySupport(t *testing.T) { PrivateKeyPolicy: keys.PrivateKeyPolicyHardwareKeyTouch, SerialNumber: 87654321, }, - assertErr: func(t require.TestingT, err error, i ...interface{}) { + assertErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsBadParameter(err), "expected bad parameter error but got %v", err) require.ErrorContains(t, err, "unknown hardware key") }, @@ -3001,7 +2999,7 @@ func TestGenerateUserCertWithHardwareKeySupport(t *testing.T) { PrivateKeyPolicy: keys.PrivateKeyPolicyHardwareKeyTouch, SerialNumber: 12345678, }, - assertErr: func(t require.TestingT, err error, i ...interface{}) { + assertErr: func(t require.TestingT, err error, i ...any) { require.True(t, trace.IsBadParameter(err), "expected bad parameter error but got %v", err) require.ErrorContains(t, err, "no known hardware keys") }, @@ -3799,7 +3797,6 @@ func TestGetMFADevices_WithToken(t *testing.T) { }, } for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() tokenID := "test-token-not-found" @@ -3946,7 +3943,7 @@ func TestFilterResources(t *testing.T) { const resourceCount = 100 nodes := make([]types.ResourceWithLabels, 0, resourceCount) - for i := 0; i < resourceCount; i++ { + for range resourceCount { s, err := types.NewServer(uuid.NewString(), types.KindNode, types.ServerSpecV2{}) require.NoError(t, err) nodes = append(nodes, s) @@ -3962,7 +3959,7 @@ func TestFilterResources(t *testing.T) { { name: "ListResources fails", cache: mockCache{resourcesError: fail}, - errorAssertion: func(t require.TestingT, err error, i ...interface{}) { + errorAssertion: func(t require.TestingT, err error, i ...any) { require.Error(t, err, i...) require.ErrorIs(t, err, fail) }, @@ -3978,7 +3975,7 @@ func TestFilterResources(t *testing.T) { { name: "fatal errors are propagated", cache: mockCache{resources: nodes}, - errorAssertion: func(t require.TestingT, err error, i ...interface{}) { + errorAssertion: func(t require.TestingT, err error, i ...any) { require.Error(t, err, i...) require.ErrorIs(t, err, fail) }, @@ -3997,7 +3994,6 @@ func TestFilterResources(t *testing.T) { } for _, tt := range cases { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() @@ -4516,7 +4512,7 @@ func TestCleanupNotifications(t *testing.T) { var createdNotifications []notificationInfo createNotifications := func(username string, count int, expiryDuration time.Duration) { - for i := 0; i < count; i++ { + for i := range count { var id string if username != "" { notification := newUserNotificationWithExpiry(t, username, fmt.Sprintf("%s-notification-%d", username, i+1), timestamppb.New(fakeClock.Now().Add(expiryDuration))) diff --git a/lib/auth/auth_with_roles.go b/lib/auth/auth_with_roles.go index d122dd90fa8..f60820fc4c2 100644 --- a/lib/auth/auth_with_roles.go +++ b/lib/auth/auth_with_roles.go @@ -850,7 +850,7 @@ Outer: // one of the specified : pairs (e.g. `node:list|token:create` // would be satisfied by either a user that can list nodes *or* create tokens). Verbs: - for _, s := range strings.Split(alert.Metadata.Labels[types.AlertVerbPermit], "|") { + for s := range strings.SplitSeq(alert.Metadata.Labels[types.AlertVerbPermit], "|") { rv := strings.Split(s, ":") if len(rv) != 2 { continue Verbs @@ -875,7 +875,7 @@ Outer: sups := make(map[string]types.AlertSeverity) for _, alert := range alerts { - for _, id := range strings.Split(alert.Metadata.Labels[types.AlertSupersedes], ",") { + for id := range strings.SplitSeq(alert.Metadata.Labels[types.AlertSupersedes], ",") { if sups[id] < alert.Spec.Severity { sups[id] = alert.Spec.Severity } diff --git a/lib/auth/auth_with_roles_test.go b/lib/auth/auth_with_roles_test.go index e4f37bee5ee..304ef843d37 100644 --- a/lib/auth/auth_with_roles_test.go +++ b/lib/auth/auth_with_roles_test.go @@ -142,7 +142,6 @@ func TestGenerateUserCerts_MFAVerifiedFieldSet(t *testing.T) { }, }, } { - test := test t.Run(test.desc, func(t *testing.T) { mfaResponse := test.getMFAResponse() certs, err := client.GenerateUserCerts(context.Background(), proto.UserCertsRequest{ @@ -2009,7 +2008,7 @@ func BenchmarkListNodes(b *testing.B) { srv := newTestTLSServer(b) var ids []string - for i := 0; i < roleCount; i++ { + for range roleCount { ids = append(ids, uuid.New().String()) } @@ -2017,7 +2016,7 @@ func BenchmarkListNodes(b *testing.B) { var hiddenNodes int // Create test nodes. - for i := 0; i < nodeCount; i++ { + for i := range nodeCount { name := uuid.New().String() id := ids[i%len(ids)] if id == "hidden" { @@ -2200,7 +2199,7 @@ func TestGetAndList_Nodes(t *testing.T) { srv := newTestTLSServer(t) // Create test nodes. - for i := 0; i < 10; i++ { + for range 10 { name := uuid.New().String() node, err := types.NewServerWithLabels( name, @@ -2323,8 +2322,7 @@ func TestStreamSessionEventsRBAC(t *testing.T) { clt, err := srv.NewClient(identity) require.NoError(t, err) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() _, errC := clt.StreamSessionEvents(ctx, "foo", 0) select { case err := <-errC: @@ -2338,8 +2336,7 @@ func TestStreamSessionEventsRBAC(t *testing.T) { func TestStreamSessionEvents_User(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() srv := newTestTLSServer(t) username := "user" @@ -2374,8 +2371,7 @@ func TestStreamSessionEvents_User(t *testing.T) { func TestStreamSessionEvents_Builtin(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() srv := newTestTLSServer(t) identity := TestBuiltin(types.RoleProxy) @@ -2859,7 +2855,7 @@ func TestGetAndList_DatabaseServers(t *testing.T) { srv := newTestTLSServer(t) // Create test databases. - for i := 0; i < 5; i++ { + for i := range 5 { name := fmt.Sprintf("db-%d", i) database, err := types.NewDatabaseV3( types.Metadata{ @@ -2998,7 +2994,7 @@ func TestGetAndList_ApplicationServers(t *testing.T) { srv := newTestTLSServer(t) // Create test app servers. - for i := 0; i < 5; i++ { + for i := range 5 { name := fmt.Sprintf("app-%v", i) app, err := types.NewAppV3(types.Metadata{ Name: name, @@ -3178,7 +3174,7 @@ func TestListSAMLIdPServiceProviderAndListResources(t *testing.T) { ctx := context.Background() srv := newTestTLSServer(t) - for i := 0; i < 5; i++ { + for i := range 5 { name := fmt.Sprintf("saml-app-%v", i) sp, err := types.NewSAMLIdPServiceProvider(types.Metadata{ Name: name, @@ -3729,7 +3725,7 @@ func TestGetAndList_KubernetesServers(t *testing.T) { srv := newTestTLSServer(t) // Create test kube servers. - for i := 0; i < 5; i++ { + for range 5 { // insert legacy kube servers name := uuid.NewString() cluster, err := types.NewKubernetesClusterV3( @@ -3858,7 +3854,7 @@ func TestListDatabaseServices(t *testing.T) { numInitialResources := 5 // Create test Database Services. - for i := 0; i < numInitialResources; i++ { + for range numInitialResources { name := uuid.NewString() s, err := types.NewDatabaseServiceV1(types.Metadata{ Name: name, @@ -4001,7 +3997,7 @@ func TestListResources_NeedTotalCountFlag(t *testing.T) { srv := newTestTLSServer(t) // Create test nodes. - for i := 0; i < 3; i++ { + for range 3 { name := uuid.New().String() node, err := types.NewServerWithLabels( name, @@ -4054,7 +4050,7 @@ func TestListResources_SearchAsRoles(t *testing.T) { // Create test nodes. const numTestNodes = 3 - for i := 0; i < numTestNodes; i++ { + for i := range numTestNodes { name := fmt.Sprintf("node%d", i) node, err := types.NewServerWithLabels( name, @@ -4194,7 +4190,7 @@ func TestListResources_WithLogins(t *testing.T) { return srv.Auth().UnifiedResourceCache.IsInitialized() }, 5*time.Second, 200*time.Millisecond, "unified resource watcher never initialized") - for i := 0; i < 5; i++ { + for i := range 5 { name := uuid.New().String() node, err := types.NewServerWithLabels( name, @@ -4337,7 +4333,7 @@ func TestGetAndList_WindowsDesktops(t *testing.T) { srv := newTestTLSServer(t) // Create test desktops. - for i := 0; i < 5; i++ { + for range 5 { name := uuid.New().String() desktop, err := types.NewWindowsDesktopV3(name, map[string]string{"name": name}, types.WindowsDesktopSpecV3{Addr: "_", HostID: "_"}) @@ -4857,7 +4853,7 @@ func TestListResources_SortAndDeduplicate(t *testing.T) { name: "KindDatabaseServer", kind: types.KindDatabaseServer, insertResources: func() { - for i := 0; i < len(names); i++ { + for i := range names { db, err := types.NewDatabaseServerV3(types.Metadata{ Name: fmt.Sprintf("name-%v", i), }, types.DatabaseServerSpecV3{ @@ -4883,7 +4879,7 @@ func TestListResources_SortAndDeduplicate(t *testing.T) { name: "KindAppServer", kind: types.KindAppServer, insertResources: func() { - for i := 0; i < len(names); i++ { + for i := range names { server, err := types.NewAppServerV3(types.Metadata{ Name: fmt.Sprintf("name-%v", i), }, types.AppServerSpecV3{ @@ -4900,7 +4896,7 @@ func TestListResources_SortAndDeduplicate(t *testing.T) { name: "KindWindowsDesktop", kind: types.KindWindowsDesktop, insertResources: func() { - for i := 0; i < len(names); i++ { + for i := range names { desktop, err := types.NewWindowsDesktopV3(names[i], nil, types.WindowsDesktopSpecV3{ Addr: "_", HostID: fmt.Sprintf("name-%v", i), @@ -4914,7 +4910,7 @@ func TestListResources_SortAndDeduplicate(t *testing.T) { name: "KindKubernetesCluster", kind: types.KindKubernetesCluster, insertResources: func() { - for i := 0; i < len(names); i++ { + for i := range names { kube, err := types.NewKubernetesClusterV3(types.Metadata{ Name: names[i], @@ -5000,7 +4996,7 @@ func TestListResources_WithRoles(t *testing.T) { // inserts a pool nodes with different labels insertNodes := func(ctx context.Context, t *testing.T, srv *Server, nodeCount int, labels map[string]string) { - for i := 0; i < nodeCount; i++ { + for range nodeCount { name := uuid.NewString() addr := fmt.Sprintf("node-%s.example.com", name) @@ -5139,7 +5135,6 @@ func TestListResources_WithRoles(t *testing.T) { // ensure that a user can see the correct number of resources for their role(s) for _, tt := range cases { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() @@ -5215,7 +5210,7 @@ func TestListUnifiedResources_WithLogins(t *testing.T) { ) require.NoError(t, err) - for i := 0; i < 5; i++ { + for i := range 5 { name := uuid.New().String() node, err := types.NewServerWithLabels( name, @@ -5336,7 +5331,7 @@ func TestListUnifiedResources_IncludeRequestable(t *testing.T) { // Create test nodes. const numTestNodes = 3 - for i := 0; i < numTestNodes; i++ { + for i := range numTestNodes { name := fmt.Sprintf("node%d", i) node, err := types.NewServerWithLabels( name, @@ -5785,7 +5780,7 @@ func TestListUnifiedResources_KindsFilter(t *testing.T) { return srv.Auth().UnifiedResourceCache.IsInitialized() }, 5*time.Second, 200*time.Millisecond, "unified resource watcher never initialized") - for i := 0; i < 5; i++ { + for i := range 5 { name := uuid.New().String() node, err := types.NewServerWithLabels( name, @@ -5928,7 +5923,7 @@ func TestListUnifiedResources_WithSearch(t *testing.T) { }, 5*time.Second, 200*time.Millisecond, "unified resource watcher never initialized") names := []string{"vivi", "cloud", "aerith", "barret", "cid", "vivi2"} - for i := 0; i < 6; i++ { + for i := range 6 { name := names[i] node, err := types.NewServerWithLabels( name, @@ -6002,7 +5997,7 @@ func TestListUnifiedResources_MixedAccess(t *testing.T) { }, 5*time.Second, 200*time.Millisecond, "unified resource watcher never initialized") names := []string{"tifa", "cloud", "aerith", "baret", "cid", "tifa2"} - for i := 0; i < 6; i++ { + for i := range 6 { name := names[i] // add nodes @@ -6157,7 +6152,7 @@ func TestListUnifiedResources_WithPredicate(t *testing.T) { }, 5*time.Second, 200*time.Millisecond, "unified resource watcher never initialized") names := []string{"tifa", "cloud", "aerith", "baret", "cid", "tifa2"} - for i := 0; i < 6; i++ { + for i := range 6 { name := names[i] // add nodes @@ -7566,7 +7561,7 @@ func TestCreateSAMLIdPServiceProvider(t *testing.T) { }, allowRule: samlIdPRoleCondition(types.Labels{"env": []string{"dev"}}), eventCode: events.SAMLIdPServiceProviderCreateFailureCode, - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, errCreateVerbDenied) }, }, @@ -7584,7 +7579,7 @@ func TestCreateSAMLIdPServiceProvider(t *testing.T) { }, allowRule: samlIdPRoleCondition(types.Labels{"env": []string{"dev"}}, types.VerbCreate), eventCode: events.SAMLIdPServiceProviderCreateFailureCode, - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, errSAMLAppLabelsDenied) }, }, @@ -7603,7 +7598,7 @@ func TestCreateSAMLIdPServiceProvider(t *testing.T) { allowRule: samlIdPRoleCondition(types.Labels{"env": []string{"dev"}}, types.VerbCreate), denyRule: samlIdPRoleCondition(types.Labels{"env": []string{"dev"}}, types.VerbCreate), eventCode: events.SAMLIdPServiceProviderCreateFailureCode, - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, errCreateVerbDenied) }, }, @@ -7622,7 +7617,7 @@ func TestCreateSAMLIdPServiceProvider(t *testing.T) { allowRule: samlIdPRoleCondition(types.Labels{"env": []string{"dev"}}, types.VerbCreate), denyRule: samlIdPRoleCondition(types.Labels{"env": []string{"dev"}}), eventCode: events.SAMLIdPServiceProviderCreateFailureCode, - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, errSAMLAppLabelsDenied) }, }, @@ -7636,7 +7631,7 @@ func TestCreateSAMLIdPServiceProvider(t *testing.T) { EntityID: "sp1", }, eventCode: events.SAMLIdPServiceProviderCreateFailureCode, - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, errCreateVerbDenied) }, }, @@ -7737,7 +7732,7 @@ func TestUpdateSAMLIdPServiceProvider(t *testing.T) { }, allowRule: samlIdPRoleCondition(types.Labels{"env": []string{"dev"}}), eventCode: events.SAMLIdPServiceProviderUpdateFailureCode, - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, errUpdateVerbDenied) }, }, @@ -7755,7 +7750,7 @@ func TestUpdateSAMLIdPServiceProvider(t *testing.T) { }, allowRule: samlIdPRoleCondition(types.Labels{"env": []string{"dev"}}, types.VerbUpdate), eventCode: events.SAMLIdPServiceProviderUpdateFailureCode, - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, errSAMLAppLabelsDenied) }, }, @@ -7774,7 +7769,7 @@ func TestUpdateSAMLIdPServiceProvider(t *testing.T) { allowRule: samlIdPRoleCondition(types.Labels{"env": []string{"dev"}}, types.VerbUpdate), denyRule: samlIdPRoleCondition(types.Labels{}, types.VerbUpdate), eventCode: events.SAMLIdPServiceProviderUpdateFailureCode, - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, errUpdateVerbDenied) }, }, @@ -7793,7 +7788,7 @@ func TestUpdateSAMLIdPServiceProvider(t *testing.T) { allowRule: samlIdPRoleCondition(types.Labels{}, types.VerbUpdate), denyRule: samlIdPRoleCondition(types.Labels{"env": []string{"prod"}}), eventCode: events.SAMLIdPServiceProviderUpdateFailureCode, - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, errSAMLAppLabelsDenied) }, }, @@ -7807,7 +7802,7 @@ func TestUpdateSAMLIdPServiceProvider(t *testing.T) { EntityID: "sp1", }, eventCode: events.SAMLIdPServiceProviderUpdateFailureCode, - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, errUpdateVerbDenied) }, }, @@ -7852,14 +7847,14 @@ func TestCreateSAMLIdPServiceProviderInvalidInputs(t *testing.T) { name: "missing url scheme in acs input", entityID: "sp", acsURL: "sp", - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid scheme") }, }, { name: "missing url scheme for acs in ed", entityDescriptor: services.NewSAMLTestSPMetadata("sp", "sp"), - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid url scheme") }, }, @@ -7867,14 +7862,14 @@ func TestCreateSAMLIdPServiceProviderInvalidInputs(t *testing.T) { name: "http url scheme in acs", entityID: "sp", acsURL: "http://sp", - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid scheme") }, }, { name: "http url scheme for acs in ed", entityDescriptor: services.NewSAMLTestSPMetadata("sp", "http://sp"), - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "unsupported ACS bindings") }, }, @@ -7882,14 +7877,14 @@ func TestCreateSAMLIdPServiceProviderInvalidInputs(t *testing.T) { name: "unsupported scheme in acs", entityID: "sp", acsURL: "gopher://sp", - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid scheme") }, }, { name: "unsupported scheme for acs in ed", entityDescriptor: services.NewSAMLTestSPMetadata("sp", "gopher://sp"), - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid url scheme") }, }, @@ -7897,14 +7892,14 @@ func TestCreateSAMLIdPServiceProviderInvalidInputs(t *testing.T) { name: "invalid character in acs", entityID: "sp", acsURL: "https://sp>", - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "unsupported character") }, }, { name: "invalid character in acs in ed", entityDescriptor: services.NewSAMLTestSPMetadata("sp", "https://sp>"), - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "unsupported ACS bindings") }, }, @@ -7913,7 +7908,7 @@ func TestCreateSAMLIdPServiceProviderInvalidInputs(t *testing.T) { entityID: "sp", acsURL: "https://sp", relayState: "default_state"), - errAssertion: func(t require.TestingT, err error, i ...interface{}) { + errAssertion: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "unsupported ACS bindings") }, }, @@ -7994,7 +7989,7 @@ func TestUpdateSAMLIdPServiceProviderInvalidInputs(t *testing.T) { name: "invalid character in relay state", entityDescriptor: services.NewSAMLTestSPMetadata("https://sp", "https://sp"), relayState: "default_state 0 && b.overflow[i].expires.After(now) { break diff --git a/lib/utils/fanoutbuffer/buffer_test.go b/lib/utils/fanoutbuffer/buffer_test.go index 6ce37b36f37..fba32731a82 100644 --- a/lib/utils/fanoutbuffer/buffer_test.go +++ b/lib/utils/fanoutbuffer/buffer_test.go @@ -85,7 +85,7 @@ func concurrentFanout(ctx context.Context, t require.TestingT, events int, curso defer buf.Close() results := make(chan error, cursors) - for i := 0; i < cursors; i++ { + for range cursors { cursor := buf.NewCursor() go func() { var result error @@ -126,7 +126,7 @@ func concurrentFanout(ctx context.Context, t require.TestingT, events int, curso buf.Append(outbuf[:]...) } - for i := 0; i < cursors; i++ { + for range cursors { select { case err := <-results: require.NoError(t, err) @@ -162,7 +162,7 @@ func TestBasics(t *testing.T) { require.Zero(t, n) // continuously stream items - for i := 0; i < bufSize; i++ { + for i := range bufSize { buf.Append(i) n, err := cursor.Read(ctx, rbuf[:]) @@ -173,7 +173,7 @@ func TestBasics(t *testing.T) { var input []int // fill and drain buffer - for i := 0; i < bufSize; i++ { + for i := range bufSize { input = append(input, i) } @@ -189,7 +189,7 @@ func TestBasics(t *testing.T) { // generate new input that causes overflow/backlog input = nil - for i := 0; i < bufSize*2; i++ { + for i := range bufSize * 2 { input = append(input, i) } buf.Append(input...) @@ -203,7 +203,7 @@ func TestBasics(t *testing.T) { require.Equal(t, input, output) // overflow and then exceed grace-period - for i := 0; i < bufSize*2; i++ { + for i := range bufSize * 2 { buf.Append(i) } clock.Advance(gracePeriod * 2) @@ -217,8 +217,7 @@ func TestBasics(t *testing.T) { } func TestCursorFinalizer(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() buf := NewBuffer[int](Config{}) defer buf.Close() diff --git a/lib/utils/fields.go b/lib/utils/fields.go index e076990b2c1..739badf7df3 100644 --- a/lib/utils/fields.go +++ b/lib/utils/fields.go @@ -28,7 +28,7 @@ import ( ) // Fields represents a generic string-keyed map. -type Fields map[string]interface{} +type Fields map[string]any // GetString returns a string representation of a field. func (f Fields) GetString(key string) string { @@ -49,7 +49,7 @@ func (f Fields) GetStrings(key string) []string { if ok { return strings } - slice, _ := val.([]interface{}) + slice, _ := val.([]any) res := make([]string, 0, len(slice)) for _, v := range slice { s, ok := v.(string) diff --git a/lib/utils/fields_test.go b/lib/utils/fields_test.go index d96ee1fdf9c..be0eb0cc921 100644 --- a/lib/utils/fields_test.go +++ b/lib/utils/fields_test.go @@ -33,7 +33,7 @@ func TestFields(t *testing.T) { now := time.Now().Round(time.Minute) sliceString := []string{"test", "string", "slice"} - sliceInterface := []interface{}{"test", "string", "slice"} + sliceInterface := []any{"test", "string", "slice"} f := Fields{ "one": 1, "name": "vincent", diff --git a/lib/utils/fncache_test.go b/lib/utils/fncache_test.go index 4e3e5341975..859cc393923 100644 --- a/lib/utils/fncache_test.go +++ b/lib/utils/fncache_test.go @@ -101,8 +101,7 @@ func TestFnCacheConcurrentReads(t *testing.T) { const workers = 100 t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() // set up a chage that won't ttl out values during the test cache, err := NewFnCache(FnCacheConfig{TTL: time.Hour}) @@ -110,7 +109,7 @@ func TestFnCacheConcurrentReads(t *testing.T) { results := make(chan result, workers) - for i := 0; i < workers; i++ { + for i := range workers { go func(n int) { val, err := FnCacheGet(ctx, cache, "key", func(context.Context) (any, error) { // return a unique value for each worker so that we can verify whether @@ -127,7 +126,7 @@ func TestFnCacheConcurrentReads(t *testing.T) { val := first.val.(string) require.NotEmpty(t, val) - for i := 0; i < (workers - 1); i++ { + for range workers - 1 { r := <-results require.NoError(t, r.err) require.Equal(t, val, r.val.(string)) @@ -138,8 +137,7 @@ func TestFnCacheConcurrentReads(t *testing.T) { func TestFnCacheExpiry(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() clock := clockwork.NewFakeClock() @@ -171,7 +169,7 @@ func TestFnCacheExpiry(t *testing.T) { require.True(t, get()) // subsequent gets use the cached value - for i := 0; i < 20; i++ { + for range 20 { require.False(t, get()) } @@ -252,7 +250,7 @@ func testFnCacheFuzzy(t *testing.T, ttl time.Duration, delay time.Duration) { var wg sync.WaitGroup // spawn workers - for w := int64(0); w < workers; w++ { + for range workers { wg.Add(1) go func() { defer wg.Done() @@ -376,8 +374,7 @@ func TestFnCacheContext(t *testing.T) { func TestFnCacheReloadOnErr(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() cache, err := NewFnCache(FnCacheConfig{ TTL: time.Minute, @@ -389,7 +386,7 @@ func TestFnCacheReloadOnErr(t *testing.T) { // test synchronous case, all sad path loads should result in // calls to loadfn. - for i := 0; i < 100; i++ { + for range 100 { FnCacheGet(ctx, cache, "happy", func(ctx context.Context) (string, error) { happy.Add(1) return "yay!", nil @@ -405,7 +402,7 @@ func TestFnCacheReloadOnErr(t *testing.T) { // test concurrent case. some "sad" loads should overlap now. var wg sync.WaitGroup - for i := 0; i < 100; i++ { + for range 100 { wg.Add(2) go func() { defer wg.Done() @@ -430,8 +427,7 @@ func TestFnCacheReloadOnErr(t *testing.T) { func TestFnCacheEviction(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() clock := clockwork.NewFakeClock() @@ -464,7 +460,7 @@ func TestFnCacheEviction(t *testing.T) { require.Equal(t, "test", out2) // Assert that eviction does not occur prematurely. - for i := 0; i < 6; i++ { + for range 6 { clock.Advance(10 * time.Minute) cache.RemoveExpired() @@ -507,7 +503,7 @@ func TestFnCacheEviction(t *testing.T) { // Shutdown the cache and validate all items are expired. cache.Shutdown(context.Background()) timeout := time.After(10 * time.Second) - for i := 0; i < 2; i++ { + for range 2 { select { case expired := <-expiredC: switch k := expired.k.(type) { @@ -538,8 +534,7 @@ func TestFnCacheEviction(t *testing.T) { func TestFnCacheRemove(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() type item struct { k any @@ -585,8 +580,7 @@ func TestFnCacheRemove(t *testing.T) { func TestFnCacheSet(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() clock := clockwork.NewFakeClock() type item struct { diff --git a/lib/utils/fs.go b/lib/utils/fs.go index 6831a4a482b..76e528d6ebc 100644 --- a/lib/utils/fs.go +++ b/lib/utils/fs.go @@ -339,7 +339,7 @@ func removeSecure(filePath string, fi os.FileInfo) error { if runtime.GOOS == "windows" { // Windows can't unlink the file before overwriting. if f != nil { - for i := 0; i < 3; i++ { + for range 3 { if err := overwriteFile(f, fi); err != nil { break } @@ -352,7 +352,7 @@ func removeSecure(filePath string, fi os.FileInfo) error { } else { removeErr := os.Remove(filePath) if f != nil { - for i := 0; i < 3; i++ { + for range 3 { if err := overwriteFile(f, fi); err != nil { break } diff --git a/lib/utils/gcp/gcp_test.go b/lib/utils/gcp/gcp_test.go index bcf2b71e200..ef7f6d6cc9b 100644 --- a/lib/utils/gcp/gcp_test.go +++ b/lib/utils/gcp/gcp_test.go @@ -130,7 +130,7 @@ func TestProjectIDFromServiceAccountName(t *testing.T) { name: "empty string", serviceAccount: "", want: "", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid service account format: empty string received") }, }, @@ -138,7 +138,7 @@ func TestProjectIDFromServiceAccountName(t *testing.T) { name: "missing @", serviceAccount: "test", want: "", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid service account format: missing @") }, }, @@ -146,7 +146,7 @@ func TestProjectIDFromServiceAccountName(t *testing.T) { name: "missing domain after @", serviceAccount: "test@", want: "", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid service account format: missing .iam.gserviceaccount.com after @") }, }, @@ -154,7 +154,7 @@ func TestProjectIDFromServiceAccountName(t *testing.T) { name: "missing user before @", serviceAccount: "@project", want: "", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid service account format: empty user") }, }, @@ -162,7 +162,7 @@ func TestProjectIDFromServiceAccountName(t *testing.T) { name: "missing domain", serviceAccount: "test@myproject-123456", want: "", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid service account format: missing .iam.gserviceaccount.com after @") }, }, @@ -170,7 +170,7 @@ func TestProjectIDFromServiceAccountName(t *testing.T) { name: "wrong domain suffix", serviceAccount: "test@myproject-123456.iam.gserviceaccount", want: "", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid service account format: expected suffix \"iam.gserviceaccount.com\", got \"iam.gserviceaccount\"") }, }, @@ -178,7 +178,7 @@ func TestProjectIDFromServiceAccountName(t *testing.T) { name: "missing project id", serviceAccount: "test@.iam.gserviceaccount.com", want: "", - wantErr: func(t require.TestingT, err error, i ...interface{}) { + wantErr: func(t require.TestingT, err error, i ...any) { require.ErrorContains(t, err, "invalid service account format: missing project ID") }, }, diff --git a/lib/utils/genmap/genmap_test.go b/lib/utils/genmap/genmap_test.go index 3f5d7f4ee2e..986dc13f2b2 100644 --- a/lib/utils/genmap/genmap_test.go +++ b/lib/utils/genmap/genmap_test.go @@ -33,8 +33,7 @@ import ( func TestCaching(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() // set up a genmap with a long regen interval var counter atomic.Uint64 @@ -50,7 +49,7 @@ func TestCaching(t *testing.T) { // verify that many concurrent calls result in only a single call to // the underlying generator. var eg errgroup.Group - for i := 0; i < 100; i++ { + for range 100 { eg.Go(func() error { n, err := gm.Get(ctx, "some-key") if err != nil { @@ -82,8 +81,7 @@ func TestCaching(t *testing.T) { func TestConcurrentTermination(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() // set up a genmap with a short regen interval var counter atomic.Uint64 @@ -135,8 +133,7 @@ func TestConcurrentTermination(t *testing.T) { func TestBackground(t *testing.T) { t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() // set up a genmap with a short regen interval var counter atomic.Uint64 @@ -159,7 +156,7 @@ func TestBackground(t *testing.T) { // verify that background regeneration occurs multiple times timeout := time.After(time.Second * 30) - for i := 0; i < 4; i++ { + for range 4 { select { case <-gench: case <-timeout: diff --git a/lib/utils/host/hostusers.go b/lib/utils/host/hostusers.go index f8cbbd9dbda..6d9e1812460 100644 --- a/lib/utils/host/hostusers.go +++ b/lib/utils/host/hostusers.go @@ -210,7 +210,7 @@ func GetAllUsers() ([]string, int, error) { return nil, -1, trace.Wrap(err) } var users []string - for _, line := range bytes.Split(output, []byte("\n")) { + for line := range bytes.SplitSeq(output, []byte("\n")) { line := string(line) passwdEnt := strings.SplitN(line, ":", 2) if passwdEnt[0] != "" { diff --git a/lib/utils/hostid/hostid_test.go b/lib/utils/hostid/hostid_test.go index 208b95c292f..a10df48a6ac 100644 --- a/lib/utils/hostid/hostid_test.go +++ b/lib/utils/hostid/hostid_test.go @@ -51,7 +51,7 @@ func TestReadOrCreate(t *testing.T) { ids := make([]string, concurrency) barrier := make(chan struct{}) - for i := 0; i < concurrency; i++ { + for i := range concurrency { wg.Go(func() error { <-barrier id, err := hostid.ReadOrCreateFile( diff --git a/lib/utils/hostid/hostid_unix.go b/lib/utils/hostid/hostid_unix.go index cee2ee0b2df..24ddbf9c8df 100644 --- a/lib/utils/hostid/hostid_unix.go +++ b/lib/utils/hostid/hostid_unix.go @@ -89,7 +89,7 @@ func ReadOrCreateFile(dataDir string, opts ...func(*options)) (string, error) { return "", trace.Wrap(err) } - for i := 0; i < o.iterationLimit; i++ { + for range o.iterationLimit { if read, err := ReadFile(dataDir); err == nil { return read, nil } else if !trace.IsNotFound(err) { diff --git a/lib/utils/inmemory_fs.go b/lib/utils/inmemory_fs.go index 9726e52bda6..945424f4310 100644 --- a/lib/utils/inmemory_fs.go +++ b/lib/utils/inmemory_fs.go @@ -70,7 +70,7 @@ func (fi *InMemoryFile) IsDir() bool { // Sys is platform independent // InMemoryFile's implementation is no-op -func (fi *InMemoryFile) Sys() interface{} { +func (fi *InMemoryFile) Sys() any { return nil } diff --git a/lib/utils/interval/duration_test.go b/lib/utils/interval/duration_test.go index eed1df9cc0d..976dcec85bc 100644 --- a/lib/utils/interval/duration_test.go +++ b/lib/utils/interval/duration_test.go @@ -94,7 +94,7 @@ func TestVariableDurationIncDec(t *testing.T) { var wg sync.WaitGroup start := make(chan struct{}) wg.Add(100) - for i := 0; i < 100; i++ { + for i := range 100 { go func() { defer wg.Done() <-start @@ -112,7 +112,7 @@ func TestVariableDurationIncDec(t *testing.T) { start = make(chan struct{}) wg.Add(50) - for i := 0; i < 50; i++ { + for i := range 50 { go func() { defer wg.Done() <-start diff --git a/lib/utils/interval/interval_test.go b/lib/utils/interval/interval_test.go index 52a0692f91b..4ebd2f73d5f 100644 --- a/lib/utils/interval/interval_test.go +++ b/lib/utils/interval/interval_test.go @@ -40,7 +40,7 @@ func TestLastTick(t *testing.T) { require.False(t, ok) timeout := time.After(time.Second * 30) - for i := 0; i < 3; i++ { + for range 3 { clock.Advance(time.Minute) var tick time.Time @@ -68,7 +68,7 @@ func TestIntervalReset(t *testing.T) { var success, failure atomic.Uint64 var wg sync.WaitGroup - for i := 0; i < iterations; i++ { + for range iterations { wg.Add(1) go func() { defer wg.Done() @@ -83,7 +83,7 @@ func TestIntervalReset(t *testing.T) { start := time.Now() - for i := 0; i < 6; i++ { + for range 6 { select { case <-interval.Next(): failure.Add(1) @@ -126,7 +126,7 @@ func TestIntervalResetTo(t *testing.T) { var success, failure atomic.Uint64 var wg sync.WaitGroup - for i := 0; i < workers; i++ { + for range workers { wg.Add(1) go func() { defer wg.Done() @@ -138,7 +138,7 @@ func TestIntervalResetTo(t *testing.T) { start := time.Now() - for i := 0; i < ticks; i++ { + for range ticks { interval.ResetTo(shortDuration) <-interval.Next() } diff --git a/lib/utils/interval/multi.go b/lib/utils/interval/multi.go index f3c1fae80d7..fee1f5cd326 100644 --- a/lib/utils/interval/multi.go +++ b/lib/utils/interval/multi.go @@ -20,6 +20,7 @@ package interval import ( "errors" + "slices" "sync" "time" @@ -388,10 +389,8 @@ type pendingTicks[T comparable] struct { func (p *pendingTicks[T]) add(now time.Time, key T) { p.time = now - for _, k := range p.keys { - if k == key { - return - } + if slices.Contains(p.keys, key) { + return } p.keys = append(p.keys, key) } @@ -409,7 +408,7 @@ func (p *pendingTicks[T]) next() (tick Tick[T], ok bool) { func (p *pendingTicks[T]) remove(key T) { for idx := range p.keys { if p.keys[idx] == key { - p.keys = append(p.keys[:idx], p.keys[idx+1:]...) + p.keys = slices.Delete(p.keys, idx, idx+1) return } } diff --git a/lib/utils/interval/multi_test.go b/lib/utils/interval/multi_test.go index 56a9953a996..bd6bc32d196 100644 --- a/lib/utils/interval/multi_test.go +++ b/lib/utils/interval/multi_test.go @@ -40,7 +40,7 @@ func TestMultiIntervalReset(t *testing.T) { var wg sync.WaitGroup - for i := 0; i < iterations; i++ { + for range iterations { wg.Add(1) go func() { defer wg.Done() @@ -58,7 +58,7 @@ func TestMultiIntervalReset(t *testing.T) { start := time.Now() - for i := 0; i < 6; i++ { + for range 6 { select { case <-interval.Next(): failure.Add(1) @@ -114,7 +114,7 @@ func TestMultiIntervalBasics(t *testing.T) { var fast, slow, once int var prevT time.Time - for i := 0; i < 60; i++ { + for range 60 { tick := <-interval.Next() require.False(t, tick.Time.IsZero()) require.True(t, tick.Time.After(prevT) || tick.Time.Equal(prevT)) @@ -169,7 +169,7 @@ func TestMultiIntervalVariableDuration(t *testing.T) { var fooct, barct int var prevT time.Time - for i := 0; i < 60; i++ { + for range 60 { tick := <-interval.Next() require.False(t, tick.Time.IsZero()) require.True(t, tick.Time.After(prevT) || tick.Time.Equal(prevT)) @@ -197,7 +197,7 @@ func TestMultiIntervalVariableDuration(t *testing.T) { fooct = 0 barct = 0 - for i := 0; i < 60; i++ { + for range 60 { tick := <-interval.Next() switch tick.Key { case "foo": @@ -230,7 +230,7 @@ func TestMultiIntervalPush(t *testing.T) { defer interval.Stop() // verify that single-interval is working - for i := 0; i < 3; i++ { + for range 3 { tick := <-interval.Next() require.Equal(t, "foo", tick.Key) } @@ -243,7 +243,7 @@ func TestMultiIntervalPush(t *testing.T) { // aggregate rates of both sub-intervals var foo, bar int - for i := 0; i < 60; i++ { + for range 60 { tick := <-interval.Next() switch tick.Key { case "foo": @@ -272,7 +272,7 @@ func TestMultiIntervalPush(t *testing.T) { // aggregate new rates for both sub-intervals foo = 0 bar = 0 - for i := 0; i < 60; i++ { + for range 60 { tick := <-interval.Next() switch tick.Key { case "foo": @@ -308,7 +308,7 @@ func TestMultiIntervalFireNow(t *testing.T) { defer interval.Stop() // verify that only the 'fast' interval is firing - for i := 0; i < 10; i++ { + for range 10 { tick := <-interval.Next() require.Equal(t, "fast", tick.Key) } @@ -318,7 +318,7 @@ func TestMultiIntervalFireNow(t *testing.T) { // make sure that we observe slow interval firing var seenSlow bool - for i := 0; i < 60; i++ { + for range 60 { tick := <-interval.Next() if tick.Key == "slow" { seenSlow = true diff --git a/lib/utils/iterators_test.go b/lib/utils/iterators_test.go index c05252a153d..46a4f1bf962 100644 --- a/lib/utils/iterators_test.go +++ b/lib/utils/iterators_test.go @@ -144,10 +144,7 @@ func (s *mockBackendLister) List(ctx context.Context, pageSize int, pageToken st if err != nil { return nil, "", trace.Wrap(err) } - endIndex := startIndex + pageSize - if endIndex > len(s.items) { - endIndex = len(s.items) - } + endIndex := min(startIndex+pageSize, len(s.items)) items := s.items[startIndex:endIndex] if endIndex < len(s.items) { return items, strconv.Itoa(endIndex), nil diff --git a/lib/utils/jsontools.go b/lib/utils/jsontools.go index 0047305eb0c..cf9c354c376 100644 --- a/lib/utils/jsontools.go +++ b/lib/utils/jsontools.go @@ -61,7 +61,7 @@ func hasPrefix(buf []byte, prefix []byte) bool { // FastUnmarshal uses the json-iterator library for fast JSON unmarshalling. // Note, this function marshals floats with 6 digits precision. -func FastUnmarshal(data []byte, v interface{}) error { +func FastUnmarshal(data []byte, v any) error { iter := jsoniter.ConfigFastest.BorrowIterator(data) defer jsoniter.ConfigFastest.ReturnIterator(iter) @@ -94,7 +94,7 @@ var SafeConfigWithIndent = jsoniter.Config{ // FastMarshal uses the json-iterator library for fast JSON marshaling. // Note, this function unmarshals floats with 6 digits precision. -func FastMarshal(v interface{}) ([]byte, error) { +func FastMarshal(v any) ([]byte, error) { data, err := SafeConfig.Marshal(v) if err != nil { return nil, trace.Wrap(err) @@ -105,7 +105,7 @@ func FastMarshal(v interface{}) ([]byte, error) { // FastMarshal uses the json-iterator library for fast JSON marshaling // with indentation. Note, this function unmarshals floats with 6 digits precision. -func FastMarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { +func FastMarshalIndent(v any, prefix, indent string) ([]byte, error) { data, err := SafeConfig.MarshalIndent(v, prefix, indent) if err != nil { return nil, trace.Wrap(err) @@ -133,7 +133,7 @@ func WriteJSONObject[M ~map[K]V, K comparable, V any](w io.Writer, m M) error { } // WriteJSON marshals multiple documents as a JSON list with indentation. -func WriteJSON(w io.Writer, values interface{}) error { +func WriteJSON(w io.Writer, values any) error { encoder := json.NewEncoder(w) encoder.SetIndent("", " ") err := encoder.Encode(values) @@ -168,7 +168,7 @@ const yamlDocDelimiter = "---" // WriteYAML detects whether value is a list // and marshals multiple documents delimited by `---`, otherwise, marshals // a single value -func WriteYAML(w io.Writer, values interface{}) error { +func WriteYAML(w io.Writer, values any) error { if reflect.TypeOf(values).Kind() != reflect.Slice { return trace.Wrap(writeYAML(w, values)) } @@ -180,7 +180,7 @@ func WriteYAML(w io.Writer, values interface{}) error { } allDocs := func() bool { - for i := 0; i < slice.Len(); i++ { + for i := range slice.Len() { if !isDoc(slice.Index(i)) { return false } @@ -191,7 +191,7 @@ func WriteYAML(w io.Writer, values interface{}) error { return trace.Wrap(writeYAML(w, values)) } // second pass can marshal documents - for i := 0; i < slice.Len(); i++ { + for i := range slice.Len() { err := writeYAML(w, slice.Index(i).Interface()) if err != nil { return trace.Wrap(err) @@ -220,7 +220,7 @@ func isDoc(val reflect.Value) bool { } // writeYAML writes marshaled YAML to writer -func writeYAML(w io.Writer, values interface{}) error { +func writeYAML(w io.Writer, values any) error { data, err := yaml.Marshal(values) if err != nil { return trace.Wrap(err) @@ -230,11 +230,11 @@ func writeYAML(w io.Writer, values interface{}) error { } // ReadYAML can unmarshal a stream of documents, used in tests. -func ReadYAML(reader io.Reader) (interface{}, error) { +func ReadYAML(reader io.Reader) (any, error) { decoder := kyaml.NewYAMLOrJSONDecoder(reader, 32*1024) - var values []interface{} + var values []any for { - var val interface{} + var val any err := decoder.Decode(&val) if err != nil { if errors.Is(err, io.EOF) { diff --git a/lib/utils/jsontools_test.go b/lib/utils/jsontools_test.go index ecfd7cd3608..0e23a3fd3aa 100644 --- a/lib/utils/jsontools_test.go +++ b/lib/utils/jsontools_test.go @@ -44,7 +44,7 @@ func TestMarshalMapConsistency(t *testing.T) { compareTo, err := FastMarshal(value) require.NoError(t, err) - for i := 0; i < 100; i++ { + for i := range 100 { roundTrip := make(map[string]string) err := FastUnmarshal(compareTo, &roundTrip) require.NoError(t, err) @@ -101,7 +101,7 @@ func TestStreamJSONArray(t *testing.T) { require.Equal(t, numbers, numOut) var iterative []string - for i := 0; i < 100; i++ { + for i := range 100 { var iterBuf bytes.Buffer err = StreamJSONArray(stream.Slice(iterative), &iterBuf, false) require.NoError(t, err) diff --git a/lib/utils/linking.go b/lib/utils/linking.go index b6da605dbfe..15978d84fb5 100644 --- a/lib/utils/linking.go +++ b/lib/utils/linking.go @@ -83,7 +83,7 @@ func ParseWebLinks(response *http.Response) WebLinks { if links, ok := response.Header["Link"]; ok && len(links) > 0 { for _, lnk := range links { - for _, link := range strings.Split(lnk, ",") { + for link := range strings.SplitSeq(lnk, ",") { segments := strings.Split(strings.TrimSpace(link), ";") // link must at least have href and rel diff --git a/lib/utils/loadbalancer.go b/lib/utils/loadbalancer.go index 6a256e9113b..1352db5817b 100644 --- a/lib/utils/loadbalancer.go +++ b/lib/utils/loadbalancer.go @@ -25,6 +25,7 @@ import ( "log/slog" "math/rand/v2" "net" + "slices" "sync" "time" @@ -164,7 +165,7 @@ func (l *LoadBalancer) RemoveBackend(b NetAddr) error { defer l.Unlock() for i := range l.backends { if l.backends[i] == b { - l.backends = append(l.backends[:i], l.backends[i+1:]...) + l.backends = slices.Delete(l.backends, i, i+1) l.dropConnections(b) return nil } @@ -302,7 +303,7 @@ func (l *LoadBalancer) forward(conn net.Conn) error { }() var lastErr error - for i := 0; i < 2; i++ { + for range 2 { select { case err := <-messagesC: if err != nil && !errors.Is(err, io.EOF) { diff --git a/lib/utils/log/formatter_test.go b/lib/utils/log/formatter_test.go index 6c974b84857..a5448384a3a 100644 --- a/lib/utils/log/formatter_test.go +++ b/lib/utils/log/formatter_test.go @@ -362,7 +362,7 @@ func TestConcurrentOutput(t *testing.T) { var wg sync.WaitGroup ctx := context.Background() - for i := 0; i < 1000; i++ { + for i := range 1000 { wg.Add(1) go func(i int) { defer wg.Done() @@ -388,7 +388,7 @@ func allPossibleSubsets(in []string) [][]string { for subsetBits := 1; subsetBits < (1 << length); subsetBits++ { var subset []string - for object := 0; object < length; object++ { + for object := range length { if (subsetBits>>object)&1 == 1 { subset = append(subset, in[object]) } diff --git a/lib/utils/log/slog_handler_test.go b/lib/utils/log/slog_handler_test.go index c8ad8331491..172fdd950b0 100644 --- a/lib/utils/log/slog_handler_test.go +++ b/lib/utils/log/slog_handler_test.go @@ -67,7 +67,7 @@ func TestSlogTextHandler(t *testing.T) { results := func() []map[string]any { var ms []map[string]any - for _, line := range bytes.Split(buf.Bytes(), []byte{'\n'}) { + for line := range bytes.SplitSeq(buf.Bytes(), []byte{'\n'}) { if len(line) == 0 { continue } @@ -152,7 +152,7 @@ func TestSlogJSONHandler(t *testing.T) { results := func() []map[string]any { var ms []map[string]any - for _, line := range bytes.Split(buf.Bytes(), []byte{'\n'}) { + for line := range bytes.SplitSeq(buf.Bytes(), []byte{'\n'}) { if len(line) == 0 { continue } diff --git a/lib/utils/mcputils/id_tracker_test.go b/lib/utils/mcputils/id_tracker_test.go index 94743e31b08..e61319f4381 100644 --- a/lib/utils/mcputils/id_tracker_test.go +++ b/lib/utils/mcputils/id_tracker_test.go @@ -90,7 +90,7 @@ func BenchmarkIDTracker(b *testing.B) { idTracker, err := NewIDTracker(100) require.NoError(b, err) - for i := 0; i < 100; i++ { + for i := range 100 { idTracker.PushRequest(&JSONRPCRequest{ ID: mcp.NewRequestId(i), Method: mcp.MethodToolsList, diff --git a/lib/utils/mcputils/protocol.go b/lib/utils/mcputils/protocol.go index fadbcb75c1c..5a8d8537167 100644 --- a/lib/utils/mcputils/protocol.go +++ b/lib/utils/mcputils/protocol.go @@ -66,7 +66,7 @@ type baseJSONRPCMessage struct { // JSONRPC specifies the version of JSONRPC. JSONRPC string `json:"jsonrpc"` // ID is the ID for request and response. ID is nil for notification. - ID mcp.RequestId `json:"id,omitempty"` + ID mcp.RequestId `json:"id"` // Method is the request or notification method. Method is empty for response. Method mcp.MCPMethod `json:"method,omitempty"` // Params is the params for request and notification. @@ -126,7 +126,7 @@ type JSONRPCNotification struct { type JSONRPCRequest struct { JSONRPC string `json:"jsonrpc"` Method mcp.MCPMethod `json:"method"` - ID mcp.RequestId `json:"id,omitempty"` + ID mcp.RequestId `json:"id"` Params JSONRPCParams `json:"params,omitempty"` } diff --git a/lib/utils/mcputils/protocol_test.go b/lib/utils/mcputils/protocol_test.go index cf7a61045ae..acf0f4c7216 100644 --- a/lib/utils/mcputils/protocol_test.go +++ b/lib/utils/mcputils/protocol_test.go @@ -140,8 +140,8 @@ func TestJSONRPCResponse(t *testing.T) { Description: "Get current weather information for a location", InputSchema: mcp.ToolInputSchema{ Type: "object", - Properties: map[string]interface{}{ - "location": map[string]interface{}{ + Properties: map[string]any{ + "location": map[string]any{ "type": "string", "description": "City name or zip code", }, diff --git a/lib/utils/net.go b/lib/utils/net.go index 807fa5e9c56..de814e92214 100644 --- a/lib/utils/net.go +++ b/lib/utils/net.go @@ -58,7 +58,7 @@ func FindMatchingProxyDNS(requestHostnameOrFQDN string, proxyDNSNames []string) hostParts := strings.Split(normalizedRequestHost, ".") // Iterate over each possible suffix of requestHostOrFQDN parts - for start := 0; start < len(hostParts); start++ { + for start := range hostParts { possibleHost := strings.Join(hostParts[start:], ".") for _, proxyDNSName := range proxyDNSNames { // Normalize proxy DNS name by removing port if present diff --git a/lib/utils/oidc/issuer_test.go b/lib/utils/oidc/issuer_test.go index dd360ab937d..0b33489cecb 100644 --- a/lib/utils/oidc/issuer_test.go +++ b/lib/utils/oidc/issuer_test.go @@ -162,10 +162,10 @@ func TestIssuerForCluster(t *testing.T) { } } -func badParameterCheck(t require.TestingT, err error, msgAndArgs ...interface{}) { +func badParameterCheck(t require.TestingT, err error, msgAndArgs ...any) { require.True(t, trace.IsBadParameter(err), `expected "bad parameter", but got %v`, err) } -func notFoundCheck(t require.TestingT, err error, msgAndArgs ...interface{}) { +func notFoundCheck(t require.TestingT, err error, msgAndArgs ...any) { require.True(t, trace.IsNotFound(err), `expected "not found", but got %v`, err) } diff --git a/lib/utils/parse/parse_test.go b/lib/utils/parse/parse_test.go index 628d83c701f..7acfa50599e 100644 --- a/lib/utils/parse/parse_test.go +++ b/lib/utils/parse/parse_test.go @@ -211,10 +211,10 @@ func TestVariable(t *testing.T) { func TestInterpolate(t *testing.T) { t.Parallel() - errCheckIsNotFound := func(tt require.TestingT, err error, i ...interface{}) { + errCheckIsNotFound := func(tt require.TestingT, err error, i ...any) { require.True(tt, trace.IsNotFound(err), "expected not found error, got %v", err) } - errCheckIsBadParameter := func(tt require.TestingT, err error, i ...interface{}) { + errCheckIsBadParameter := func(tt require.TestingT, err error, i ...any) { require.True(tt, trace.IsBadParameter(err), "expected bad parameter error, got %v", err) } type result struct { diff --git a/lib/utils/proxyconn.go b/lib/utils/proxyconn.go index 030df414f71..08af05bf095 100644 --- a/lib/utils/proxyconn.go +++ b/lib/utils/proxyconn.go @@ -80,7 +80,7 @@ func ProxyConn(ctx context.Context, client, server io.ReadWriteCloser) error { }() var errors []error - for i := 0; i < 2; i++ { + for range 2 { select { case err := <-errCh: if err != nil && !IsOKNetworkError(err) { diff --git a/lib/utils/replace.go b/lib/utils/replace.go index 9477ef74219..edbe3977195 100644 --- a/lib/utils/replace.go +++ b/lib/utils/replace.go @@ -390,13 +390,8 @@ func RegexMatchesAny(inputs []string, expression string) (bool, error) { if err != nil { return false, trace.Wrap(err) } - for _, input := range inputs { - // Since the expression is always surrounded by ^ and $ this is an exact - // match for either a plain string (for example ^hello$) or for a regexp - // (for example ^hel*o$). - if expr.MatchString(input) { - return true, nil - } + if slices.ContainsFunc(inputs, expr.MatchString) { + return true, nil } return false, nil } diff --git a/lib/utils/roundrobin_test.go b/lib/utils/roundrobin_test.go index 9f865c51136..0d2bc44cae3 100644 --- a/lib/utils/roundrobin_test.go +++ b/lib/utils/roundrobin_test.go @@ -39,11 +39,11 @@ func TestRoundRobinConcurrent(t *testing.T) { var wg sync.WaitGroup - for w := 0; w < workers; w++ { + for range workers { wg.Add(1) go func() { defer wg.Done() - for r := 0; r < rounds; r++ { + for range rounds { if rr.Next() { tct.Add(1) } else { diff --git a/lib/utils/slice.go b/lib/utils/slice.go index 4009277ceef..fad8c71c08c 100644 --- a/lib/utils/slice.go +++ b/lib/utils/slice.go @@ -44,7 +44,7 @@ func NewSliceSyncPool(sliceSize int64) *SliceSyncPool { sliceSize: sliceSize, zeroSlice: make([]byte, sliceSize), } - s.New = func() interface{} { + s.New = func() any { slice := make([]byte, s.sliceSize) return &slice } @@ -67,7 +67,7 @@ func (s *SliceSyncPool) Zero(b []byte) { copy(b, s.zeroSlice[:len(b)]) } else { // use working, but less optimal implementation - for i := 0; i < len(b); i++ { + for i := range b { b[i] = 0 } } @@ -96,7 +96,7 @@ func NewBufferSyncPool(size int64) *BufferSyncPool { return &BufferSyncPool{ size: size, Pool: sync.Pool{ - New: func() interface{} { + New: func() any { return bytes.NewBuffer(make([]byte, size)) }, }, diff --git a/lib/utils/slice_test.go b/lib/utils/slice_test.go index 76f4a1dd1a2..617ea0b2a1c 100644 --- a/lib/utils/slice_test.go +++ b/lib/utils/slice_test.go @@ -31,7 +31,7 @@ func TestSlice(t *testing.T) { pool := NewSliceSyncPool(1024) // having a loop is not a guarantee that the same slice // will be reused, but a good enough bet - for i := 0; i < 10; i++ { + for range 10 { slice := pool.Get() require.Len(t, slice, 1024, "Returned slice should have zero len and values") for i := range slice { diff --git a/lib/utils/socks/socks.go b/lib/utils/socks/socks.go index afcd5bdacd4..df220751537 100644 --- a/lib/utils/socks/socks.go +++ b/lib/utils/socks/socks.go @@ -94,7 +94,7 @@ func readAuthenticationMethod(conn net.Conn) ([]byte, error) { // Read nmethods number of bytes from the connection return the list of // supported authentication methods to the caller. authMethods := make([]byte, nmethods) - for i := byte(0); i < nmethods; i++ { + for range nmethods { method, err := readByte(conn) if err != nil { return nil, trace.Wrap(err) diff --git a/lib/utils/sortcache/sortcache_test.go b/lib/utils/sortcache/sortcache_test.go index dd61f522de1..dd36d21339e 100644 --- a/lib/utils/sortcache/sortcache_test.go +++ b/lib/utils/sortcache/sortcache_test.go @@ -18,7 +18,6 @@ package sortcache import ( - "context" "slices" "strconv" "testing" @@ -319,7 +318,7 @@ func BenchmarkSortCache(b *testing.B) { cache.Put(r2) // seed cache with lots of additional resources to help simulate large reads - for i := 0; i < resourcesPerKind-1; i++ { + for i := range resourcesPerKind - 1 { cache.Put(resource{ kind: "node", name: strconv.Itoa(i), @@ -333,8 +332,7 @@ func BenchmarkSortCache(b *testing.B) { // set up a background process to inject concurrent writes in a fairly // tight loop (should roughly simulate the load generated by a background // event stream injecting updates into a replica). - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := b.Context() go func() { for { if ctx.Err() != nil { @@ -346,7 +344,7 @@ func BenchmarkSortCache(b *testing.B) { }() // set up a bunch of background concurrent read operations to simulate load. - for i := 0; i < concurrency; i++ { + for range concurrency { go func() { var n int buf := make([]resource, 0, resourcesPerKind) diff --git a/lib/utils/spreadwork/spreadwork.go b/lib/utils/spreadwork/spreadwork.go index 65c6044b62d..3fd4c2dfbd0 100644 --- a/lib/utils/spreadwork/spreadwork.go +++ b/lib/utils/spreadwork/spreadwork.go @@ -78,10 +78,7 @@ func ApplyOverTime[T any](ctx context.Context, conf ApplyOverTimeConfig, items [ defer ticker.Stop() maxBatches := int(conf.MaxDuration / conf.BatchInterval) - dynamicBatchSize := (len(items) / maxBatches) + 1 - if dynamicBatchSize < conf.MinBatchSize { - dynamicBatchSize = conf.MinBatchSize - } + dynamicBatchSize := max((len(items)/maxBatches)+1, conf.MinBatchSize) for { if dynamicBatchSize > len(items) { diff --git a/lib/utils/testutils/testhelpers.go b/lib/utils/testutils/testhelpers.go index 2d70ae230bc..af56f7966f5 100644 --- a/lib/utils/testutils/testhelpers.go +++ b/lib/utils/testutils/testhelpers.go @@ -112,7 +112,7 @@ func generateUsername(tb testing.TB) string { // already exists (but it does not create the user). func GenerateLocalUsername(tb testing.TB) string { const maxAttempts = 10 - for i := 0; i < maxAttempts; i++ { + for range maxAttempts { login := generateUsername(tb) _, err := user.Lookup(login) if errors.Is(err, user.UnknownUserError(login)) { diff --git a/lib/utils/testutils/testutils.go b/lib/utils/testutils/testutils.go index 2bbe39dd58f..85301f1ad4f 100644 --- a/lib/utils/testutils/testutils.go +++ b/lib/utils/testutils/testutils.go @@ -67,7 +67,7 @@ func exhaustiveNonEmpty(value reflect.Value, ignore map[string]struct{}) bool { return false } - for i := 0; i < value.Len(); i++ { + for i := range value.Len() { if exhaustiveNonEmpty(value.Index(i), ignore) { return true } @@ -177,7 +177,7 @@ func findAllEmpty(value reflect.Value, ignore map[string]struct{}, path []string } var emptyPaths []string - for i := 0; i < value.Len(); i++ { + for i := range value.Len() { emptyPaths = append(emptyPaths, findAllEmpty(value.Index(i), ignore, append(path, fmt.Sprintf("%d", i)))...) } return emptyPaths diff --git a/lib/utils/timeout_test.go b/lib/utils/timeout_test.go index cb0fac617ef..796ef7656cb 100644 --- a/lib/utils/timeout_test.go +++ b/lib/utils/timeout_test.go @@ -46,7 +46,7 @@ func TestObeyIdleTimeout(t *testing.T) { errC := make(chan error, 3) go func() { var b [1]byte - for i := 0; i < 3; i++ { + for range 3 { _, err := io.ReadFull(c1, b[:]) errC <- err } diff --git a/lib/utils/typical/cached_parser_test.go b/lib/utils/typical/cached_parser_test.go index 1f15207ab3f..c469f51091a 100644 --- a/lib/utils/typical/cached_parser_test.go +++ b/lib/utils/typical/cached_parser_test.go @@ -43,7 +43,7 @@ func TestCachedParser(t *testing.T) { require.ErrorContains(t, err, "expected type int, got value (hello) with type (string)") // Parse $defaultCacheSize unique expressions to fill the cache. - for i := 0; i < defaultCacheSize; i++ { + for i := range defaultCacheSize { expr := fmt.Sprintf("inc(%d)", i) parsed, err := p.Parse(expr) @@ -66,7 +66,7 @@ func TestCachedParser(t *testing.T) { // Parse $logAfterEvictions-1 unique expressions to cause // $logAfterEvictions-1 cache evictions - for i := 0; i < logAfterEvictions-1; i++ { + for i := range logAfterEvictions - 1 { expr := fmt.Sprintf("inc(%d)", defaultCacheSize+i) parsed, err := p.Parse(expr) @@ -91,7 +91,7 @@ func TestCachedParser(t *testing.T) { // Parse another $logAfterEvictions unique expressions to cause // another $logAfterEvictions cache evictions and one more log - for i := 0; i < logAfterEvictions; i++ { + for i := range logAfterEvictions { expr := fmt.Sprintf("inc(%d)", defaultCacheSize+logAfterEvictions+i+1) _, err := p.Parse(expr) require.NoError(t, err) diff --git a/lib/utils/typical/parser_test.go b/lib/utils/typical/parser_test.go index 00377e0ec6a..bec67ff0075 100644 --- a/lib/utils/typical/parser_test.go +++ b/lib/utils/typical/parser_test.go @@ -467,7 +467,6 @@ func TestParser(t *testing.T) { }, }, } { - tc := tc t.Run(tc.desc, func(t *testing.T) { t.Parallel() expr, err := parser.Parse(tc.expr) @@ -566,7 +565,7 @@ func TestUnknownIdentifier(t *testing.T) { name: "unknown variable", expression: "unknown", knownVariablesOnly: true, - parseAssertion: func(t require.TestingT, err error, i ...interface{}) { + parseAssertion: func(t require.TestingT, err error, i ...any) { var u typical.UnknownIdentifierError require.ErrorAs(t, err, &u, i...) require.ErrorAs(t, trace.Wrap(err), &u, i...) @@ -584,7 +583,6 @@ func TestUnknownIdentifier(t *testing.T) { } for _, test := range cases { - test := test t.Run(test.name, func(t *testing.T) { spec := typical.ParserSpec[resource]{ Functions: map[string]typical.Function{ diff --git a/lib/utils/uds/socketpair_unix_test.go b/lib/utils/uds/socketpair_unix_test.go index 48f07eb7368..15bf45fe8a3 100644 --- a/lib/utils/uds/socketpair_unix_test.go +++ b/lib/utils/uds/socketpair_unix_test.go @@ -74,7 +74,7 @@ func TestSocketparFDPassing(t *testing.T) { var eg errgroup.Group - for i := 0; i < maxFiles; i++ { + for i := range maxFiles { f := i + 1 eg.Go(func() error { msg := fmt.Sprintf("send-%d", f) @@ -85,7 +85,7 @@ func TestSocketparFDPassing(t *testing.T) { // fds are the remote halves of socket pairs to be sent // to the server along with the associated message. fds := make([]*os.File, 0, f) - for j := 0; j < f; j++ { + for range f { clt, srv, err := NewSocketpair(SocketTypeStream) if err != nil { return trace.Errorf("failed to create socket pair: %v", err) diff --git a/lib/utils/utils.go b/lib/utils/utils.go index 96478dbc6e7..827489016ce 100644 --- a/lib/utils/utils.go +++ b/lib/utils/utils.go @@ -31,6 +31,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "sort" "strconv" "strings" @@ -263,10 +264,8 @@ func IsGroupMember(gid int) (bool, error) { if err != nil { return false, trace.ConvertSystemError(err) } - for _, group := range groups { - if group == gid { - return true, nil - } + if slices.Contains(groups, gid) { + return true, nil } return false, nil } @@ -323,7 +322,7 @@ func HostFQDN(hostUUID, clusterName string) string { // IsValidHostname checks if a string represents a valid hostname. func IsValidHostname(hostname string) bool { - for _, label := range strings.Split(hostname, ".") { + for label := range strings.SplitSeq(hostname, ".") { if len(validation.IsDNS1035Label(label)) > 0 { return false } diff --git a/lib/utils/utils_test.go b/lib/utils/utils_test.go index 9247db5174a..76f50b0bbe8 100644 --- a/lib/utils/utils_test.go +++ b/lib/utils/utils_test.go @@ -56,7 +56,7 @@ func TestRandomDuration(t *testing.T) { expectedMin := time.Duration(0) expectedMax := time.Second * 10 - for i := 0; i < 50; i++ { + for range 50 { dur := RandomDuration(expectedMax) require.GreaterOrEqual(t, dur, expectedMin) require.Less(t, dur, expectedMax) @@ -477,8 +477,8 @@ func TestMarshalYAML(t *testing.T) { } testCases := []struct { comment string - val interface{} - expected interface{} + val any + expected any isDoc bool }{ { @@ -487,23 +487,23 @@ func TestMarshalYAML(t *testing.T) { }, { comment: "list of yaml types", - val: []interface{}{"hello", "there"}, + val: []any{"hello", "there"}, }, { comment: "list of yaml documents", - val: []interface{}{kv{Key: "a"}, kv{Key: "b"}}, - expected: []interface{}{map[string]interface{}{"Key": "a"}, map[string]interface{}{"Key": "b"}}, + val: []any{kv{Key: "a"}, kv{Key: "b"}}, + expected: []any{map[string]any{"Key": "a"}, map[string]any{"Key": "b"}}, isDoc: true, }, { comment: "list of pointers to yaml docs", - val: []interface{}{kv{Key: "a"}, &kv{Key: "b"}}, - expected: []interface{}{map[string]interface{}{"Key": "a"}, map[string]interface{}{"Key": "b"}}, + val: []any{kv{Key: "a"}, &kv{Key: "b"}}, + expected: []any{map[string]any{"Key": "a"}, map[string]any{"Key": "b"}}, isDoc: true, }, { comment: "list of maps", - val: []interface{}{map[string]interface{}{"Key": "a"}, map[string]interface{}{"Key": "b"}}, + val: []any{map[string]any{"Key": "a"}, map[string]any{"Key": "b"}}, isDoc: true, }, } diff --git a/lib/utils/ver_test.go b/lib/utils/ver_test.go index ff3d4b3bafa..3f3135caac7 100644 --- a/lib/utils/ver_test.go +++ b/lib/utils/ver_test.go @@ -91,7 +91,6 @@ func TestMajorSemver(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { got, err := MajorSemver(tt.version) if tt.wantErr { @@ -176,7 +175,6 @@ func TestMinVerWithoutPreRelease(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel()