mirror of
https://github.com/gravitational/teleport.git
synced 2026-09-19 01:58:44 +08:00
Apply more modernize fixes (#55975)
- lib/srv - lib/limiter - lib/multiplexer - lib/usagereporter
This commit is contained in:
@@ -29,42 +29,42 @@ import (
|
||||
func TestConnectionsLimiter(t *testing.T) {
|
||||
l := limiter.NewConnectionsLimiter(0)
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
require.NoError(t, l.AcquireConnection("token1"))
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
require.NoError(t, l.AcquireConnection("token2"))
|
||||
}
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
l.ReleaseConnection("token1")
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
l.ReleaseConnection("token2")
|
||||
}
|
||||
|
||||
l = limiter.NewConnectionsLimiter(5)
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
require.NoError(t, l.AcquireConnection("token1"))
|
||||
}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
require.NoError(t, l.AcquireConnection("token2"))
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
require.Error(t, l.AcquireConnection("token2"))
|
||||
}
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
l.ReleaseConnection("token1")
|
||||
require.NoError(t, l.AcquireConnection("token1"))
|
||||
}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
l.ReleaseConnection("token2")
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
require.NoError(t, l.AcquireConnection("token2"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,7 +132,7 @@ type CustomRateFunc func(endpoint string) *RateSet
|
||||
// rate limits by client IP. Accepts a CustomRateFunc to set custom rates for
|
||||
// specific gRPC methods.
|
||||
func (l *Limiter) UnaryServerInterceptorWithCustomRate(customRate CustomRateFunc) grpc.UnaryServerInterceptor {
|
||||
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
|
||||
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
|
||||
peerInfo, ok := peer.FromContext(ctx)
|
||||
if !ok {
|
||||
return nil, trace.AccessDenied("missing peer info")
|
||||
@@ -155,7 +155,7 @@ func (l *Limiter) UnaryServerInterceptorWithCustomRate(customRate CustomRateFunc
|
||||
|
||||
// StreamServerInterceptor is a gRPC stream interceptor that rate limits
|
||||
// incoming requests by client IP.
|
||||
func (l *Limiter) StreamServerInterceptor(srv interface{}, serverStream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
func (l *Limiter) StreamServerInterceptor(srv any, serverStream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
peerInfo, ok := peer.FromContext(serverStream.Context())
|
||||
if !ok {
|
||||
return trace.AccessDenied("missing peer info")
|
||||
|
||||
+15
-15
@@ -64,23 +64,23 @@ func TestRateLimiter(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
for i := 0; i < 20; i++ {
|
||||
for range 20 {
|
||||
require.NoError(t, limiter.RegisterRequest("token1"))
|
||||
}
|
||||
for i := 0; i < 20; i++ {
|
||||
for range 20 {
|
||||
require.NoError(t, limiter.RegisterRequest("token2"))
|
||||
}
|
||||
|
||||
require.Error(t, limiter.RegisterRequest("token1"))
|
||||
|
||||
clock.Advance(10 * time.Millisecond)
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
require.NoError(t, limiter.RegisterRequest("token1"))
|
||||
}
|
||||
require.Error(t, limiter.RegisterRequest("token1"))
|
||||
|
||||
clock.Advance(10 * time.Millisecond)
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
require.NoError(t, limiter.RegisterRequest("token1"))
|
||||
}
|
||||
require.Error(t, limiter.RegisterRequest("token1"))
|
||||
@@ -88,7 +88,7 @@ func TestRateLimiter(t *testing.T) {
|
||||
clock.Advance(10 * time.Millisecond)
|
||||
// the second rate is full
|
||||
err = nil
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
err = limiter.RegisterRequest("token1")
|
||||
if err != nil {
|
||||
break
|
||||
@@ -100,7 +100,7 @@ func TestRateLimiter(t *testing.T) {
|
||||
// Now the second rate has free space
|
||||
require.NoError(t, limiter.RegisterRequest("token1"))
|
||||
err = nil
|
||||
for i := 0; i < 15; i++ {
|
||||
for range 15 {
|
||||
err = limiter.RegisterRequest("token1")
|
||||
if err != nil {
|
||||
break
|
||||
@@ -131,7 +131,7 @@ func TestCustomRate(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// Max out custom rate.
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
require.NoError(t, limiter.RegisterRequestWithCustomRate("token1", customRate))
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ func TestCustomRate(t *testing.T) {
|
||||
require.Error(t, limiter.RegisterRequestWithCustomRate("token1", customRate))
|
||||
|
||||
// Test default rate still works.
|
||||
for i := 0; i < 20; i++ {
|
||||
for range 20 {
|
||||
require.NoError(t, limiter.RegisterRequest("token1"))
|
||||
}
|
||||
}
|
||||
@@ -172,7 +172,7 @@ func TestLimiter_UnaryServerInterceptor(t *testing.T) {
|
||||
serverInfo := &grpc.UnaryServerInfo{
|
||||
FullMethod: "/method",
|
||||
}
|
||||
handler := func(context.Context, interface{}) (interface{}, error) { return nil, nil }
|
||||
handler := func(context.Context, any) (any, error) { return nil, nil }
|
||||
|
||||
unaryInterceptor := limiter.UnaryServerInterceptor()
|
||||
|
||||
@@ -181,7 +181,7 @@ func TestLimiter_UnaryServerInterceptor(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// should eventually fail, not testing the limiter behavior here
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
_, err = unaryInterceptor(ctx, req, serverInfo, handler)
|
||||
if err != nil {
|
||||
break
|
||||
@@ -203,7 +203,7 @@ func TestLimiter_UnaryServerInterceptor(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// should eventually fail, not testing the limiter behavior here
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
_, err = unaryInterceptor(ctx, req, serverInfo, handler)
|
||||
if err != nil {
|
||||
break
|
||||
@@ -239,14 +239,14 @@ func TestLimiter_StreamServerInterceptor(t *testing.T) {
|
||||
ctx: ctx,
|
||||
}
|
||||
info := &grpc.StreamServerInfo{}
|
||||
handler := func(srv interface{}, stream grpc.ServerStream) error { return nil }
|
||||
handler := func(srv any, stream grpc.ServerStream) error { return nil }
|
||||
|
||||
// pass at least once
|
||||
err = limiter.StreamServerInterceptor(nil, ss, info, handler)
|
||||
require.NoError(t, err)
|
||||
|
||||
// should eventually fail, not testing the limiter behavior here
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
err = limiter.StreamServerInterceptor(nil, ss, info, handler)
|
||||
if err != nil {
|
||||
break
|
||||
@@ -353,7 +353,7 @@ func TestListener(t *testing.T) {
|
||||
|
||||
// open connections without closing to enforce limits
|
||||
conns := make([]net.Conn, 0, connLimit)
|
||||
for i := 0; i < connLimit; i++ {
|
||||
for i := range connLimit {
|
||||
conn, err := ln.Accept()
|
||||
test.acceptAssertion(t, i, conn, err)
|
||||
|
||||
@@ -384,7 +384,7 @@ func TestListener(t *testing.T) {
|
||||
|
||||
// open connections again after closing to
|
||||
// ensure that closing reset limits
|
||||
for i := 0; i < 5; i++ {
|
||||
for i := range 5 {
|
||||
conn, err := ln.Accept()
|
||||
test.acceptAssertion(t, i, conn, err)
|
||||
|
||||
|
||||
@@ -563,7 +563,7 @@ func (m *Mux) detect(conn net.Conn) (*Conn, error) {
|
||||
// signed header from our own proxies, which take precedence.
|
||||
var proxyLine *ProxyLine
|
||||
unsignedPROXYLineReceived := false
|
||||
for i := 0; i < maxDetectionPasses; i++ {
|
||||
for range maxDetectionPasses {
|
||||
proto, err := detectProto(reader)
|
||||
if err != nil {
|
||||
return nil, trace.Wrap(err)
|
||||
|
||||
@@ -650,7 +650,7 @@ func TestMux(t *testing.T) {
|
||||
httpServer.Close()
|
||||
s.Stop()
|
||||
// wait for both servers to finish
|
||||
for i := 0; i < 2; i++ {
|
||||
for range 2 {
|
||||
err := <-errCh
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unsafe"
|
||||
@@ -119,7 +120,7 @@ func (p *ProxyLine) Bytes() ([]byte, error) {
|
||||
b := &bytes.Buffer{}
|
||||
header := proxyV2Header{VersionCommand: (Version2 << 4) | ProxyCommand}
|
||||
copy(header.Signature[:], ProxyV2Prefix)
|
||||
var addr interface{}
|
||||
var addr any
|
||||
if p.Source.Port < 0 || p.Destination.Port < 0 ||
|
||||
p.Source.Port > math.MaxUint16 || p.Destination.Port > math.MaxUint16 {
|
||||
return nil, trace.BadParameter("source or destination port (%q,%q) is out of range 0-65535", p.Source.Port, p.Destination.Port)
|
||||
@@ -596,7 +597,7 @@ func getTLSCerts(ca types.CertAuthority) [][]byte {
|
||||
pairs := ca.GetTrustedTLSKeyPairs()
|
||||
out := make([][]byte, len(pairs))
|
||||
for i, pair := range pairs {
|
||||
out[i] = append([]byte{}, pair.Cert...)
|
||||
out[i] = slices.Clone(pair.Cert)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@ func (p *TestProxy) handleConnection(clientConn net.Conn) error {
|
||||
errCh <- trace.Wrap(err)
|
||||
}()
|
||||
var errs []error
|
||||
for i := 0; i < 2; i++ {
|
||||
for range 2 {
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil && !utils.IsOKNetworkError(err) {
|
||||
|
||||
@@ -193,7 +193,7 @@ func (s *AuthProxyDialerService) proxyConn(ctx context.Context, upstreamConn, do
|
||||
errC <- trace.Wrap(err)
|
||||
}()
|
||||
var errs []error
|
||||
for i := 0; i < 2; i++ {
|
||||
for range 2 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return trace.Wrap(ctx.Err())
|
||||
|
||||
@@ -59,7 +59,7 @@ func TestDialLocalAuthServerAvailableServers(t *testing.T) {
|
||||
authServers := make([]string, 1, 11)
|
||||
authServers[0] = socket.Addr().String()
|
||||
// multiple invalid servers to minimize chance that we select good one first try
|
||||
for i := 0; i < 10; i++ {
|
||||
for i := range 10 {
|
||||
// The 203.0.113.0/24 range is part of block TEST-NET-3 as defined in RFC-5735 (https://www.rfc-editor.org/rfc/rfc5735).
|
||||
// IPs in this range do not appear on the public internet.
|
||||
authServers = append(authServers, fmt.Sprintf("203.0.113.%d:3025", i+1))
|
||||
|
||||
@@ -248,7 +248,7 @@ func isXMLOfLocalName(data []byte, wantLocalName string) bool {
|
||||
|
||||
// unmarshalXMLChildNode decodes the XML-encoded data and stores the child node
|
||||
// with the specified name to v, where v is a pointer to an AWS SDK v2 struct.
|
||||
func unmarshalXMLChildNode(v interface{}, data []byte, childName string) error {
|
||||
func unmarshalXMLChildNode(v any, data []byte, childName string) error {
|
||||
decoder := xml.NewDecoder(bytes.NewReader(data))
|
||||
st, err := smithyxml.FetchRootElement(decoder)
|
||||
if err != nil {
|
||||
|
||||
@@ -113,7 +113,6 @@ func TestHandleAWSAccessSigVerification(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -323,7 +322,7 @@ func TestLocalProxyConcurrentCertRenewal(t *testing.T) {
|
||||
}()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 2; i++ {
|
||||
for range 2 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
@@ -407,7 +406,6 @@ func TestCheckDBCerts(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
tlsCert := mustGenCertSignedWithCA(t, suite.ca,
|
||||
withIdentity(tlsca.Identity{
|
||||
@@ -659,7 +657,7 @@ func createAWSAccessProxySuite(t *testing.T, provider aws.CredentialsProvider) *
|
||||
return lp
|
||||
}
|
||||
|
||||
func requireExpiredCertErr(t require.TestingT, err error, _ ...interface{}) {
|
||||
func requireExpiredCertErr(t require.TestingT, err error, _ ...any) {
|
||||
if h, ok := t.(*testing.T); ok {
|
||||
h.Helper()
|
||||
}
|
||||
@@ -669,7 +667,7 @@ func requireExpiredCertErr(t require.TestingT, err error, _ ...interface{}) {
|
||||
require.Equal(t, x509.Expired, certErr.Reason)
|
||||
}
|
||||
|
||||
func requireCertSubjectUserErr(t require.TestingT, err error, _ ...interface{}) {
|
||||
func requireCertSubjectUserErr(t require.TestingT, err error, _ ...any) {
|
||||
if h, ok := t.(*testing.T); ok {
|
||||
h.Helper()
|
||||
}
|
||||
@@ -677,7 +675,7 @@ func requireCertSubjectUserErr(t require.TestingT, err error, _ ...interface{})
|
||||
require.ErrorContains(t, err, "certificate subject is for user")
|
||||
}
|
||||
|
||||
func requireCertSubjectDatabaseErr(t require.TestingT, err error, _ ...interface{}) {
|
||||
func requireCertSubjectDatabaseErr(t require.TestingT, err error, _ ...any) {
|
||||
if h, ok := t.(*testing.T); ok {
|
||||
h.Helper()
|
||||
}
|
||||
@@ -751,7 +749,6 @@ func TestGetCertsForConn(t *testing.T) {
|
||||
},
|
||||
}
|
||||
for name, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
// we wont actually be listening for connections, but local proxy config needs to be valid to pass checks.
|
||||
|
||||
@@ -130,10 +130,7 @@ func ExtractMySQLEngineVersion(fn func(ctx context.Context, conn net.Conn) error
|
||||
}
|
||||
// The version should never be longer than 255 characters including
|
||||
// the prefix, but better to be safe.
|
||||
versionEnd := 255
|
||||
if len(alpn) < versionEnd {
|
||||
versionEnd = len(alpn)
|
||||
}
|
||||
versionEnd := min(len(alpn), 255)
|
||||
|
||||
mysqlVersionBase64 := alpn[mysqlVerStart:versionEnd]
|
||||
mysqlVersionBytes, err := base64.StdEncoding.DecodeString(mysqlVersionBase64)
|
||||
|
||||
@@ -660,7 +660,7 @@ func TestMatchMySQLConn(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
protos []string
|
||||
version interface{}
|
||||
version any
|
||||
}{
|
||||
{
|
||||
name: "success",
|
||||
@@ -738,7 +738,6 @@ func TestProxyPingConnections(t *testing.T) {
|
||||
suite.Start(t)
|
||||
|
||||
for _, protocol := range common.ProtocolsWithPingSupport {
|
||||
protocol := protocol
|
||||
t.Run(string(protocol), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -195,7 +195,7 @@ func (r requestByAssumedRoleTransport) RoundTrip(req *http.Request) (*http.Respo
|
||||
}
|
||||
|
||||
func hasStatusCode(wantStatusCode int) require.ErrorAssertionFunc {
|
||||
return func(t require.TestingT, err error, msgAndArgs ...interface{}) {
|
||||
return func(t require.TestingT, err error, msgAndArgs ...any) {
|
||||
var respErr *transporthttp.ResponseError
|
||||
require.ErrorAs(t, err, &respErr, msgAndArgs...)
|
||||
require.Equal(t, wantStatusCode, respErr.Response.StatusCode, msgAndArgs...)
|
||||
@@ -457,7 +457,6 @@ func TestAWSSignerHandler(t *testing.T) {
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
fakeClock := clockwork.NewFakeClock()
|
||||
|
||||
@@ -97,7 +97,7 @@ func TestForwarder_getToken(t *testing.T) {
|
||||
return &azcore.AccessToken{Token: "foobar"}, nil
|
||||
},
|
||||
},
|
||||
checkErr: func(t require.TestingT, err error, i ...interface{}) {
|
||||
checkErr: func(t require.TestingT, err error, i ...any) {
|
||||
require.ErrorContains(t, err, "timeout waiting for access token for 5s")
|
||||
require.ErrorIs(t, err, context.DeadlineExceeded)
|
||||
},
|
||||
@@ -110,7 +110,7 @@ func TestForwarder_getToken(t *testing.T) {
|
||||
return nil, trace.BadParameter("bad param foo")
|
||||
},
|
||||
},
|
||||
checkErr: func(t require.TestingT, err error, i ...interface{}) {
|
||||
checkErr: func(t require.TestingT, err error, i ...any) {
|
||||
require.ErrorContains(t, err, "bad param foo")
|
||||
require.True(t, trace.IsBadParameter(err))
|
||||
},
|
||||
@@ -124,7 +124,7 @@ func TestForwarder_getToken(t *testing.T) {
|
||||
return nil, trace.BadParameter("bad param foo")
|
||||
},
|
||||
},
|
||||
checkErr: func(t require.TestingT, err error, i ...interface{}) {
|
||||
checkErr: func(t require.TestingT, err error, i ...any) {
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
},
|
||||
},
|
||||
|
||||
@@ -338,10 +338,7 @@ func (c *cloud) getFederationDuration(req *AWSSigninRequest, temporarySession bo
|
||||
maxDuration = maxTemporarySessionDuration
|
||||
}
|
||||
|
||||
duration := req.Identity.Expires.Sub(c.cfg.Clock.Now())
|
||||
if duration > maxDuration {
|
||||
duration = maxDuration
|
||||
}
|
||||
duration := min(req.Identity.Expires.Sub(c.cfg.Clock.Now()), maxDuration)
|
||||
|
||||
if duration < minimumSessionDuration {
|
||||
return 0, trace.AccessDenied("minimum AWS session duration is %v but Teleport identity expires in %v", minimumSessionDuration, duration)
|
||||
|
||||
@@ -99,7 +99,7 @@ func TestIsSessionUsingTemporaryCredentials(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test // capture range variable
|
||||
// capture range variable
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
isTemporary, err := isSessionUsingTemporaryCredentials(ctx, aws.Config{Credentials: test.credentials})
|
||||
@@ -148,7 +148,7 @@ func TestCloudGetFederationDuration(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test // capture range variable
|
||||
// capture range variable
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, err := NewCloud(CloudConfig{
|
||||
@@ -241,7 +241,7 @@ func TestCloudGetAWSSigninToken(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test // capture range variable
|
||||
// capture range variable
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
mockFederationServer := httptest.NewServer(test.federationServerHandler)
|
||||
|
||||
@@ -111,7 +111,7 @@ func TestHandler_getToken(t *testing.T) {
|
||||
}),
|
||||
}
|
||||
},
|
||||
checkErr: func(t require.TestingT, err error, i ...interface{}) {
|
||||
checkErr: func(t require.TestingT, err error, i ...any) {
|
||||
require.ErrorContains(t, err, "timeout waiting for access token for 5s")
|
||||
require.ErrorIs(t, err, context.DeadlineExceeded)
|
||||
},
|
||||
@@ -125,7 +125,7 @@ func TestHandler_getToken(t *testing.T) {
|
||||
},
|
||||
}),
|
||||
}),
|
||||
checkErr: func(t require.TestingT, err error, i ...interface{}) {
|
||||
checkErr: func(t require.TestingT, err error, i ...any) {
|
||||
require.ErrorContains(t, err, "bad param foo")
|
||||
require.True(t, trace.IsBadParameter(err))
|
||||
},
|
||||
|
||||
@@ -474,7 +474,6 @@ func (s *Server) close(ctx context.Context) error {
|
||||
// server below would be undone.
|
||||
s.mu.RLock()
|
||||
for name := range s.apps {
|
||||
name := name
|
||||
heartbeat := s.heartbeats[name]
|
||||
|
||||
if dynamic, ok := s.dynamicLabels[name]; ok {
|
||||
|
||||
@@ -553,7 +553,6 @@ func TestShutdown(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -326,9 +326,9 @@ func host(addr string) string {
|
||||
// charWrap wraps a line to about 80 characters to make it easier to read.
|
||||
func charWrap(message string) string {
|
||||
var sb strings.Builder
|
||||
for _, line := range strings.Split(message, "\n") {
|
||||
for line := range strings.SplitSeq(message, "\n") {
|
||||
var n int
|
||||
for _, word := range strings.Fields(line) {
|
||||
for word := range strings.FieldsSeq(line) {
|
||||
sb.WriteString(word)
|
||||
sb.WriteString(" ")
|
||||
|
||||
|
||||
@@ -112,8 +112,7 @@ func (m mockConnMetadata) RemoteAddr() net.Addr {
|
||||
func TestRBAC(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
node, err := types.NewNode("testie_node", types.SubKindTeleportNode, types.ServerSpecV2{
|
||||
Addr: "1.2.3.4:22",
|
||||
@@ -396,8 +395,7 @@ func TestForwardingGitLocalOnly(t *testing.T) {
|
||||
func TestRBACJoinMFA(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
const clusterName = "localhost"
|
||||
const username = "testuser"
|
||||
|
||||
+1
-3
@@ -260,8 +260,7 @@ func TestSSHAccessLockTargets(t *testing.T) {
|
||||
func TestCreateOrJoinSession(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
srv := newMockServer(t)
|
||||
registry, err := NewSessionRegistry(SessionRegistryConfig{
|
||||
@@ -306,7 +305,6 @@ func TestCreateOrJoinSession(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -1022,7 +1022,6 @@ func TestAccessMongoDB(t *testing.T) {
|
||||
// Execute each scenario on both modern and legacy Mongo servers
|
||||
// to make sure legacy messages are also subject to RBAC.
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(fmt.Sprintf("%v", test.desc), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -1034,7 +1033,6 @@ func TestAccessMongoDB(t *testing.T) {
|
||||
testCtx.createUserAndRole(ctx, t, test.user, test.role, test.allowDbUsers, test.allowDbNames)
|
||||
|
||||
for _, clientOpt := range clientOpts {
|
||||
clientOpt := clientOpt
|
||||
|
||||
t.Run(fmt.Sprintf("%v/%v", serverOpt.name, clientOpt.name), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
@@ -1250,7 +1248,6 @@ func TestRedisPubSub(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
@@ -1330,7 +1327,7 @@ func TestRedisPipeline(t *testing.T) {
|
||||
pipeliner := redisClient.Pipeline()
|
||||
|
||||
// Set multiple keys using pipelining.
|
||||
for i := 0; i < 10; i++ {
|
||||
for i := range 10 {
|
||||
err := pipeliner.Set(ctx, fmt.Sprintf("foo%d", i), i, 0).Err()
|
||||
require.NoError(t, err)
|
||||
}
|
||||
@@ -1342,7 +1339,7 @@ func TestRedisPipeline(t *testing.T) {
|
||||
require.NoError(t, cmd.Err())
|
||||
}
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
for i := range 10 {
|
||||
err := pipeliner.Get(ctx, fmt.Sprintf("foo%d", i)).Err()
|
||||
require.NoError(t, err)
|
||||
}
|
||||
@@ -1397,7 +1394,7 @@ func TestRedisTransaction(t *testing.T) {
|
||||
return err
|
||||
}
|
||||
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
for range maxRetries {
|
||||
err := redisClient.Watch(ctx, txf, key)
|
||||
if err == nil {
|
||||
// Success.
|
||||
@@ -1422,7 +1419,7 @@ func TestRedisTransaction(t *testing.T) {
|
||||
asyncErrors := make(chan error, concurrentConnections)
|
||||
defer close(asyncErrors)
|
||||
|
||||
for i := 0; i < concurrentConnections; i++ {
|
||||
for range concurrentConnections {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
@@ -407,7 +407,6 @@ func TestAutoUsersMongoDB(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -684,7 +684,6 @@ func TestTLSConfiguration(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -694,7 +693,6 @@ func TestTLSConfiguration(t *testing.T) {
|
||||
defaults.ProtocolMySQL,
|
||||
defaults.ProtocolMongoDB,
|
||||
} {
|
||||
dbType := dbType
|
||||
t.Run(dbType, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cfg := &setupTLSTestCfg{
|
||||
@@ -854,7 +852,7 @@ func TestCADownloaderGetVersion(t *testing.T) {
|
||||
desc: "without support to ETag returns error",
|
||||
database: rds,
|
||||
supportEtag: false,
|
||||
expectError: func(t require.TestingT, err error, _ ...interface{}) {
|
||||
expectError: func(t require.TestingT, err error, _ ...any) {
|
||||
require.Error(t, err)
|
||||
require.True(t, trace.IsNotImplemented(err), "expected trace.NotImplementedError but received %T", err)
|
||||
},
|
||||
|
||||
@@ -127,7 +127,7 @@ func (e *Engine) handleClientServerConn(ctx context.Context, clientConn *protoco
|
||||
}()
|
||||
|
||||
var errs []error
|
||||
for i := 0; i < 2; i++ {
|
||||
for range 2 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return trace.Wrap(ctx.Err())
|
||||
|
||||
@@ -295,7 +295,7 @@ func TestGetAzureIdentityResourceID(t *testing.T) {
|
||||
}, nil /* scaleSetAPI */),
|
||||
},
|
||||
errAssertion: require.NoError,
|
||||
resourceIDAssertion: func(requireT require.TestingT, value interface{}, _ ...interface{}) {
|
||||
resourceIDAssertion: func(requireT require.TestingT, value any, _ ...any) {
|
||||
require.Equal(requireT, identityResourceID(t, "identity"), value)
|
||||
},
|
||||
},
|
||||
@@ -372,7 +372,7 @@ func TestGetAzureIdentityResourceID(t *testing.T) {
|
||||
),
|
||||
},
|
||||
errAssertion: require.NoError,
|
||||
resourceIDAssertion: func(requireT require.TestingT, value interface{}, _ ...interface{}) {
|
||||
resourceIDAssertion: func(requireT require.TestingT, value any, _ ...any) {
|
||||
require.Equal(requireT, identityResourceID(t, "identity"), value)
|
||||
},
|
||||
},
|
||||
@@ -700,7 +700,6 @@ func TestAuthGetAWSTokenWithAssumedRole(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
for name, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
tt.checkGetAuthFn(t, auth)
|
||||
|
||||
@@ -56,7 +56,7 @@ func TestGetDatabaseServers(t *testing.T) {
|
||||
"no match": {
|
||||
identity: identityWithDatabase("no-match", "root", "alice", nil),
|
||||
getter: newDatabaseServersWithServers("first", "second", "third"),
|
||||
expectErrorFunc: func(tt require.TestingT, err error, i ...interface{}) {
|
||||
expectErrorFunc: func(tt require.TestingT, err error, i ...any) {
|
||||
require.Error(t, err)
|
||||
require.True(t, trace.IsNotFound(err), "expected trace.NotFound error but got %T", err)
|
||||
},
|
||||
@@ -106,7 +106,7 @@ func TestGetServerTLSConfig(t *testing.T) {
|
||||
server: databaseServerWithName("db", "server1"),
|
||||
identity: identityWithDatabase("db", clusterName, user.GetName(), []string{role.GetName()}),
|
||||
expectErrorFunc: require.NoError,
|
||||
expectTLSConfigFunc: func(tt require.TestingT, tlsConfigI interface{}, _ ...interface{}) {
|
||||
expectTLSConfigFunc: func(tt require.TestingT, tlsConfigI any, _ ...any) {
|
||||
require.IsType(t, &tls.Config{}, tlsConfigI)
|
||||
tlsConfig, _ := tlsConfigI.(*tls.Config)
|
||||
require.Len(t, tlsConfig.Certificates, 1)
|
||||
|
||||
@@ -125,7 +125,6 @@ func TestResolveEndpoint(t *testing.T) {
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
// mock a request.
|
||||
|
||||
@@ -104,7 +104,6 @@ func TestAccessElasticsearch(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
// Create user/role with the requested permissions.
|
||||
testCtx.createUserAndRole(ctx, t, test.user, test.role, test.allowDbUsers, []string{})
|
||||
|
||||
@@ -190,7 +190,7 @@ func (e *Engine) DeleteUser(ctx context.Context, sessionCtx *common.Session) err
|
||||
func (e *Engine) isUserActive(ctx context.Context, sessionCtx *common.Session, client adminClient) (bool, error) {
|
||||
e.Log.DebugContext(e.Context, "Checking if user is active.", "user", sessionCtx.DatabaseUser)
|
||||
var resp struct {
|
||||
Inprog []interface{} `bson:"inprog"`
|
||||
Inprog []any `bson:"inprog"`
|
||||
}
|
||||
|
||||
err := client.Database(adminDatabaseName).RunCommand(ctx, bson.D{
|
||||
|
||||
@@ -89,7 +89,7 @@ func readOpKillCursors(header MessageHeader, payload []byte) (*MessageOpKillCurs
|
||||
return nil, trace.BadParameter("malformed OP_KILL_CURSORS: missing number of cursor IDs %v", payload)
|
||||
}
|
||||
var cursorIDs []int64
|
||||
for n := 0; n < int(numberOfCursorIDs); n++ {
|
||||
for range int(numberOfCursorIDs) {
|
||||
var cursorID int64
|
||||
cursorID, rem, ok = readInt64(rem)
|
||||
if !ok {
|
||||
|
||||
@@ -781,7 +781,7 @@ func makeIsMasterReply(wireVersion int, maxMessageSize uint32) ([]byte, error) {
|
||||
}
|
||||
|
||||
// makeFindReply builds a document used as a "find" command reply.
|
||||
func makeFindReply(result interface{}) ([]byte, error) {
|
||||
func makeFindReply(result any) ([]byte, error) {
|
||||
return bson.Marshal(bson.M{
|
||||
"ok": 1,
|
||||
"cursor": bson.M{
|
||||
|
||||
@@ -87,7 +87,6 @@ func TestFetchMySQLVersion(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -142,7 +142,6 @@ func Test_getGCPUserAndPassword(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
sessionCtx := &common.Session{
|
||||
Database: db,
|
||||
|
||||
@@ -455,7 +455,6 @@ func TestParsePacket(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@ type StatementExecutePacket struct {
|
||||
}
|
||||
|
||||
// Parameters returns a slice of parameters.
|
||||
func (p *StatementExecutePacket) Parameters(definitions []mysql.Field) (parameters []interface{}, ok bool) {
|
||||
func (p *StatementExecutePacket) Parameters(definitions []mysql.Field) (parameters []any, ok bool) {
|
||||
// TODO(greedy52) implement parsing of null bitmap, parameter types, and
|
||||
// paramerter binary values.
|
||||
return nil, true
|
||||
@@ -186,7 +186,7 @@ type StatementBulkExecutePacket struct {
|
||||
}
|
||||
|
||||
// Parameters returns a slice of parameters.
|
||||
func (p *StatementBulkExecutePacket) Parameters(definitions []mysql.Field) (parameters []interface{}, ok bool) {
|
||||
func (p *StatementBulkExecutePacket) Parameters(definitions []mysql.Field) (parameters []any, ok bool) {
|
||||
// TODO(greedy52) implement parsing of parameters from
|
||||
// COM_STMT_BULK_EXECUTE packet.
|
||||
return nil, true
|
||||
|
||||
@@ -42,7 +42,7 @@ import (
|
||||
|
||||
// TestClientConn defines interface for client.Conn.
|
||||
type TestClientConn interface {
|
||||
Execute(command string, args ...interface{}) (*mysql.Result, error)
|
||||
Execute(command string, args ...any) (*mysql.Result, error)
|
||||
Close() error
|
||||
UseDB(dbName string) error
|
||||
GetServerVersion() string
|
||||
@@ -314,7 +314,7 @@ func (h *testHandler) HandleQuery(query string) (*mysql.Result, error) {
|
||||
if query == "show tables" {
|
||||
resultSet, err := mysql.BuildSimpleTextResultset(
|
||||
[]string{"Tables_in_test"},
|
||||
[][]interface{}{
|
||||
[][]any{
|
||||
// In raw bytes, this table name starts with 0x11 which used to
|
||||
// cause server packet parsing issues since it clashed with
|
||||
// COM_CHANGE_USER packet type.
|
||||
@@ -331,11 +331,11 @@ func (h *testHandler) HandleQuery(query string) (*mysql.Result, error) {
|
||||
return newTestQueryResponse(), nil
|
||||
}
|
||||
|
||||
func (h *testHandler) HandleStmtPrepare(prepare string) (int, int, interface{}, error) {
|
||||
func (h *testHandler) HandleStmtPrepare(prepare string) (int, int, any, error) {
|
||||
params := strings.Count(prepare, "?")
|
||||
return params, 0, nil, nil
|
||||
}
|
||||
func (h *testHandler) HandleStmtExecute(_ interface{}, query string, args []interface{}) (*mysql.Result, error) {
|
||||
func (h *testHandler) HandleStmtExecute(_ any, query string, args []any) (*mysql.Result, error) {
|
||||
h.log.DebugContext(context.Background(), "Received execute statement with args", "query", query, "args", args)
|
||||
if strings.HasPrefix(query, "CALL ") {
|
||||
return h.handleCallProcedure(query, args)
|
||||
@@ -343,7 +343,7 @@ func (h *testHandler) HandleStmtExecute(_ interface{}, query string, args []inte
|
||||
return newTestQueryResponse(), nil
|
||||
}
|
||||
|
||||
func (h *testHandler) handleCallProcedure(query string, args []interface{}) (*mysql.Result, error) {
|
||||
func (h *testHandler) handleCallProcedure(query string, args []any) (*mysql.Result, error) {
|
||||
query = strings.TrimSpace(strings.TrimPrefix(query, "CALL"))
|
||||
openBracketIndex := strings.IndexByte(query, '(')
|
||||
endBracketIndex := strings.LastIndexByte(query, ')')
|
||||
|
||||
@@ -452,8 +452,8 @@ func (s *TestServer) handleCreateStoredProcedure(query string, pid uint32) error
|
||||
|
||||
procName := storedProcedureName(pid, match[storedProcedureRe.SubexpIndex("Schema")], match[storedProcedureRe.SubexpIndex("ProcName")])
|
||||
var argsCount int
|
||||
args := strings.Split(match[storedProcedureRe.SubexpIndex("Args")], ",")
|
||||
for _, arg := range args {
|
||||
args := strings.SplitSeq(match[storedProcedureRe.SubexpIndex("Args")], ",")
|
||||
for arg := range args {
|
||||
// Skip arguments that have a default value.
|
||||
if !strings.Contains(strings.ToLower(arg), "default") {
|
||||
argsCount++
|
||||
|
||||
@@ -673,7 +673,7 @@ func withRetry(ctx context.Context, log *slog.Logger, f func() error) error {
|
||||
}
|
||||
|
||||
// retry a finite number of times before giving up.
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
err := f()
|
||||
if err == nil {
|
||||
return nil
|
||||
|
||||
@@ -120,7 +120,7 @@ func TestCheckPgPermission(t *testing.T) {
|
||||
name: "invalid permission",
|
||||
perm: "INVALID",
|
||||
objKind: databaseobjectimportrule.ObjectKindTable,
|
||||
checkErr: func(t require.TestingT, err error, i ...interface{}) {
|
||||
checkErr: func(t require.TestingT, err error, i ...any) {
|
||||
require.ErrorContains(t, err, "unrecognized \"table\" Postgres permission: \"INVALID\"")
|
||||
},
|
||||
},
|
||||
@@ -128,7 +128,7 @@ func TestCheckPgPermission(t *testing.T) {
|
||||
name: "multiple permissions not allowed",
|
||||
perm: "SELECT, UPDATE",
|
||||
objKind: databaseobjectimportrule.ObjectKindTable,
|
||||
checkErr: func(t require.TestingT, err error, i ...interface{}) {
|
||||
checkErr: func(t require.TestingT, err error, i ...any) {
|
||||
require.ErrorContains(t, err, "unrecognized \"table\" Postgres permission: \"SELECT, UPDATE\"")
|
||||
},
|
||||
},
|
||||
|
||||
@@ -210,9 +210,7 @@ func TestProxyProtocolPostgresStartup(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
for _, proxy := range proxyTargets {
|
||||
proxy := proxy
|
||||
testName := fmt.Sprintf("%s %s", proxy.name, tt.name)
|
||||
t.Run(testName, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -79,7 +79,6 @@ func TestProxyConnectionLimiting(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Keep close functions to all connections. Call and release all active connection at the end of test.
|
||||
@@ -92,7 +91,7 @@ func TestProxyConnectionLimiting(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("limit can be hit", func(t *testing.T) {
|
||||
for i := 0; i < connLimitNumber; i++ {
|
||||
for range connLimitNumber {
|
||||
// Try to connect to the database.
|
||||
dbConn, err := tt.connect()
|
||||
require.NoError(t, err)
|
||||
@@ -206,7 +205,6 @@ func TestProxyRateLimiting(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Keep close functions to all connections. Call and release all active connection at the end of test.
|
||||
@@ -218,7 +216,7 @@ func TestProxyRateLimiting(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
for i := 0; i < connLimitNumber; i++ {
|
||||
for range connLimitNumber {
|
||||
// Try to connect to the database.
|
||||
pgConn, err := tt.connect()
|
||||
if err == nil {
|
||||
|
||||
@@ -318,7 +318,7 @@ func (c *clusterClient) Process(ctx context.Context, inCmd redis.Cmder) error {
|
||||
return trace.BadParameter("wrong number of arguments for 'mget' command")
|
||||
}
|
||||
|
||||
var resultsKeys []interface{}
|
||||
var resultsKeys []any
|
||||
|
||||
keys := cmd.Args()[1:]
|
||||
for _, key := range keys {
|
||||
|
||||
@@ -119,20 +119,20 @@ func (e *Engine) processPubSub(ctx context.Context, pubSub *redis.PubSub) error
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case *redis.Subscription:
|
||||
if err := e.sendToClient([]interface{}{msg.Kind, msg.Channel, msg.Count}); err != nil {
|
||||
if err := e.sendToClient([]any{msg.Kind, msg.Channel, msg.Count}); err != nil {
|
||||
return trace.Wrap(err)
|
||||
}
|
||||
case *redis.Pong:
|
||||
if err := e.sendToClient([]interface{}{msg.Payload}); err != nil {
|
||||
if err := e.sendToClient([]any{msg.Payload}); err != nil {
|
||||
return trace.Wrap(err)
|
||||
}
|
||||
case *redis.Message:
|
||||
var payloadResp []interface{}
|
||||
var payloadResp []any
|
||||
if msg.Pattern != "" {
|
||||
// pattern is only set when the subscription type is pmessage
|
||||
payloadResp = []interface{}{"pmessage", msg.Pattern, msg.Channel}
|
||||
payloadResp = []any{"pmessage", msg.Pattern, msg.Channel}
|
||||
} else {
|
||||
payloadResp = []interface{}{"message", msg.Channel}
|
||||
payloadResp = []any{"message", msg.Channel}
|
||||
}
|
||||
|
||||
if len(msg.PayloadSlice) > 0 {
|
||||
|
||||
@@ -137,7 +137,6 @@ func Test_parseRedisURI(t *testing.T) {
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -234,7 +234,7 @@ func (e *Engine) maybeHandleFirstHello() {
|
||||
}
|
||||
|
||||
// sendToClient sends a command to connected Redis client.
|
||||
func (e *Engine) sendToClient(vals interface{}) error {
|
||||
func (e *Engine) sendToClient(vals any) error {
|
||||
if vals == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -524,7 +524,7 @@ func (e *Engine) readClientCmd(ctx context.Context) (*redis.Cmd, error) {
|
||||
return nil, trace.Wrap(err)
|
||||
}
|
||||
|
||||
val, ok := cmd.Val().([]interface{})
|
||||
val, ok := cmd.Val().([]any)
|
||||
if !ok {
|
||||
return nil, trace.BadParameter("failed to cast Redis value to a slice, got %T", cmd.Val())
|
||||
}
|
||||
@@ -536,7 +536,7 @@ func (e *Engine) readClientCmd(ctx context.Context) (*redis.Cmd, error) {
|
||||
// "terminal" errors as second value (connection should be terminated when this happens)
|
||||
// or returns error/value as the first value. Then value should be sent back to
|
||||
// the client without terminating the connection.
|
||||
func (e *Engine) processServerResponse(cmd *redis.Cmd, err error, sessionCtx *common.Session) (interface{}, error) {
|
||||
func (e *Engine) processServerResponse(cmd *redis.Cmd, err error, sessionCtx *common.Session) (any, error) {
|
||||
value, cmdErr := cmd.Result()
|
||||
if err == nil {
|
||||
// If the server didn't return any error use cmd.Err() as server error.
|
||||
|
||||
@@ -37,7 +37,7 @@ var ErrCmdNotSupported = trace.NotImplemented("command not supported")
|
||||
// * Redis errors and Go error: go-redis returns a "human-readable" string instead of RESP compatible error message
|
||||
// * integers: go-redis converts them to string, which is not always what we want.
|
||||
// * slices: arrays are recursively converted to RESP responses.
|
||||
func WriteCmd(wr *redis.Writer, vals interface{}) error {
|
||||
func WriteCmd(wr *redis.Writer, vals any) error {
|
||||
switch val := vals.(type) {
|
||||
case nil:
|
||||
// Note: RESP3 has different sequence for nil, current nil is RESP2 compatible as the rest
|
||||
@@ -102,7 +102,7 @@ func WriteCmd(wr *redis.Writer, vals interface{}) error {
|
||||
if err := writeUinteger(wr, val); err != nil {
|
||||
return trace.Wrap(err)
|
||||
}
|
||||
case interface{}:
|
||||
case any:
|
||||
var err error
|
||||
v := reflect.ValueOf(val)
|
||||
|
||||
@@ -166,7 +166,7 @@ func writeError(wr *redis.Writer, prefix string, val error) error {
|
||||
}
|
||||
|
||||
// writeSlice converts a slice to Redis wire form.
|
||||
func writeSlice(wr *redis.Writer, vals interface{}) error {
|
||||
func writeSlice(wr *redis.Writer, vals any) error {
|
||||
v := reflect.ValueOf(vals)
|
||||
|
||||
if v.Kind() != reflect.Slice {
|
||||
@@ -182,7 +182,7 @@ func writeSlice(wr *redis.Writer, vals interface{}) error {
|
||||
return trace.Wrap(err)
|
||||
}
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
for i := range n {
|
||||
if err := WriteCmd(wr, v.Index(i).Interface()); err != nil {
|
||||
return trace.Wrap(err)
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ import (
|
||||
func TestWriteCmd(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
val interface{}
|
||||
val any
|
||||
expected []byte
|
||||
wantErr bool
|
||||
}{
|
||||
@@ -69,7 +69,7 @@ func TestWriteCmd(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "[]nil",
|
||||
val: []interface{}{nil},
|
||||
val: []any{nil},
|
||||
expected: []byte("*1\r\n$-1\r\n"),
|
||||
},
|
||||
{
|
||||
@@ -100,7 +100,6 @@ func TestWriteCmd(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -140,27 +139,27 @@ func TestMakeUnknownCommandErrorForCmd(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tests := []struct {
|
||||
name string
|
||||
command []interface{}
|
||||
command []any
|
||||
expectedError redis.RedisError
|
||||
}{
|
||||
{
|
||||
name: "HELLO",
|
||||
command: []interface{}{"HELLO", 3, "AUTH", "user", "TOKEN"},
|
||||
command: []any{"HELLO", 3, "AUTH", "user", "TOKEN"},
|
||||
expectedError: "ERR unknown command 'HELLO', with args beginning with: '3' 'AUTH' 'user' 'TOKEN'",
|
||||
},
|
||||
{
|
||||
name: "no extra args",
|
||||
command: []interface{}{"abcdef"},
|
||||
command: []any{"abcdef"},
|
||||
expectedError: "ERR unknown command 'abcdef', with args beginning with: ",
|
||||
},
|
||||
{
|
||||
name: "cluster",
|
||||
command: []interface{}{"cluster", "aaa", "bbb"},
|
||||
command: []any{"cluster", "aaa", "bbb"},
|
||||
expectedError: "ERR unknown subcommand 'aaa'. Try CLUSTER HELP.",
|
||||
},
|
||||
{
|
||||
name: "command",
|
||||
command: []interface{}{"command", "aaa", "bbb"},
|
||||
command: []any{"command", "aaa", "bbb"},
|
||||
expectedError: "ERR unknown subcommand 'aaa'. Try COMMAND HELP.",
|
||||
},
|
||||
}
|
||||
|
||||
+3
-13
@@ -25,6 +25,7 @@ import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -431,12 +432,7 @@ func (m *monitoredDatabases) setCloud(databases types.Databases) {
|
||||
// watchers, aka legacy database discovery done by the db service.
|
||||
// The lock must be held when calling this function.
|
||||
func (m *monitoredDatabases) isCloud_Locked(database types.Database) bool {
|
||||
for i := range m.cloud {
|
||||
if m.cloud[i] == database {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(m.cloud, database)
|
||||
}
|
||||
|
||||
// isDiscoveryResource_Locked returns whether a database was discovered by the
|
||||
@@ -450,12 +446,7 @@ func (m *monitoredDatabases) isDiscoveryResource_Locked(database types.Database)
|
||||
// object.
|
||||
// The lock must be held when calling this function.
|
||||
func (m *monitoredDatabases) isResource_Locked(database types.Database) bool {
|
||||
for i := range m.resources {
|
||||
if m.resources[i] == database {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(m.resources, database)
|
||||
}
|
||||
|
||||
// getLocked returns a slice containing all of the monitored databases.
|
||||
@@ -1024,7 +1015,6 @@ func (s *Server) close(ctx context.Context) error {
|
||||
// server below would be undone.
|
||||
s.mu.RLock()
|
||||
for name := range s.proxiedDatabases {
|
||||
name := name
|
||||
heartbeat := s.heartbeats[name]
|
||||
|
||||
if dynamic, ok := s.dynamicLabels[name]; ok {
|
||||
|
||||
@@ -159,7 +159,7 @@ func TestDatabaseServerLimiting(t *testing.T) {
|
||||
})
|
||||
|
||||
// Connect the maximum allowed number of clients.
|
||||
for i := int64(0); i < connLimit; i++ {
|
||||
for range connLimit {
|
||||
pgConn, err := testCtx.postgresClient(ctx, user, "postgres", dbUser, dbName)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -183,7 +183,7 @@ func TestDatabaseServerLimiting(t *testing.T) {
|
||||
}
|
||||
})
|
||||
// Connect the maximum allowed number of clients.
|
||||
for i := int64(0); i < connLimit; i++ {
|
||||
for range connLimit {
|
||||
mysqlConn, err := testCtx.mysqlClient(user, "mysql", dbUser)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -208,7 +208,7 @@ func TestDatabaseServerLimiting(t *testing.T) {
|
||||
})
|
||||
// Mongo driver behave different from MySQL and Postgres. In this case we just want to hit the limit
|
||||
// by creating some DB connections.
|
||||
for i := int64(0); i < 2*connLimit; i++ {
|
||||
for range 2 * connLimit {
|
||||
mongoConn, err := testCtx.mongoClient(ctx, user, "mongo", dbUser)
|
||||
|
||||
if err == nil {
|
||||
@@ -261,7 +261,7 @@ func TestDatabaseServerAutoDisconnect(t *testing.T) {
|
||||
|
||||
// advance clock several times, perform query.
|
||||
// the activity should update the idle activity timer.
|
||||
for i := 0; i < 10; i++ {
|
||||
for i := range 10 {
|
||||
advanceInSteps(testCtx.clock, clientIdleTimeout/2)
|
||||
_, err = pgConn.Exec(ctx, "select 1").ReadAll()
|
||||
require.NoErrorf(t, err, "failed on iteration %v", i+1)
|
||||
@@ -453,7 +453,6 @@ func TestShutdown(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -527,7 +526,7 @@ func TestTrackActiveConnections(t *testing.T) {
|
||||
|
||||
// Create a few connections, increasing the active connections. Keep track
|
||||
// of the closer functions, so we can close them later.
|
||||
for i := 0; i < numActiveConnections; i++ {
|
||||
for i := range numActiveConnections {
|
||||
expectedActiveConnections := int32(i + 1)
|
||||
conn, err := testCtx.postgresClient(ctx, "alice", "postgres", "postgres", "postgres")
|
||||
require.NoError(t, err)
|
||||
@@ -542,7 +541,7 @@ func TestTrackActiveConnections(t *testing.T) {
|
||||
}
|
||||
|
||||
// For each connection we close, the active connections should drop too.
|
||||
for i := 0; i < numActiveConnections; i++ {
|
||||
for i := range numActiveConnections {
|
||||
expectedActiveConnections := int32(numActiveConnections - (i + 1))
|
||||
require.NoError(t, closeFuncs[i]())
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ func Test_replaceLoginReqToken(t *testing.T) {
|
||||
const loginResponse = `{"data":{"CLIENT_APP_ID":"","CLIENT_APP_VERSION":"","SVN_REVISION":"","ACCOUNT_NAME":"testAccountName","AUTHENTICATOR":"SNOWFLAKE_JWT","CLIENT_ENVIRONMENT":null,"LOGIN_NAME":"alice","TOKEN":"testJWT"}}`
|
||||
|
||||
type args struct {
|
||||
loginReq map[string]interface{}
|
||||
loginReq map[string]any
|
||||
jwtToken string
|
||||
accountName string
|
||||
loginName string
|
||||
@@ -170,7 +170,7 @@ func Test_replaceLoginReqToken(t *testing.T) {
|
||||
{
|
||||
name: "base case",
|
||||
args: args{
|
||||
loginReq: map[string]interface{}{
|
||||
loginReq: map[string]any{
|
||||
"TOKEN": "testJWT",
|
||||
"ACCOUNT_NAME": "testAccountName",
|
||||
},
|
||||
@@ -183,7 +183,7 @@ func Test_replaceLoginReqToken(t *testing.T) {
|
||||
{
|
||||
name: "remove password",
|
||||
args: args{
|
||||
loginReq: map[string]interface{}{
|
||||
loginReq: map[string]any{
|
||||
"TOKEN": "testJWT",
|
||||
"ACCOUNT_NAME": "testAccountName",
|
||||
"PASSWORD": "password",
|
||||
@@ -197,7 +197,7 @@ func Test_replaceLoginReqToken(t *testing.T) {
|
||||
{
|
||||
name: "remove username",
|
||||
args: args{
|
||||
loginReq: map[string]interface{}{
|
||||
loginReq: map[string]any{
|
||||
"TOKEN": "testJWT",
|
||||
"ACCOUNT_NAME": "testAccountName",
|
||||
"LOGIN_NAME": "alice",
|
||||
@@ -211,7 +211,7 @@ func Test_replaceLoginReqToken(t *testing.T) {
|
||||
{
|
||||
name: "replace authenticator username",
|
||||
args: args{
|
||||
loginReq: map[string]interface{}{
|
||||
loginReq: map[string]any{
|
||||
"TOKEN": "testJWT",
|
||||
"ACCOUNT_NAME": "testAccountName",
|
||||
"AUTHENTICATOR": "PASSWORD",
|
||||
@@ -225,7 +225,7 @@ func Test_replaceLoginReqToken(t *testing.T) {
|
||||
{
|
||||
name: "replace login name",
|
||||
args: args{
|
||||
loginReq: map[string]interface{}{
|
||||
loginReq: map[string]any{
|
||||
"TOKEN": "testJWT",
|
||||
"ACCOUNT_NAME": "testAccountName",
|
||||
"AUTHENTICATOR": "PASSWORD",
|
||||
|
||||
@@ -56,13 +56,13 @@ type loginResponseData struct {
|
||||
|
||||
// allFields contains all fields from the JSON. Those fields will
|
||||
// be added when marshaling JSON.
|
||||
allFields map[string]interface{}
|
||||
allFields map[string]any
|
||||
}
|
||||
|
||||
func (l *loginResponseData) MarshalJSON() ([]byte, error) {
|
||||
elems := reflect.TypeOf(l).Elem()
|
||||
|
||||
for i := 0; i < elems.NumField(); i++ {
|
||||
for i := range elems.NumField() {
|
||||
jsonTag, ok := elems.Field(i).Tag.Lookup("json")
|
||||
if !ok {
|
||||
continue
|
||||
@@ -93,8 +93,8 @@ func (l *loginResponseData) UnmarshalJSON(data []byte) error {
|
||||
// loginResponse is the payload returned by the /queries/v1/query-request endpoint.
|
||||
type loginResponse struct {
|
||||
Data loginResponseData `json:"data"`
|
||||
Code interface{} `json:"code"`
|
||||
Message interface{} `json:"message"`
|
||||
Code any `json:"code"`
|
||||
Message any `json:"message"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
@@ -151,14 +151,14 @@ type renewSessionResponse struct {
|
||||
// SQL query that we need to log.
|
||||
type queryRequest struct {
|
||||
SQLText string `json:"sqlText"`
|
||||
Parameters map[string]interface{} `json:"parameters,omitempty"`
|
||||
Parameters map[string]any `json:"parameters,omitempty"`
|
||||
Bindings map[string]execBindParameter `json:"bindings,omitempty"`
|
||||
BindStage string `json:"bindStage,omitempty"`
|
||||
}
|
||||
|
||||
type execBindParameter struct {
|
||||
Type string `json:"type"`
|
||||
Value interface{} `json:"value"`
|
||||
Type string `json:"type"`
|
||||
Value any `json:"value"`
|
||||
}
|
||||
|
||||
func (q *queryRequest) paramsToSlice() []string {
|
||||
@@ -174,7 +174,7 @@ func (q *queryRequest) paramsToSlice() []string {
|
||||
return args
|
||||
}
|
||||
|
||||
func queryParametersToSlice(parameters map[string]interface{}) []string {
|
||||
func queryParametersToSlice(parameters map[string]any) []string {
|
||||
params := make([]string, 0)
|
||||
|
||||
for k, v := range parameters {
|
||||
|
||||
@@ -151,7 +151,6 @@ func TestAccessSnowflake(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
// Create user/role with the requested permissions.
|
||||
testCtx.createUserAndRole(ctx, t, test.user, test.role, test.allowDbUsers, test.allowDbNames)
|
||||
|
||||
@@ -31,10 +31,10 @@ import (
|
||||
func unaryServerLoggingInterceptor(ctx context.Context, log *slog.Logger) grpc.UnaryServerInterceptor {
|
||||
return func(
|
||||
ctx context.Context,
|
||||
req interface{},
|
||||
req any,
|
||||
info *grpc.UnaryServerInfo,
|
||||
handler grpc.UnaryHandler,
|
||||
) (interface{}, error) {
|
||||
) (any, error) {
|
||||
res, err := handler(ctx, req)
|
||||
logRPC(ctx, log, info.FullMethod, err)
|
||||
return res, err
|
||||
@@ -44,7 +44,7 @@ func unaryServerLoggingInterceptor(ctx context.Context, log *slog.Logger) grpc.U
|
||||
// streamServerLoggingInterceptor is gRPC middleware that logs some debug info.
|
||||
func streamServerLoggingInterceptor(ctx context.Context, log *slog.Logger) grpc.StreamServerInterceptor {
|
||||
return func(
|
||||
srv interface{},
|
||||
srv any,
|
||||
stream grpc.ServerStream,
|
||||
info *grpc.StreamServerInfo,
|
||||
handler grpc.StreamHandler,
|
||||
|
||||
@@ -197,10 +197,10 @@ func NewTestServer(config common.TestServerConfig) (tsrv *TestServer, err error)
|
||||
func unaryAuthInterceptor(c credentialChecker) grpc.UnaryServerInterceptor {
|
||||
return func(
|
||||
ctx context.Context,
|
||||
req interface{},
|
||||
req any,
|
||||
info *grpc.UnaryServerInfo,
|
||||
handler grpc.UnaryHandler,
|
||||
) (interface{}, error) {
|
||||
) (any, error) {
|
||||
if err := c.check(ctx); err != nil {
|
||||
return nil, trace.Wrap(err)
|
||||
}
|
||||
@@ -210,7 +210,7 @@ func unaryAuthInterceptor(c credentialChecker) grpc.UnaryServerInterceptor {
|
||||
|
||||
func streamingAuthInterceptor(c credentialChecker) grpc.StreamServerInterceptor {
|
||||
return func(
|
||||
srv interface{},
|
||||
srv any,
|
||||
stream grpc.ServerStream,
|
||||
info *grpc.StreamServerInfo,
|
||||
handler grpc.StreamHandler,
|
||||
@@ -260,7 +260,7 @@ func (s *TestServer) BatchCreateSessions(ctx context.Context, req *spannerpb.Bat
|
||||
tpl = &spannerpb.Session{CreatorRole: "test"}
|
||||
}
|
||||
var sessions []*spannerpb.Session
|
||||
for i := 0; i < int(req.SessionCount); i++ {
|
||||
for range int(req.SessionCount) {
|
||||
name := req.GetDatabase() + "/sessions/" + uuid.NewString()
|
||||
sessions = append(sessions, &spannerpb.Session{
|
||||
Name: name,
|
||||
|
||||
@@ -61,7 +61,7 @@ func TestConnectorSelection(t *testing.T) {
|
||||
},
|
||||
// When using a non-Azure database, the connector should fail
|
||||
// loading Kerberos credentials.
|
||||
errAssertion: func(t require.TestingT, err error, _ ...interface{}) {
|
||||
errAssertion: func(t require.TestingT, err error, _ ...any) {
|
||||
require.ErrorContains(t, err, unimplementedMessage)
|
||||
},
|
||||
},
|
||||
@@ -77,7 +77,7 @@ func TestConnectorSelection(t *testing.T) {
|
||||
},
|
||||
// When using a Azure database with AD configuration, the connector
|
||||
// should fail loading Kerberos credentials.
|
||||
errAssertion: func(t require.TestingT, err error, _ ...interface{}) {
|
||||
errAssertion: func(t require.TestingT, err error, _ ...any) {
|
||||
require.ErrorContains(t, err, unimplementedMessage)
|
||||
},
|
||||
},
|
||||
@@ -90,7 +90,7 @@ func TestConnectorSelection(t *testing.T) {
|
||||
// When using a Azure database without AD configuration, the
|
||||
// connector should fail because it could not connect to the
|
||||
// database.
|
||||
errAssertion: func(t require.TestingT, err error, _ ...interface{}) {
|
||||
errAssertion: func(t require.TestingT, err error, _ ...any) {
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "unable to open tcp connection with host")
|
||||
},
|
||||
@@ -108,7 +108,7 @@ func TestConnectorSelection(t *testing.T) {
|
||||
},
|
||||
// RDS proxies cannot be accessed outside their VPC. So, this test
|
||||
// case should not resolve their host.
|
||||
errAssertion: func(t require.TestingT, err error, _ ...interface{}) {
|
||||
errAssertion: func(t require.TestingT, err error, _ ...any) {
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "no such host")
|
||||
},
|
||||
|
||||
@@ -368,7 +368,7 @@ func TestHandleConnectionAuditEvents(t *testing.T) {
|
||||
// intercalateChunkedPacketMessages intercalates a chunked packet with a regular packet a specified number of times.
|
||||
func intercalateChunkedPacketMessages(chunkedPacket [][]byte, regularPacket []byte, repeat int) [][]byte {
|
||||
var result [][]byte
|
||||
for i := 0; i < repeat; i++ {
|
||||
for range repeat {
|
||||
result = append(result, chunkedPacket...)
|
||||
result = append(result, regularPacket)
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ func toRPCRequest(p Packet) (*RPCRequest, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getParameters(val interface{}) []string {
|
||||
func getParameters(val any) []string {
|
||||
if val == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -436,9 +436,7 @@ func makeDatabase(name string, labels map[string]string, additionalLabels map[st
|
||||
labels = make(map[string]string)
|
||||
}
|
||||
|
||||
for k, v := range additionalLabels {
|
||||
labels[k] = v
|
||||
}
|
||||
maps.Copy(labels, additionalLabels)
|
||||
|
||||
ds := types.DatabaseSpecV3{
|
||||
Protocol: defaults.ProtocolPostgres,
|
||||
|
||||
@@ -595,7 +595,7 @@ func fillReadRequestCache(cache *sharedDirectoryAuditCache, did directoryID) {
|
||||
cache.Lock()
|
||||
defer cache.Unlock()
|
||||
|
||||
for i := 0; i < maxAuditCacheItems; i++ {
|
||||
for i := range maxAuditCacheItems {
|
||||
cache.readRequestCache[completionID(i)] = readRequestInfo{
|
||||
directoryID: did,
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
@@ -1195,9 +1196,7 @@ func (s *WindowsService) staticHostHeartbeatInfo(host servicecfg.WindowsHost,
|
||||
return func() (types.Resource, error) {
|
||||
addr := host.Address.String()
|
||||
labels := getHostLabels(addr)
|
||||
for k, v := range host.Labels {
|
||||
labels[k] = v
|
||||
}
|
||||
maps.Copy(labels, host.Labels)
|
||||
name := host.Name
|
||||
if name == "" {
|
||||
var err error
|
||||
|
||||
@@ -118,7 +118,7 @@ func (s *Server) reconcileAccessGraph(ctx context.Context, currentTAGResources *
|
||||
errs := make([]error, 0, len(allFetchers))
|
||||
// Collect the results from all fetchers.
|
||||
// Each fetcher can return an error and a result.
|
||||
for i := 0; i < len(allFetchers); i++ {
|
||||
for range allFetchers {
|
||||
fetcherResult := <-resultsC
|
||||
if fetcherResult.err != nil {
|
||||
errs = append(errs, fetcherResult.err)
|
||||
@@ -213,10 +213,7 @@ func pushUpsertInBatches(
|
||||
upsert *accessgraphv1alpha.AWSResourceList,
|
||||
) error {
|
||||
for i := 0; i < len(upsert.Resources); i += batchSize {
|
||||
end := i + batchSize
|
||||
if end > len(upsert.Resources) {
|
||||
end = len(upsert.Resources)
|
||||
}
|
||||
end := min(i+batchSize, len(upsert.Resources))
|
||||
err := client.Send(
|
||||
&accessgraphv1alpha.AWSEventsStreamRequest{
|
||||
Operation: &accessgraphv1alpha.AWSEventsStreamRequest_Upsert{
|
||||
@@ -238,10 +235,7 @@ func pushDeleteInBatches(
|
||||
toDel *accessgraphv1alpha.AWSResourceList,
|
||||
) error {
|
||||
for i := 0; i < len(toDel.Resources); i += batchSize {
|
||||
end := i + batchSize
|
||||
if end > len(toDel.Resources) {
|
||||
end = len(toDel.Resources)
|
||||
}
|
||||
end := min(i+batchSize, len(toDel.Resources))
|
||||
err := client.Send(
|
||||
&accessgraphv1alpha.AWSEventsStreamRequest{
|
||||
Operation: &accessgraphv1alpha.AWSEventsStreamRequest_Delete{
|
||||
@@ -925,7 +919,7 @@ func (s *Server) pollEventsFromSQSFilesImpl(ctx context.Context,
|
||||
) error {
|
||||
parallelDownloads := make(chan struct{}, 60)
|
||||
errG, ctx := errgroup.WithContext(ctx)
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
errG.Go(
|
||||
s.processMessagesWorker(
|
||||
ctx,
|
||||
|
||||
@@ -77,7 +77,6 @@ func (s *Server) reconcileAccessGraphAzure(
|
||||
tokens := make(chan struct{}, 3)
|
||||
accountIds := map[string]struct{}{}
|
||||
for _, fetcher := range allFetchers {
|
||||
fetcher := fetcher
|
||||
accountIds[fetcher.GetSubscriptionID()] = struct{}{}
|
||||
tokens <- struct{}{}
|
||||
go func() {
|
||||
@@ -92,7 +91,7 @@ func (s *Server) reconcileAccessGraphAzure(
|
||||
// Collect the results from all fetchers.
|
||||
results := make([]*azuresync.Resources, 0, len(allFetchers))
|
||||
errs := make([]error, 0, len(allFetchers))
|
||||
for i := 0; i < len(allFetchers); i++ {
|
||||
for range allFetchers {
|
||||
// Each fetcher can return an error and a result.
|
||||
fetcherResult := <-resultsC
|
||||
if fetcherResult.err != nil {
|
||||
@@ -137,10 +136,7 @@ func azurePushUpsertInBatches(
|
||||
upsert *accessgraphv1alpha.AzureResourceList,
|
||||
) error {
|
||||
for i := 0; i < len(upsert.Resources); i += batchSize {
|
||||
end := i + batchSize
|
||||
if end > len(upsert.Resources) {
|
||||
end = len(upsert.Resources)
|
||||
}
|
||||
end := min(i+batchSize, len(upsert.Resources))
|
||||
err := client.Send(
|
||||
&accessgraphv1alpha.AzureEventsStreamRequest{
|
||||
Operation: &accessgraphv1alpha.AzureEventsStreamRequest_Upsert{
|
||||
@@ -163,10 +159,7 @@ func azurePushDeleteInBatches(
|
||||
toDel *accessgraphv1alpha.AzureResourceList,
|
||||
) error {
|
||||
for i := 0; i < len(toDel.Resources); i += batchSize {
|
||||
end := i + batchSize
|
||||
if end > len(toDel.Resources) {
|
||||
end = len(toDel.Resources)
|
||||
}
|
||||
end := min(i+batchSize, len(toDel.Resources))
|
||||
err := client.Send(
|
||||
&accessgraphv1alpha.AzureEventsStreamRequest{
|
||||
Operation: &accessgraphv1alpha.AzureEventsStreamRequest_Delete{
|
||||
|
||||
@@ -1967,7 +1967,6 @@ func TestGetLabelEngineVersion(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -1997,7 +1996,7 @@ func TestNewDatabaseFromAzureSQLServer(t *testing.T) {
|
||||
},
|
||||
},
|
||||
expectedErr: require.NoError,
|
||||
expectedDB: func(t require.TestingT, i interface{}, _ ...interface{}) {
|
||||
expectedDB: func(t require.TestingT, i any, _ ...any) {
|
||||
db, ok := i.(types.Database)
|
||||
require.True(t, ok, "expected types.Database, got %T", i)
|
||||
|
||||
@@ -2052,7 +2051,7 @@ func TestNewDatabaseFromAzureManagedSQLServer(t *testing.T) {
|
||||
},
|
||||
},
|
||||
expectedErr: require.NoError,
|
||||
expectedDB: func(t require.TestingT, i interface{}, _ ...interface{}) {
|
||||
expectedDB: func(t require.TestingT, i any, _ ...any) {
|
||||
db, ok := i.(types.Database)
|
||||
require.True(t, ok, "expected types.Database, got %T", i)
|
||||
|
||||
@@ -2129,7 +2128,6 @@ func TestDatabaseFromAzureMySQLFlexServer(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
rid := makeAzureResourceID(subID, group, provider, tt.serverName)
|
||||
@@ -2207,7 +2205,6 @@ func TestDatabaseFromAzurePostgresFlexServer(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
rid := makeAzureResourceID(subID, group, provider, tt.serverName)
|
||||
@@ -2316,7 +2313,6 @@ func TestMakeAzureDatabaseLoginUsername(t *testing.T) {
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
db, err := types.NewDatabaseV3(types.Metadata{
|
||||
|
||||
@@ -490,7 +490,6 @@ func makeAzureRedisEnterpriseDB(t *testing.T, name, region, group, subscription
|
||||
func labelsToAzureTags(labels map[string]string) map[string]*string {
|
||||
tags := make(map[string]*string, len(labels))
|
||||
for k, v := range labels {
|
||||
v := v
|
||||
tags[k] = &v
|
||||
}
|
||||
return tags
|
||||
|
||||
@@ -34,8 +34,7 @@ import (
|
||||
func TestWatcher(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
app1, err := types.NewAppV3(types.Metadata{Name: "app1"}, types.AppSpecV3{Cloud: types.CloudAWS})
|
||||
require.NoError(t, err)
|
||||
@@ -89,8 +88,7 @@ func TestWatcher(t *testing.T) {
|
||||
func TestWatcherWithDynamicFetchers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
app1, err := types.NewAppV3(types.Metadata{Name: "app1"}, types.AppSpecV3{Cloud: types.CloudAWS})
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -171,7 +171,7 @@ func (m *mockEC2Client) DescribeInstances(ctx context.Context, input *ec2.Descri
|
||||
|
||||
func genEC2InstanceIDs(n int) []string {
|
||||
var ec2InstanceIDs []string
|
||||
for i := 0; i < n; i++ {
|
||||
for i := range n {
|
||||
ec2InstanceIDs = append(ec2InstanceIDs, fmt.Sprintf("instance-id-%d", i))
|
||||
}
|
||||
return ec2InstanceIDs
|
||||
@@ -1288,7 +1288,6 @@ func TestDiscoveryKubeServices(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -1752,7 +1751,7 @@ func TestDiscoveryServer_New(t *testing.T) {
|
||||
|
||||
cloudClients: &mockFetchersClients{},
|
||||
matchers: Matchers{},
|
||||
errAssertion: func(t require.TestingT, err error, i ...interface{}) {
|
||||
errAssertion: func(t require.TestingT, err error, i ...any) {
|
||||
require.ErrorIs(t, err, &trace.BadParameterError{Message: "no matchers or discovery group configured for discovery"})
|
||||
},
|
||||
discServerAssertion: require.Nil,
|
||||
@@ -1776,7 +1775,7 @@ func TestDiscoveryServer_New(t *testing.T) {
|
||||
},
|
||||
},
|
||||
errAssertion: require.NoError,
|
||||
discServerAssertion: func(t require.TestingT, i interface{}, i2 ...interface{}) {
|
||||
discServerAssertion: func(t require.TestingT, i any, i2 ...any) {
|
||||
require.NotNil(t, i)
|
||||
val, ok := i.(*Server)
|
||||
require.True(t, ok)
|
||||
@@ -1809,7 +1808,7 @@ func TestDiscoveryServer_New(t *testing.T) {
|
||||
},
|
||||
},
|
||||
errAssertion: require.NoError,
|
||||
discServerAssertion: func(t require.TestingT, i interface{}, i2 ...interface{}) {
|
||||
discServerAssertion: func(t require.TestingT, i any, i2 ...any) {
|
||||
require.NotNil(t, i)
|
||||
val, ok := i.(*Server)
|
||||
require.True(t, ok)
|
||||
@@ -1820,8 +1819,7 @@ func TestDiscoveryServer_New(t *testing.T) {
|
||||
|
||||
for _, tt := range testCases {
|
||||
t.Run(tt.desc, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
discServer, err := New(
|
||||
ctx,
|
||||
@@ -3160,7 +3158,6 @@ func TestAzureVMDiscovery(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -3468,7 +3465,6 @@ func TestGCPVMDiscovery(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -210,7 +210,7 @@ func (r *Resources) count() int {
|
||||
|
||||
elem := reflect.ValueOf(r).Elem()
|
||||
sum := 0
|
||||
for i := 0; i < elem.NumField(); i++ {
|
||||
for i := range elem.NumField() {
|
||||
field := elem.Field(i)
|
||||
if field.IsValid() {
|
||||
switch field.Kind() {
|
||||
|
||||
@@ -81,7 +81,6 @@ func (a *Fetcher) fetchAWSEC2Instances(ctx context.Context) ([]*accessgraphv1alp
|
||||
}
|
||||
|
||||
for _, region := range a.Regions {
|
||||
region := region
|
||||
eG.Go(func() error {
|
||||
prevIterationEc2 := sliceFilter(
|
||||
existing,
|
||||
|
||||
@@ -101,7 +101,6 @@ func (a *Fetcher) fetchAWSSEKSClusters(ctx context.Context) (fetchAWSEKSClusters
|
||||
}
|
||||
|
||||
for _, region := range a.Regions {
|
||||
region := region
|
||||
eG.Go(func() error {
|
||||
eksClient, err := a.GetEKSClient(ctx, region, a.getAWSOptions()...)
|
||||
if err != nil {
|
||||
|
||||
@@ -53,7 +53,6 @@ func (a *Fetcher) pollAWSGroups(ctx context.Context, result *Resources, collectE
|
||||
groupsMu := sync.Mutex{}
|
||||
var existing = a.lastResult
|
||||
for _, group := range result.Groups {
|
||||
group := group
|
||||
eG.Go(func() error {
|
||||
groupInlinePolicies, err := a.fetchGroupInlinePolicies(ctx, group)
|
||||
if err != nil {
|
||||
|
||||
@@ -79,7 +79,6 @@ func (a *Fetcher) fetchAWSRDSDatabases(ctx context.Context) (
|
||||
}
|
||||
|
||||
for _, region := range a.Regions {
|
||||
region := region
|
||||
eG.Go(func() error {
|
||||
awsCfg, err := a.AWSConfigProvider.GetConfig(ctx, region, a.getAWSOptions()...)
|
||||
if err != nil {
|
||||
|
||||
@@ -57,7 +57,6 @@ func (a *Fetcher) pollAWSRoles(ctx context.Context, result *Resources, collectEr
|
||||
eG.SetLimit(5)
|
||||
roleMu := sync.Mutex{}
|
||||
for _, role := range result.Roles {
|
||||
role := role
|
||||
eG.Go(func() error {
|
||||
roleInlinePolicies, err := a.fetchRoleInlinePolicies(ctx, role)
|
||||
if err != nil {
|
||||
|
||||
@@ -90,7 +90,6 @@ func (a *Fetcher) fetchS3Buckets(ctx context.Context) ([]*accessgraphv1alpha.AWS
|
||||
|
||||
// Iterate over the buckets and fetch their inline and attached policies.
|
||||
for _, bucket := range buckets {
|
||||
bucket := bucket
|
||||
eG.Go(func() error {
|
||||
var failedReqs failedRequests
|
||||
var errs []error
|
||||
|
||||
@@ -54,7 +54,6 @@ func (a *Fetcher) pollAWSUsers(ctx context.Context, result, existing *Resources,
|
||||
// fetch user inline policies, attached policies, and groups in parallel
|
||||
// and collect the results.
|
||||
for _, user := range result.Users {
|
||||
user := user
|
||||
eG.Go(func() error {
|
||||
userInlinePolicies, err := a.fetchUserInlinePolicies(ctx, user)
|
||||
if err != nil {
|
||||
|
||||
@@ -298,7 +298,6 @@ func TestAzureDBServerFetchers(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -422,7 +421,6 @@ func withAzurePostgresVersion(version string) func(*armpostgresql.Server) {
|
||||
func labelsToAzureTags(labels map[string]string) map[string]*string {
|
||||
tags := make(map[string]*string, len(labels))
|
||||
for k, v := range labels {
|
||||
v := v
|
||||
tags[k] = &v
|
||||
}
|
||||
return tags
|
||||
|
||||
@@ -122,7 +122,6 @@ type awsFetcherTest struct {
|
||||
func testAWSFetchers(t *testing.T, tests ...awsFetcherTest) {
|
||||
t.Helper()
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
fakeSTS := &mocks.STSClient{}
|
||||
require.Nil(t, test.fetcherCfg.AWSConfigProvider, "testAWSFetchers injects a fake AWSConfigProvider, but the test input had already configured it. This is a test configuration error.")
|
||||
test.fetcherCfg.AWSConfigProvider = &mocks.AWSConfigProvider{
|
||||
|
||||
@@ -178,7 +178,6 @@ func (f *KubeAppFetcher) Get(ctx context.Context) (types.ResourcesWithLabels, er
|
||||
apps types.Apps
|
||||
)
|
||||
for _, service := range kubeServices {
|
||||
service := service
|
||||
g.Go(func() error {
|
||||
protocolAnnotation := service.GetAnnotations()[types.DiscoveryProtocolLabel]
|
||||
|
||||
|
||||
@@ -276,7 +276,6 @@ func TestKubeAppFetcher_Get(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.desc, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ package discovery
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -468,9 +469,7 @@ func mustConvertEKSToKubeServerV1(t *testing.T, eksCluster *ekstypes.Cluster, re
|
||||
|
||||
func mustConvertEKSToKubeServerV2(t *testing.T, eksCluster *ekstypes.Cluster, resourceID, _ string) types.KubeServer {
|
||||
eksTags := make(map[string]string, len(eksCluster.Tags))
|
||||
for k, v := range eksCluster.Tags {
|
||||
eksTags[k] = v
|
||||
}
|
||||
maps.Copy(eksTags, eksCluster.Tags)
|
||||
eksTags[types.OriginLabel] = types.OriginCloud
|
||||
eksTags[types.InternalResourceIDLabel] = resourceID
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ func TestGetUpsertBatchSize(t *testing.T) {
|
||||
|
||||
func generateServerInfos(t *testing.T, n int) []types.ServerInfo {
|
||||
serverInfos := make([]types.ServerInfo, 0, n)
|
||||
for i := 0; i < n; i++ {
|
||||
for i := range n {
|
||||
si, err := types.NewServerInfo(types.Metadata{
|
||||
Name: fmt.Sprintf("instance-%d", i),
|
||||
Labels: map[string]string{"foo": "bar"},
|
||||
@@ -129,7 +129,7 @@ func TestLabelReconciler(t *testing.T) {
|
||||
}
|
||||
|
||||
clock.BlockUntil(1)
|
||||
for i := 0; i < 5; i++ {
|
||||
for i := range 5 {
|
||||
clock.Advance(time.Second)
|
||||
var upsertedServerInfos []types.ServerInfo
|
||||
outer:
|
||||
|
||||
@@ -136,7 +136,6 @@ func TestSignersWithSHA1Fallback(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -214,7 +213,6 @@ func TestDirectTCPIP(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range cases {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -250,7 +248,6 @@ func TestCheckTCPIPForward(t *testing.T) {
|
||||
},
|
||||
}
|
||||
for _, tt := range cases {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -132,7 +132,7 @@ func Test_checkSSHCommand(t *testing.T) {
|
||||
name: "org does not match",
|
||||
server: server,
|
||||
sshCommand: "git-upload-pack 'some-other-org/my-repo.git'",
|
||||
checkError: func(t require.TestingT, err error, i ...interface{}) {
|
||||
checkError: func(t require.TestingT, err error, i ...any) {
|
||||
require.True(t, trace.IsAccessDenied(err), i...)
|
||||
},
|
||||
},
|
||||
|
||||
@@ -204,12 +204,10 @@ func TestForwardServer(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
mockEmitter := &eventstest.MockRecorderEmitter{}
|
||||
mockGitService := newMockGitHostingService(t, caSigner)
|
||||
|
||||
@@ -135,7 +135,7 @@ func TestMakeGitHubSigner(t *testing.T) {
|
||||
IdentityExpires: clock.Now().Add(time.Minute),
|
||||
Clock: clock,
|
||||
},
|
||||
checkError: func(t require.TestingT, err error, i ...interface{}) {
|
||||
checkError: func(t require.TestingT, err error, i ...any) {
|
||||
require.True(t, trace.IsBadParameter(err), i...)
|
||||
},
|
||||
},
|
||||
|
||||
@@ -118,8 +118,7 @@ func TestHeartbeatKeepAlive(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
clock := clockwork.NewFakeClock()
|
||||
announcer := newFakeAnnouncer(ctx)
|
||||
|
||||
@@ -244,8 +243,7 @@ func TestHeartbeatAnnounce(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.mode.String(), func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
clock := clockwork.NewFakeClock()
|
||||
|
||||
announcer := newFakeAnnouncer(ctx)
|
||||
|
||||
@@ -169,8 +169,7 @@ func newFakeHeartbeatDriver(t *testing.T) *fakeHeartbeatDriver {
|
||||
func TestHeartbeatV2Basics(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
// set up fake hb driver that lets us easily inject failures for
|
||||
// the diff steps and assists w/ faking inventory control handles.
|
||||
@@ -296,8 +295,7 @@ func TestHeartbeatV2Basics(t *testing.T) {
|
||||
func TestHeartbeatV2NoFallbackUnchecked(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
// set up fake hb driver that lets us easily inject failures for
|
||||
// the diff steps and assists w/ faking inventory control handles.
|
||||
@@ -353,8 +351,7 @@ func TestHeartbeatV2NoFallbackUnchecked(t *testing.T) {
|
||||
func TestHeartbeatV2NoFallbackChecked(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
// set up fake hb driver that lets us easily inject failures for
|
||||
// the diff steps and assists w/ faking inventory control handles.
|
||||
|
||||
+5
-10
@@ -69,8 +69,7 @@ func newTestMonitor(ctx context.Context, t *testing.T, asrv *auth.TestAuthServer
|
||||
func TestConnectionMonitorLockInForce(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
asrv, err := auth.NewTestAuthServer(auth.TestAuthServerConfig{
|
||||
Dir: t.TempDir(),
|
||||
@@ -161,8 +160,7 @@ func TestConnectionMonitorLockInForce(t *testing.T) {
|
||||
func TestMonitorLockInForce(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
asrv, err := auth.NewTestAuthServer(auth.TestAuthServerConfig{
|
||||
Dir: t.TempDir(),
|
||||
@@ -209,8 +207,7 @@ func TestMonitorLockInForce(t *testing.T) {
|
||||
func TestMonitorStaleLocks(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
asrv, err := auth.NewTestAuthServer(auth.TestAuthServerConfig{
|
||||
Dir: t.TempDir(),
|
||||
@@ -271,8 +268,7 @@ func TestWritesDisconnectMessage(t *testing.T) {
|
||||
|
||||
var sw strings.Builder
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
clock := clockwork.NewFakeClock()
|
||||
conn, _, _ := newTestMonitor(ctx, t, asrv, func(cfg *MonitorConfig) {
|
||||
@@ -315,8 +311,7 @@ func TestMonitorDisconnectExpiredCertBeforeTimeNow(t *testing.T) {
|
||||
clock := clockwork.NewRealClock()
|
||||
|
||||
certExpirationTime := clock.Now().Add(-1 * time.Second)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
asrv, err := auth.NewTestAuthServer(auth.TestAuthServerConfig{
|
||||
Dir: t.TempDir(),
|
||||
|
||||
+3
-8
@@ -33,6 +33,7 @@ import (
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
@@ -538,13 +539,7 @@ func (o *osWrapper) startNewParker(ctx context.Context, credential *syscall.Cred
|
||||
return trace.Wrap(err)
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, localUserGroup := range groups {
|
||||
if localUserGroup == group.Gid {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
found := slices.Contains(groups, group.Gid)
|
||||
|
||||
if !found {
|
||||
// Check if the new user guid matches the TeleportDropGroup. If not
|
||||
@@ -1139,7 +1134,7 @@ func buildCommand(c *ExecCommand, localUser *user.User, tty *os.File, pamEnviron
|
||||
// to the grandchild.
|
||||
if c.ExtraFilesLen > 0 {
|
||||
cmd.ExtraFiles = make([]*os.File, c.ExtraFilesLen)
|
||||
for i := 0; i < c.ExtraFilesLen; i++ {
|
||||
for i := range c.ExtraFilesLen {
|
||||
fd := FirstExtraFile + uintptr(i)
|
||||
f := os.NewFile(fd, strconv.Itoa(int(fd)))
|
||||
if f == nil {
|
||||
|
||||
@@ -176,7 +176,6 @@ func TestStartNewParker(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
osPack, assertExpected := tt.newOsPack(t)
|
||||
|
||||
@@ -236,7 +236,7 @@ func (s *sftpSubsys) Wait() error {
|
||||
})
|
||||
|
||||
errs := []error{waitErr}
|
||||
for i := 0; i < copyingGoroutines; i++ {
|
||||
for range copyingGoroutines {
|
||||
err := <-s.errCh
|
||||
if err != nil && !utils.IsOKNetworkError(err) {
|
||||
s.logger.WarnContext(ctx, "Connection problem", "error", err)
|
||||
|
||||
@@ -1075,9 +1075,7 @@ func (s *Server) getDynamicLabels() map[string]types.CommandLabelV2 {
|
||||
// getAllLabels return a combination of static and dynamic labels.
|
||||
func (s *Server) getAllLabels() map[string]string {
|
||||
lmap := make(map[string]string)
|
||||
for key, value := range s.getStaticLabels() {
|
||||
lmap[key] = value
|
||||
}
|
||||
maps.Copy(lmap, s.getStaticLabels())
|
||||
for key, cmd := range s.getDynamicLabels() {
|
||||
lmap[key] = cmd.Result
|
||||
}
|
||||
|
||||
@@ -318,8 +318,7 @@ func newCustomFixture(t testing.TB, mutateCfg func(*auth.TestServerConfig), sshO
|
||||
// requests a reply whether processing the request was successful or not.
|
||||
func TestTerminalSizeRequest(t *testing.T) {
|
||||
f := newFixtureWithoutDiskBasedLogging(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
t.Run("Invalid session", func(t *testing.T) {
|
||||
ok, resp, err := f.ssh.clt.SendRequest(ctx, teleport.TerminalSizeRequest, true, []byte("1234"))
|
||||
@@ -388,8 +387,7 @@ func TestTerminalSizeRequest(t *testing.T) {
|
||||
// conditions on this code path.
|
||||
func TestMultipleExecCommands(t *testing.T) {
|
||||
f := newFixtureWithoutDiskBasedLogging(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
// Set up a mock emitter so we can capture audit events.
|
||||
emitter := eventstest.NewChannelEmitter(32)
|
||||
@@ -1187,7 +1185,7 @@ func TestMaxSessions(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
defer clientConn.Close()
|
||||
|
||||
for i := int64(0); i < maxSessions; i++ {
|
||||
for range maxSessions {
|
||||
se, err := clientConn.NewSession(ctx)
|
||||
require.NoError(t, err)
|
||||
defer se.Close()
|
||||
@@ -1390,7 +1388,7 @@ func TestX11Forward(t *testing.T) {
|
||||
errCh <- x11EchoRequest(serverDisplay2)
|
||||
}()
|
||||
|
||||
for i := 0; i < 4; i++ {
|
||||
for range 4 {
|
||||
select {
|
||||
case err := <-errCh:
|
||||
assert.NoError(t, err)
|
||||
@@ -1907,14 +1905,14 @@ func TestProxyRoundRobin(t *testing.T) {
|
||||
_, err = newUpack(f.testSrv, "user1", []string{f.user}, wildcardAllow)
|
||||
require.NoError(t, err)
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
for range 3 {
|
||||
testClient(t, f, proxy.Addr(), f.ssh.srvAddress, f.ssh.srv.Addr(), sshConfig)
|
||||
}
|
||||
|
||||
// close first connection, and test it again
|
||||
pool1.Stop()
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
for range 3 {
|
||||
testClient(t, f, proxy.Addr(), f.ssh.srvAddress, f.ssh.srv.Addr(), sshConfig)
|
||||
}
|
||||
}
|
||||
@@ -2349,7 +2347,6 @@ func TestGlobalRequestClusterDetails(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, tt := range cases {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -2792,8 +2789,7 @@ func TestX11ProxySupport(t *testing.T) {
|
||||
t.Parallel()
|
||||
f := newFixture(t)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
// set cluster config to record at the proxy
|
||||
recConfig, err := types.NewSessionRecordingConfigFromConfigFile(types.SessionRecordingConfigSpecV2{
|
||||
@@ -3150,7 +3146,7 @@ type upack struct {
|
||||
key []byte
|
||||
|
||||
// pkey is parsed private SSH key
|
||||
pkey interface{}
|
||||
pkey any
|
||||
|
||||
// pub is a public user key
|
||||
pub []byte
|
||||
@@ -3443,8 +3439,7 @@ func TestHostUserCreationProxy(t *testing.T) {
|
||||
func TestObtainFallbackUID(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx := t.Context()
|
||||
|
||||
type testCase struct {
|
||||
config *types.StableUNIXUserConfig
|
||||
|
||||
@@ -85,7 +85,7 @@ func executeCommand(tb testing.TB, clt *tracessh.Client, command string, executi
|
||||
tb.Helper()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < executions; i++ {
|
||||
for range executions {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
@@ -64,7 +64,6 @@ func (ai *AzureInstaller) Run(ctx context.Context, req AzureRunRequest) error {
|
||||
g.SetLimit(10)
|
||||
|
||||
for _, inst := range req.Instances {
|
||||
inst := inst
|
||||
g.Go(func() error {
|
||||
runRequest := azure.RunCommandRequest{
|
||||
Region: req.Region,
|
||||
|
||||
@@ -393,10 +393,7 @@ func (f *ec2InstanceFetcher) GetMatchingInstances(nodes []types.Server, rotation
|
||||
func chunkInstances(insts EC2Instances) []Instances {
|
||||
var instColl []Instances
|
||||
for i := 0; i < len(insts.Instances); i += awsEC2APIChunkSize {
|
||||
end := i + awsEC2APIChunkSize
|
||||
if end > len(insts.Instances) {
|
||||
end = len(insts.Instances)
|
||||
}
|
||||
end := min(i+awsEC2APIChunkSize, len(insts.Instances))
|
||||
inst := EC2Instances{
|
||||
AccountID: insts.AccountID,
|
||||
Region: insts.Region,
|
||||
@@ -428,10 +425,7 @@ func (f *ec2InstanceFetcher) GetInstances(ctx context.Context, rotation bool) ([
|
||||
|
||||
for _, res := range page.Reservations {
|
||||
for i := 0; i < len(res.Instances); i += awsEC2APIChunkSize {
|
||||
end := i + awsEC2APIChunkSize
|
||||
if end > len(res.Instances) {
|
||||
end = len(res.Instances)
|
||||
}
|
||||
end := min(i+awsEC2APIChunkSize, len(res.Instances))
|
||||
ownerID := aws.ToString(res.OwnerId)
|
||||
inst := EC2Instances{
|
||||
AccountID: ownerID,
|
||||
|
||||
@@ -60,7 +60,6 @@ func (gi *GCPInstaller) Run(ctx context.Context, req GCPRunRequest) error {
|
||||
g.SetLimit(10)
|
||||
|
||||
for _, inst := range req.Instances {
|
||||
inst := inst
|
||||
g.Go(func() error {
|
||||
runRequest := gcp.RunCommandRequest{
|
||||
Client: req.Client,
|
||||
|
||||
@@ -236,7 +236,6 @@ func (si *SSMInstaller) Run(ctx context.Context, req SSMRunRequest) error {
|
||||
g, ctx := errgroup.WithContext(ctx)
|
||||
g.SetLimit(10)
|
||||
for instanceID, instanceName := range validInstances {
|
||||
instanceID := instanceID
|
||||
instanceName := instanceName
|
||||
g.Go(func() error {
|
||||
return trace.Wrap(si.checkCommand(ctx, req, output.Command.CommandId, &instanceID, instanceName))
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user