diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index b23dd5b276b6e..a85f6754b3bfe 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -103,45 +103,40 @@ jobs: # Run various golangci-lint checks. # TODO(codingllama): Using go.work could save a bunch of repetition here. - name: golangci-lint (api) - uses: golangci/golangci-lint-action@aaa42aa0628b4ae2578232a66b541047968fac86 # v6.1.0 + uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd # v7.0.0 with: version: ${{ env.GOLANGCI_LINT_VERSION }} working-directory: api - args: --out-format=colored-line-number skip-cache: true - name: golangci-lint (teleport) - uses: golangci/golangci-lint-action@aaa42aa0628b4ae2578232a66b541047968fac86 # v6.1.0 + uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd # v7.0.0 with: version: ${{ env.GOLANGCI_LINT_VERSION }} - args: --out-format=colored-line-number --build-tags libfido2,piv + args: --build-tags libfido2,piv skip-cache: true - name: golangci-lint (assets/backport) - uses: golangci/golangci-lint-action@aaa42aa0628b4ae2578232a66b541047968fac86 # v6.1.0 + uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd # v7.0.0 with: version: ${{ env.GOLANGCI_LINT_VERSION }} working-directory: assets/backport - args: --out-format=colored-line-number skip-cache: true - name: golangci-lint (build.assets/tooling) - uses: golangci/golangci-lint-action@aaa42aa0628b4ae2578232a66b541047968fac86 # v6.1.0 + uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd # v7.0.0 with: version: ${{ env.GOLANGCI_LINT_VERSION }} working-directory: build.assets/tooling - args: --out-format=colored-line-number skip-cache: true - name: golangci-lint (integrations/terraform) - uses: golangci/golangci-lint-action@aaa42aa0628b4ae2578232a66b541047968fac86 # v6.1.0 + uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd # v7.0.0 with: version: ${{ env.GOLANGCI_LINT_VERSION }} working-directory: integrations/terraform - args: --out-format=colored-line-number skip-cache: true - name: golangci-lint (integrations/event-handler) - uses: golangci/golangci-lint-action@aaa42aa0628b4ae2578232a66b541047968fac86 # v6.1.0 + uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd # v7.0.0 with: version: ${{ env.GOLANGCI_LINT_VERSION }} working-directory: integrations/event-handler - args: --out-format=colored-line-number skip-cache: true - name: Run (non-action) linters diff --git a/.golangci.yml b/.golangci.yml index 7fece88fc3d0c..5f6368561aa47 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,93 +1,14 @@ -issues: - exclude-dirs: - - (^|/)node_modules/ - - ^api/gen/ - - ^docs/ - - ^gen/ - - ^rfd/ - - ^web/ - exclude-dirs-use-default: false - exclude-rules: - - linters: - - gosimple - text: "S1002: should omit comparison to bool constant" - - linters: - - revive - text: "exported: exported const" - # TODO(hugoShaka): Remove once https://github.com/dominikh/go-tools/issues/1294 is fixed - - linters: - - unused - path: 'integrations/operator/controllers/resources/(.+)_controller_test\.go' - # TODO(codingllama): Remove once we move to grpc.NewClient. - - linters: [staticcheck] - text: "grpc.Dial is deprecated" - - linters: [staticcheck] - text: "grpc.DialContext is deprecated" - # Deprecated gRPC dial options. Related to grpc.NewClient. - - path: (client/client.go|client/proxy/client_test.go) # api/ - linters: [staticcheck] - # grpc.FailOnNonTempDialError - # grpc.WithReturnConnectionError - text: "this DialOption is not supported by NewClient" - - path: lib/kube/grpc/grpc_test.go - linters: [staticcheck] - text: "grpc.WithBlock is deprecated" - - path: lib/observability/tracing/client.go - linters: [staticcheck] - text: "grpc.WithBlock is deprecated" - - path: integrations/lib/config.go - linters: [staticcheck] - text: "grpc.WithReturnConnectionError is deprecated" - - path: lib/service/service_test.go - linters: [staticcheck] - # grpc.WithReturnConnectionError - # grpc.FailOnNonTempDialError - text: "this DialOption is not supported by NewClient" - - path: integration/client_test.go - linters: [staticcheck] - text: "grpc.WithReturnConnectionError is deprecated" - - path: integration/integration_test.go - linters: [staticcheck] - text: "grpc.WithBlock is deprecated" - - path: lib/multiplexer/multiplexer_test.go - linters: [staticcheck] - text: "grpc.WithBlock is deprecated" - - path: provider/provider.go # integrations/terraform - linters: [staticcheck] - text: "grpc.WithReturnConnectionError is deprecated" - - linters: [govet] - path-except: ^e/ - text: "non-constant format string in call to github.com/gravitational/trace." - # lib/utils/aws/ subpackages are allowed to use AWS SDK constructors. - - path: lib/utils/aws/iamutils/iam.go - linters: [forbidigo] - text: 'iam.NewFromConfig' - - path: lib/utils/aws/iamutils/iam_v1.go - linters: [forbidigo] - text: 'iam.New' - - path: lib/utils/aws/stsutils/sts.go - linters: [forbidigo] - text: 'sts.NewFromConfig' - - path: lib/utils/aws/stsutils/sts_v1.go - linters: [forbidigo] - text: 'sts.New' - - path: lib/utils/aws/stsutils/stscreds_v1.go - linters: [forbidigo] - text: 'stscreds.NewCredentials' - exclude-use-default: true - max-same-issues: 0 - max-issues-per-linter: 0 - uniq-by-line: false - +version: '2' +run: + go: '1.23' + timeout: 15m linters: - disable-all: true + default: none enable: - bodyclose - depguard - errorlint - - gci - - goimports - - gosimple + - forbidigo - govet - ineffassign - misspell @@ -98,211 +19,391 @@ linters: - testifylint - unconvert - unused - - forbidigo - -linters-settings: - depguard: + settings: + depguard: + rules: + cgo: + files: + - '!$test' + - '**/tool/tbot/**' + - '**/lib/client/**' + - '!**/lib/integrations/**' + - '**/integrations/**' + deny: + - pkg: github.com/gravitational/teleport/lib/bpf + desc: '"lib/bpf" requires CGO' + - pkg: github.com/gravitational/teleport/lib/backend/lite + desc: '"lib/backend/lite" requires CGO' + - pkg: github.com/gravitational/teleport/lib/cgroup + desc: '"lib/cgroup" requires CGO' + - pkg: github.com/gravitational/teleport/lib/config + desc: '"lib/config" requires CGO via "lib/pam" and "lib/backend/lite"' + - pkg: github.com/gravitational/teleport/lib/desktop/rdp/rdpclient + desc: '"lib/desktop/rdp/rdpclient" requires CGO' + - pkg: github.com/gravitational/teleport/lib/devicetrust/authn$ + desc: '"lib/devicetrust/authn" requires CGO on darwin' + - pkg: github.com/gravitational/teleport/lib/devicetrust/enroll + desc: '"lib/devicetrust/enroll" requires CGO on darwin' + - pkg: github.com/gravitational/teleport/lib/devicetrust/native + desc: '"lib/devicetrust/native" requires CGO on darwin' + - pkg: github.com/gravitational/teleport/lib/inventory/metadata + desc: '"lib/inventory/metadata" requires CGO' + - pkg: github.com/gravitational/teleport/lib/pam + desc: '"lib/pam" requires CGO' + - pkg: github.com/gravitational/teleport/lib/srv/uacc + desc: '"lib/srv/uacc" requires CGO' + - pkg: github.com/gravitational/teleport/lib/system/signal + desc: '"lib/system/signal" requires CGO' + - pkg: github.com/gravitational/teleport/lib/vnet/daemon + desc: '"vnet/daemon" requires CGO' + client-tools: + list-mode: lax + files: + - '!$test' + - '**/tool/tbot/**' + - '**/lib/tbot/**' + - '**/tool/tctl/**' + - '**/tool/tsh/**' + - '**/lib/client/**' + - '**/lib/services/**' + - '**/lib/service/servicecfg/**' + - '**/lib/reversetunnelclient/**' + - '**/lib/auth/authclient/**' + - '**/lib/cloud/imds/**' + allow: + - github.com/gravitational/teleport/lib/cloud/imds + deny: + - pkg: github.com/gravitational/teleport/lib/auth$ + desc: lib/auth should not be imported to prevent increasing binary size, prefer lib/auth/authclient instead + - pkg: github.com/gravitational/teleport/lib/cloud + desc: lib/cloud should not be imported to prevent increasing binary size + - pkg: github.com/gravitational/teleport/lib/srv$ + desc: lib/srv prevents client tools from build on non-linux platforms + - pkg: github.com/gravitational/teleport/lib/web$ + desc: lib/web should not be imported to prevent increasing binary size + go-cmp: + files: + - '!$test' + - '!**/integration/helpers/**' + - '!**/integrations/operator/controllers/resources/testlib/**' + - '!**/lib/auth/test/**' + - '!**/lib/services/suite/**' + - '!**/e/lib/accesslist/equal.go' + - '!**/e/lib/auth/saml.go' + - '!**lib/services/authority.go' + - '!**lib/services/compare.go' + - '!**/lib/services/local/access_list.go' + - '!**/lib/services/local/users.go' + - '!**/lib/services/server.go' + - '!**/lib/services/user.go' + deny: + - pkg: github.com/google/go-cmp/cmp + desc: '"github.com/google/go-cmp/cmp" should only be used in tests' + - pkg: github.com/google/go-cmp/cmp/cmpopts + desc: '"github.com/google/go-cmp/cmp/cmpopts" should only be used in tests' + integration: + list-mode: lax + files: + - '!$test' + - '!**/integration/**' + - '!**/e/tests/**' + - '!**/integrations/operator/controllers/resources/testlib/**' + allow: + - github.com/gravitational/teleport/integrations + deny: + - pkg: github.com/gravitational/teleport/integration + desc: integration test should not be imported outside of integration tests + main: + deny: + - pkg: io/ioutil + desc: use "io" or "os" packages instead + - pkg: math/rand$ + desc: use "math/rand/v2" or "crypto/rand" instead + - pkg: github.com/golang/protobuf + desc: use "google.golang.org/protobuf" + - pkg: github.com/hashicorp/go-uuid + desc: use "github.com/google/uuid" instead + - pkg: github.com/pborman/uuid + desc: use "github.com/google/uuid" instead + - pkg: github.com/siddontang/go-log/log + desc: use "github.com/sirupsen/logrus" instead + - pkg: github.com/siddontang/go/log + desc: use "github.com/sirupsen/logrus" instead + - pkg: github.com/tj/assert + desc: use "github.com/stretchr/testify/assert" instead + - pkg: go.uber.org/atomic + desc: use "sync/atomic" instead + - pkg: golang.design + desc: experimental project, not to be confused with official Go packages + - pkg: golang.org/x/exp/slices + desc: use "slices" instead + - pkg: github.com/hashicorp/go-version + desc: use golang.org/x/mod/semver or coreos/go-semver/semver instead + - pkg: github.com/microsoftgraph/msgraph-sdk-go + desc: use "github.com/gravitational/teleport/lib/msgraph" instead + - pkg: github.com/cloudflare/cfssl + desc: use "crypto" or "x/crypto" instead + testify: + files: + - '!$test' + - '!**/api/testhelpers/**' + - '!**/e/lib/auth/ssotestlib.go' + - '!**/e/lib/aws/identitycenter/test/**' + - '!**/e/lib/idp/saml/testenv/**' + - '!**/e/lib/operatortest/**' + - '!**/e/tests/**' + - '!**/lib/automaticupgrades/basichttp/servermock.go' + - '!**/lib/auth/helpers.go' + - '!**/lib/auth/keystore/testhelpers.go' + - '!**/lib/auth/test/**' + - '!**/lib/backend/test/**' + - '!**/lib/events/athena/test.go' + - '!**/lib/events/test/**' + - '!**/lib/kube/proxy/utils_testing.go' + - '!**/lib/services/suite/**' + - '!**/lib/srv/mock.go' + - '!**/lib/srv/db/redis/test.go' + - '!**/lib/tbot/workloadidentity/workloadattest/podman/test_server.go' + - '!**/lib/tbot/workloadidentity/workloadattest/sigstore/sigstoretest/sigstoretest.go' + - '!**/lib/teleterm/gatewaytest/**' + - '!**/lib/utils/testhelpers.go' + - '!**/lib/utils/testutils/**' + - '!**/integration/appaccess/fixtures.go' + - '!**/integration/appaccess/jwt.go' + - '!**/integration/appaccess/pack.go' + - '!**/integration/db/fixture.go' + - '!**/integration/hsm/helpers.go' + - '!**/integration/helpers/**' + - '!**/integration/proxy/proxy_helpers.go' + - '!**/integrations/access/email/testlib/**' + - '!**/integrations/access/datadog/testlib/**' + - '!**/integrations/access/discord/testlib/**' + - '!**/integrations/access/jira/testlib/**' + - '!**/integrations/access/mattermost/testlib/**' + - '!**/integrations/access/msteams/testlib/**' + - '!**/integrations/access/opsgenie/testlib/**' + - '!**/integrations/access/pagerduty/testlib/**' + - '!**/integrations/access/servicenow/testlib/**' + - '!**/integrations/access/slack/testlib/**' + - '!**/integrations/lib/testing/integration/accessrequestsuite.go' + - '!**/integrations/lib/testing/integration/app.go' + - '!**/integrations/lib/testing/integration/authhelper.go' + - '!**/integrations/lib/testing/integration/suite.go' + - '!**/integrations/operator/controllers/resources/testlib/**' + - '!**/tool/teleport/testenv/**' + deny: + - pkg: github.com/stretchr/testify + desc: testify should not be imported outside of test code + testing: + files: + - '!$test' + - '!**/api/testhelpers/**' + - '!**/e/lib/auth/ssotestlib.go' + - '!**/e/lib/aws/identitycenter/test/**' + - '!**/e/lib/devicetrust/testenv/**' + - '!**/e/lib/devicetrust/storage/storage.go' + - '!**/e/lib/idp/saml/testenv/**' + - '!**/e/lib/jamf/testenv/**' + - '!**/e/lib/okta/api/oktaapitest/**' + - '!**/e/lib/operatortest/**' + - '!**/e/tests/**' + - '!**/integration/**' + - '!**/integrations/access/email/testlib/**' + - '!**/integrations/access/msteams/testlib/**' + - '!**/integrations/access/slack/testlib/**' + - '!**/integrations/operator/controllers/resources/testlib/**' + - '!**/lib/auth/helpers.go' + - '!**/lib/auth/keystore/testhelpers.go' + - '!**/lib/auth/test/**' + - '!**/lib/automaticupgrades/basichttp/servermock.go' + - '!**/lib/backend/test/**' + - '!**/lib/cryptosuites/precompute.go' + - '!**/lib/cryptosuites/internal/rsa/rsa.go' + - '!**/lib/events/test/**' + - '!**/lib/events/athena/test.go' + - '!**/lib/fixtures/**' + - '!**/lib/kube/proxy/utils_testing.go' + - '!**/lib/modules/test.go' + - '!**/lib/service/service.go' + - '!**/lib/services/local/users.go' + - '!**/lib/services/suite/**' + - '!**/lib/srv/mock.go' + - '!**/lib/srv/db/redis/test.go' + - '!**/lib/tbot/workloadidentity/workloadattest/podman/test_server.go' + - '!**/lib/tbot/workloadidentity/workloadattest/sigstore/sigstoretest/sigstoretest.go' + - '!**/lib/teleterm/gatewaytest/**' + - '!**/lib/utils/cli.go' + - '!**/lib/utils/testhelpers.go' + - '!**/lib/utils/testutils/**' + - '!**/tool/teleport/testenv/**' + deny: + - pkg: testing + desc: testing should not be imported outside of tests + errorlint: + errorf: true + asserts: true + comparison: true + forbidigo: + forbid: + - pattern: ^rsa\.GenerateKey$ + msg: generating RSA keys is slow, use lib/cryptosuites to generate an appropriate key type + - pattern: ^iam\.NewFromConfig$ + msg: Use iamutils.NewFromConfig + - pattern: ^sts\.NewFromConfig$ + msg: Use stsutils.NewFromConfig + - pattern: ^sts\.New$ + msg: Use stsutils.NewV1 + - pattern: ^stscreds\.NewCredentials$ + msg: Use stsutils.NewCredentials + - pattern: ^protojson\.Unmarshal$ + msg: use protojson.UnmarshalOptions and consider enabling DiscardUnknown + - pattern: ^jsonpb\.(?:Unmarshal|UnmarshalString|UnmarshalNext)$ + msg: use jsonpb.Unmarshaler and consider enabling AllowUnknownFields + misspell: + locale: US + nolintlint: + require-explanation: true + require-specific: true + allow-unused: true + revive: + rules: + - name: unused-parameter + disabled: true + sloglint: + context: all + static-msg: true + key-naming-case: snake + forbidden-keys: + - level + - msg + - source + - time + testifylint: + disable-all: true + enable: + - bool-compare + - compares + - empty + - error-is-as + - error-nil + - expected-actual + - float-compare + - len + - suite-extra-assert-call + - suite-thelper + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling rules: - main: - deny: - - pkg: io/ioutil - desc: 'use "io" or "os" packages instead' - - pkg: math/rand$ - desc: 'use "math/rand/v2" or "crypto/rand" instead' - - pkg: github.com/golang/protobuf - desc: 'use "google.golang.org/protobuf"' - - pkg: github.com/hashicorp/go-uuid - desc: 'use "github.com/google/uuid" instead' - - pkg: github.com/pborman/uuid - desc: 'use "github.com/google/uuid" instead' - - pkg: github.com/siddontang/go-log/log - desc: 'use "github.com/sirupsen/logrus" instead' - - pkg: github.com/siddontang/go/log - desc: 'use "github.com/sirupsen/logrus" instead' - - pkg: github.com/tj/assert - desc: 'use "github.com/stretchr/testify/assert" instead' - - pkg: go.uber.org/atomic - desc: 'use "sync/atomic" instead' - - pkg: golang.design - desc: 'experimental project, not to be confused with official Go packages' - - pkg: golang.org/x/exp/slices - desc: 'use "slices" instead' - - pkg: github.com/hashicorp/go-version - desc: 'use "golang.org/x/mod/semver" or "coreos/go-semver/semver" instead' - - pkg: github.com/microsoftgraph/msgraph-sdk-go - desc: 'use "github.com/gravitational/teleport/lib/msgraph" instead' - - pkg: github.com/cloudflare/cfssl - desc: 'use "crypto" or "x/crypto" instead' - # Prevent logrus from being imported by api and e. Once everything in teleport has been converted - # to use log/slog this should be moved into the main block above. - logrus: - files: - - '**/api/**' - - '**/e/**' - deny: - - pkg: github.com/sirupsen/logrus - desc: 'use "log/slog" instead' - # Prevent importing internal packages in client tools or packages containing - # common interfaces consumed by them that are known to bloat binaries or break builds - # because they only support a single platform. - client-tools: - files: - # Tests can do anything - - "!$test" - - '**/tool/tbot/**' - - '**/lib/tbot/**' - - '**/tool/tctl/**' - - '**/tool/tsh/**' - - '**/lib/client/**' - - '**/lib/services/**' - - '**/lib/service/servicecfg/**' - - '**/lib/reversetunnelclient/**' - - '**/lib/auth/authclient/**' - - '**/lib/cloud/imds/**' - allow: - - github.com/gravitational/teleport/lib/cloud/imds - deny: - - pkg: github.com/gravitational/teleport/lib/auth$ - desc: 'lib/auth should not be imported to prevent increasing binary size, prefer lib/auth/authclient instead' - - pkg: github.com/gravitational/teleport/lib/cloud - desc: 'lib/cloud should not be imported to prevent increasing binary size' - - pkg: github.com/gravitational/teleport/lib/srv$ - desc: 'lib/srv prevents client tools from build on non-linux platforms' - - pkg: github.com/gravitational/teleport/lib/web$ - desc: 'lib/web should not be imported to prevent increasing binary size' - list-mode: lax - # Prevent importing dependencies that require CGO into tools that are - # meant to be built with CGO_ENABLED=0 - cgo: - files: - # Tests can do anything - - "!$test" - - '**/tool/tbot/**' - - '**/lib/client/**' - - '!**/lib/integrations/**' - - '**/integrations/**' - deny: - - pkg: github.com/gravitational/teleport/lib/bpf - desc: '"lib/bpf" requires CGO' - - pkg: github.com/gravitational/teleport/lib/backend/lite - desc: '"lib/backend/lite" requires CGO' - - pkg: github.com/gravitational/teleport/lib/cgroup - desc: '"lib/cgroup" requires CGO' - - pkg: github.com/gravitational/teleport/lib/config - desc: '"lib/config" requires CGO via "lib/pam" and "lib/backend/lite"' - - pkg: github.com/gravitational/teleport/lib/desktop/rdp/rdpclient - desc: '"lib/desktop/rdp/rdpclient" requires CGO' - - pkg: github.com/gravitational/teleport/lib/devicetrust/authn$ - desc: '"lib/devicetrust/authn" requires CGO on darwin' - - pkg: github.com/gravitational/teleport/lib/devicetrust/enroll - desc: '"lib/devicetrust/enroll" requires CGO on darwin' - - pkg: github.com/gravitational/teleport/lib/devicetrust/native - desc: '"lib/devicetrust/native" requires CGO on darwin' - - pkg: github.com/gravitational/teleport/lib/inventory/metadata - desc: '"lib/inventory/metadata" requires CGO' - - pkg: github.com/gravitational/teleport/lib/pam - desc: '"lib/pam" requires CGO' - - pkg: github.com/gravitational/teleport/lib/srv/uacc - desc: '"lib/srv/uacc" requires CGO' - - pkg: github.com/gravitational/teleport/lib/system/signal - desc: '"lib/system/signal" requires CGO' - - pkg: github.com/gravitational/teleport/lib/vnet/daemon - desc: '"vnet/daemon" requires CGO' - # Prevent importing go-cmp into production code. From the go-cmp docs: - # > It is intended to only be used in tests, as performance is not a goal - # > and it may panic if it cannot compare the values. Its propensity towards - # > panicking means that its unsuitable for production environments where a - # > spurious panic may be fatal. - go-cmp: - files: - # Tests can do anything - - '!$test' - # Various test helpers defined outside _test.go files are allowed - - '!**/integration/helpers/**' - - '!**/integrations/operator/controllers/resources/testlib/**' - - '!**/lib/auth/test/**' - - '!**/lib/services/suite/**' - # Non-compliant legacy code. These should be converted to compare by another mechanism - # and be removed from this list in the future. Use caution before adding any additional - # exclusions to this list. - - '!**/e/lib/accesslist/equal.go' - - '!**/e/lib/auth/saml.go' - - '!**lib/services/authority.go' - - '!**lib/services/compare.go' - - '!**/lib/services/local/access_list.go' - - '!**/lib/services/local/users.go' - - '!**/lib/services/server.go' - - '!**/lib/services/user.go' - deny: - - pkg: github.com/google/go-cmp/cmp - desc: '"github.com/google/go-cmp/cmp" should only be used in tests' - - pkg: github.com/google/go-cmp/cmp/cmpopts - desc: '"github.com/google/go-cmp/cmp/cmpopts" should only be used in tests' - errorlint: - comparison: true - asserts: true - errorf: true - gci: - sections: - - standard # Standard section: captures all standard packages. - - default # Default section: contains all imports that could not be matched to another section type. - - prefix(github.com/gravitational/teleport) # Custom section: groups all imports with the specified Prefix. - - prefix(github.com/gravitational/teleport/integrations/terraform,github.com/gravitational/teleport/integrations/event-handler) - skip-generated: true # Skip generated files. - custom-order: true # Required for "sections" to take effect. - misspell: - locale: US - nolintlint: - allow-unused: true # Enabled because of conditional builds / build tags. - require-explanation: true - require-specific: true - revive: - rules: - - name: unused-parameter - disabled: true - sloglint: - context: all - key-naming-case: snake - static-msg: true - forbidden-keys: - - level - - msg - - source - - time - testifylint: - disable-all: true - enable: - - bool-compare - - compares - - empty - - error-is-as - - error-nil - - expected-actual - - float-compare - - len - - suite-extra-assert-call - - suite-thelper - forbidigo: - forbid: - - p: '^rsa\.GenerateKey$' - msg: 'generating RSA keys is slow, use lib/cryptosuites to generate an appropriate key type' - # AWS SDK wrapped constructors. - - p: '^iam\.NewFromConfig$' - msg: 'Use iamutils.NewFromConfig' - - p: '^iam\.New$' - msg: 'Use iamutils.NewV1' - - p: '^sts\.NewFromConfig$' - msg: 'Use stsutils.NewFromConfig' - - p: '^sts\.New$' - msg: 'Use stsutils.NewV1' - - p: '^stscreds\.NewCredentials$' - msg: 'Use stsutils.NewCredentials' - - p: '^protojson\.Unmarshal$' - msg: "use protojson.UnmarshalOptions and consider enabling DiscardUnknown" - - p: '^jsonpb\.(?:Unmarshal|UnmarshalString|UnmarshalNext)$' - msg: "use jsonpb.Unmarshaler and consider enabling AllowUnknownFields" - -run: - go: '1.23' - build-tags: [] - timeout: 15m + - linters: + - staticcheck + text: 'QF1008: could remove embedded field' + - linters: + - staticcheck + text: 'QF1008: could simplify selectors' + - linters: + - staticcheck + text: 'S1002: should omit comparison to bool constant' + - linters: + - revive + text: 'exported: exported const' + - linters: + - unused + path: integrations/operator/controllers/resources/(.+)_controller_test\.go + - linters: + - staticcheck + text: grpc.Dial is deprecated + - linters: + - staticcheck + text: grpc.DialContext is deprecated + - linters: + - staticcheck + path: (client/client.go|client/proxy/client_test.go) + text: this DialOption is not supported by NewClient + - linters: + - staticcheck + path: lib/kube/grpc/grpc_test.go + text: grpc.WithBlock is deprecated + - linters: + - staticcheck + path: lib/observability/tracing/client.go + text: grpc.WithBlock is deprecated + - linters: + - staticcheck + path: integrations/lib/config.go + text: grpc.WithReturnConnectionError is deprecated + - linters: + - staticcheck + path: lib/service/service_test.go + text: this DialOption is not supported by NewClient + - linters: + - staticcheck + path: integration/client_test.go + text: grpc.WithReturnConnectionError is deprecated + - linters: + - staticcheck + path: integration/integration_test.go + text: grpc.WithBlock is deprecated + - linters: + - staticcheck + path: lib/multiplexer/multiplexer_test.go + text: grpc.WithBlock is deprecated + - linters: + - staticcheck + path: provider/provider.go + text: grpc.WithReturnConnectionError is deprecated + - linters: + - staticcheck + text: 'BlockUntil is deprecated: New code should prefer BlockUntilContext' + - linters: + - forbidigo + path: lib/utils/aws/iamutils/iam.go + text: iam.NewFromConfig + - linters: + - forbidigo + path: lib/utils/aws/stsutils/sts.go + text: sts.NewFromConfig + - linters: + - forbidigo + path: lib/utils/aws/stsutils/sts_v1.go + text: sts.New + - linters: + - forbidigo + path: lib/utils/aws/stsutils/stscreds_v1.go + text: stscreds.NewCredentials + paths: + - (^|/)node_modules/ + - ^api/gen/ + - ^docs/ + - ^gen/ + - ^rfd/ + - ^web/ +issues: + max-issues-per-linter: 0 + max-same-issues: 0 + uniq-by-line: false +formatters: + enable: + - gci + - goimports + settings: + gci: + sections: + - standard + - default + - prefix(github.com/gravitational/teleport) + - prefix(github.com/gravitational/teleport/integrations/terraform,github.com/gravitational/teleport/integrations/event-handler) + custom-order: true + exclusions: + generated: lax + paths: + - (^|/)node_modules/ + - ^api/gen/ + - ^docs/ + - ^gen/ + - ^rfd/ + - ^web/ diff --git a/api/client/contextdialer.go b/api/client/contextdialer.go index f6f69625189b5..90f27468764c8 100644 --- a/api/client/contextdialer.go +++ b/api/client/contextdialer.go @@ -196,7 +196,7 @@ func NewDialer(ctx context.Context, keepAlivePeriod, dialTimeout time.Duration, return tracedDialer(ctx, func(ctx context.Context, network, addr string) (net.Conn, error) { // Base direct dialer. - var dialer ContextDialer = cfg.baseDialer + dialer := cfg.baseDialer if dialer == nil { dialer = newDirectDialer(keepAlivePeriod, dialTimeout) } diff --git a/api/client/webclient/webclient.go b/api/client/webclient/webclient.go index e2c77534b25f6..624936124bd88 100644 --- a/api/client/webclient/webclient.go +++ b/api/client/webclient/webclient.go @@ -163,7 +163,7 @@ func doWithFallback(clt *http.Client, allowPlainHTTP bool, extraHeaders map[stri // If we're not allowed to try plain HTTP, bail out with whatever error we have. // Note that we're only allowed to try plain HTTP on the loopback address, even // if the caller says its OK - if !(allowPlainHTTP && utils.IsLoopback(req.URL.Host)) { + if !allowPlainHTTP || !utils.IsLoopback(req.URL.Host) { return nil, trace.Wrap(err) } diff --git a/api/observability/tracing/ssh/ssh_test.go b/api/observability/tracing/ssh/ssh_test.go index 441073d61b5f9..e7618a3be15e3 100644 --- a/api/observability/tracing/ssh/ssh_test.go +++ b/api/observability/tracing/ssh/ssh_test.go @@ -151,8 +151,8 @@ func (h handler) handle(sconn *ssh.ServerConn, chans <-chan ssh.NewChannel, reqs } func (h handler) requestHandler(req *ssh.Request) { - switch { - case req.Type == "test": + switch req.Type { + case "test": defer func() { if req.WantReply { if err := req.Reply(true, nil); err != nil { diff --git a/api/types/database_permissions.go b/api/types/database_permissions.go index 5f1713e7fcc4b..12c20658bf925 100644 --- a/api/types/database_permissions.go +++ b/api/types/database_permissions.go @@ -29,7 +29,7 @@ func (m *DatabasePermission) CheckAndSetDefaults() error { } } for key, val := range m.Match { - if key == Wildcard && !(len(val) == 1 && val[0] == Wildcard) { + if key == Wildcard && (len(val) != 1 || val[0] != Wildcard) { return trace.BadParameter("database permission: selector *: is not supported") } } diff --git a/api/types/database_test.go b/api/types/database_test.go index 0d954c51dc5d8..29437b970722a 100644 --- a/api/types/database_test.go +++ b/api/types/database_test.go @@ -441,7 +441,7 @@ func TestMySQLServerVersion(t *testing.T) { }) require.NoError(t, err) - require.Equal(t, "", database.GetMySQLServerVersion()) + require.Empty(t, database.GetMySQLServerVersion()) database.SetMySQLServerVersion("8.0.1") require.Equal(t, "8.0.1", database.GetMySQLServerVersion()) diff --git a/api/types/duration.go b/api/types/duration.go index c07476b9f6a59..fc5bb6112149a 100644 --- a/api/types/duration.go +++ b/api/types/duration.go @@ -200,8 +200,8 @@ func parseDuration(s string) (Duration, error) { var err error // The next character must be [0-9.] - if !(s[0] == '.' || '0' <= s[0] && s[0] <= '9') { - return 0, trace.BadParameter("time: invalid duration " + orig) + if s[0] != '.' && (s[0] < '0' || s[0] > '9') { + return 0, trace.BadParameter("time: invalid duration %q", orig) } // Consume [0-9]* pl := len(s) diff --git a/api/types/okta_test.go b/api/types/okta_test.go index ce2c203f0a0d6..ad187358e5a46 100644 --- a/api/types/okta_test.go +++ b/api/types/okta_test.go @@ -289,12 +289,12 @@ func Test_PluginOktaSyncSettings_SetUserSyncSource(t *testing.T) { syncSettings := &PluginOktaSyncSettings{} // OktaUserSyncSourceUnknown is returned for empty value - require.Equal(t, "", syncSettings.UserSyncSource) + require.Empty(t, syncSettings.UserSyncSource) require.Equal(t, OktaUserSyncSourceUnknown, syncSettings.GetUserSyncSource()) // When "asdf" is set, it doesn't change empty value syncSettings.SetUserSyncSource("asdf") - require.Equal(t, "", syncSettings.UserSyncSource) + require.Empty(t, syncSettings.UserSyncSource) require.Equal(t, OktaUserSyncSourceUnknown, syncSettings.GetUserSyncSource()) // When "asdf" is set, it doesn't change set value diff --git a/api/types/provisioning.go b/api/types/provisioning.go index 32589bc591b07..26e5b75e83781 100644 --- a/api/types/provisioning.go +++ b/api/types/provisioning.go @@ -27,7 +27,7 @@ import ( "github.com/gravitational/trace" "github.com/gravitational/teleport/api/defaults" - apiutils "github.com/gravitational/teleport/api/utils" + "github.com/gravitational/teleport/api/utils" ) // JoinMethod is the method used for new nodes to join the cluster. @@ -102,7 +102,7 @@ var JoinMethods = []JoinMethod{ func ValidateJoinMethod(method JoinMethod) error { hasJoinMethod := slices.Contains(JoinMethods, method) if !hasJoinMethod { - return trace.BadParameter("join method must be one of %s", apiutils.JoinStrings(JoinMethods, ", ")) + return trace.BadParameter("join method must be one of %s", utils.JoinStrings(JoinMethods, ", ")) } return nil @@ -657,7 +657,7 @@ func (a *ProvisionTokenSpecV2GitHub) checkAndSetDefaults() error { repoSet := rule.Repository != "" ownerSet := rule.RepositoryOwner != "" subSet := rule.Sub != "" - if !(subSet || ownerSet || repoSet) { + if !subSet && !ownerSet && !repoSet { return trace.BadParameter( `allow rule for %q must include at least one of "repository", "repository_owner" or "sub"`, JoinMethodGitHub, @@ -733,7 +733,7 @@ func (a *ProvisionTokenSpecV2Kubernetes) checkAndSetDefaults() error { default: return trace.BadParameter( "type: must be one of (%s), got %q", - apiutils.JoinStrings(JoinMethods, ", "), + utils.JoinStrings(JoinMethods, ", "), a.Type, ) } diff --git a/api/types/role.go b/api/types/role.go index 6eb242643e47f..aeb96ceca8f0f 100644 --- a/api/types/role.go +++ b/api/types/role.go @@ -1063,7 +1063,7 @@ func (c *SPIFFERoleCondition) CheckAndSetDefaults() error { return trace.BadParameter("path: should be non-empty") } isRegex := strings.HasPrefix(c.Path, "^") && strings.HasSuffix(c.Path, "$") - if !(strings.HasPrefix(c.Path, "/") || isRegex) { + if !strings.HasPrefix(c.Path, "/") && !isRegex { return trace.BadParameter( "path: should start with / or be a regex expression starting with ^ and ending with $", ) @@ -1269,7 +1269,7 @@ func (r *RoleV6) CheckAndSetDefaults() error { } checkWildcardSelector := func(labels Labels) error { for key, val := range labels { - if key == Wildcard && !(len(val) == 1 && val[0] == Wildcard) { + if key == Wildcard && (len(val) != 1 || val[0] != Wildcard) { return trace.BadParameter("selector *: is not supported") } } diff --git a/api/utils/grpc/interceptors/errors_test.go b/api/utils/grpc/interceptors/errors_test.go index ad50434ac9af7..c177ca1d1584a 100644 --- a/api/utils/grpc/interceptors/errors_test.go +++ b/api/utils/grpc/interceptors/errors_test.go @@ -80,6 +80,7 @@ func TestGRPCErrorWrapping(t *testing.T) { assert.Equal(t, "not found", err.Error()) var traceErr *trace.TraceErr + //nolint:testifylint //assert.NotErrorsAs does not exist until later versions of testify assert.False(t, errors.As(err, &traceErr), "client error should not include traces originating in the middleware") var remoteErr *interceptors.RemoteError assert.ErrorAs(t, err, &remoteErr, "Remote error is not marked as an interceptors.RemoteError") @@ -110,6 +111,8 @@ func TestGRPCErrorWrapping(t *testing.T) { assert.True(t, trace.IsAlreadyExists(err), "trace.IsAlreadyExists failed: err=%v (%T)", err, trace.Unwrap(err)) assert.Equal(t, "already exists", err.Error()) var traceErr *trace.TraceErr + + //nolint:testifylint //assert.NotErrorsAs does not exist until later versions of testify assert.False(t, errors.As(err, &traceErr), "client error should not include traces originating in the middleware") assert.True(t, trace.IsAlreadyExists(err), "trace.IsAlreadyExists failed: err=%v (%T)", err, trace.Unwrap(err)) var remoteErr *interceptors.RemoteError diff --git a/api/utils/keys/piv/pincache_test.go b/api/utils/keys/piv/pincache_test.go index fadfc3ad6a5f9..81b2d61531bb3 100644 --- a/api/utils/keys/piv/pincache_test.go +++ b/api/utils/keys/piv/pincache_test.go @@ -40,7 +40,7 @@ func TestPINCache(t *testing.T) { // Advancing by the small TTL should only expire the pin for the small TTL. clock.Advance(smallTTL) - require.Zero(t, pinCache.getPIN(smallTTL)) + require.Empty(t, pinCache.getPIN(smallTTL)) require.Equal(t, testPIN, pinCache.getPIN(mediumTTL)) require.Equal(t, testPIN, pinCache.getPIN(largeTTL)) @@ -52,7 +52,7 @@ func TestPINCache(t *testing.T) { // Advancing by the medium TTL, used to set the initial cache, should expire the PIN cache. clock.Advance(mediumTTL) - require.Zero(t, pinCache.getPIN(smallTTL)) - require.Zero(t, pinCache.getPIN(mediumTTL)) - require.Zero(t, pinCache.getPIN(largeTTL)) + require.Empty(t, pinCache.getPIN(smallTTL)) + require.Empty(t, pinCache.getPIN(mediumTTL)) + require.Empty(t, pinCache.getPIN(largeTTL)) } diff --git a/api/utils/route.go b/api/utils/route.go index af9311758e1ea..ebf9a0721ada5 100644 --- a/api/utils/route.go +++ b/api/utils/route.go @@ -92,7 +92,7 @@ func newSSHRouteMatcher(cfg SSHRouteMatcherConfig) SSHRouteMatcher { dialByID := err == nil || aws.IsEC2NodeID(cfg.Host) var ips []string - if !(cfg.DisableUnqualifiedLookups && !strings.Contains(cfg.Host, ".")) { + if !cfg.DisableUnqualifiedLookups || strings.Contains(cfg.Host, ".") { // unqualified lookups are still on by default, but future versions of teleport may disable them as they tend // to be responsible for the majority of all lookups generated by a teleport cluster and are of questionable utility. ips, _ = cfg.Resolver.LookupHost(context.Background(), cfg.Host) diff --git a/build.assets/versions.mk b/build.assets/versions.mk index 31431681ca410..55f3e5a887812 100644 --- a/build.assets/versions.mk +++ b/build.assets/versions.mk @@ -4,7 +4,7 @@ # Sync with devbox.json. GOLANG_VERSION ?= go1.23.8 -GOLANGCI_LINT_VERSION ?= v1.64.7 +GOLANGCI_LINT_VERSION ?= v2.1.5 # NOTE: Remember to update engines.node in package.json to match the major version. NODE_VERSION ?= 22.14.0 diff --git a/integration/appaccess/pack.go b/integration/appaccess/pack.go index a3e19634c79e0..7b84727a84d71 100644 --- a/integration/appaccess/pack.go +++ b/integration/appaccess/pack.go @@ -913,7 +913,7 @@ func (p *Pack) startRootAppServers(t *testing.T, count int, opts AppTestOptions) servers, err := p.rootCluster.StartApps(configs) require.NoError(t, err) - require.Equal(t, len(configs), len(servers)) + require.Len(t, configs, len(servers)) for i, appServer := range servers { srv := appServer @@ -1060,7 +1060,7 @@ func (p *Pack) startLeafAppServers(t *testing.T, count int, opts AppTestOptions) servers, err := p.leafCluster.StartApps(configs) require.NoError(t, err) - require.Equal(t, len(configs), len(servers)) + require.Len(t, configs, len(servers)) for i, appServer := range servers { srv := appServer diff --git a/integration/integration_test.go b/integration/integration_test.go index a9af4ff5e6111..c2d29bfe5f6fd 100644 --- a/integration/integration_test.go +++ b/integration/integration_test.go @@ -4822,7 +4822,7 @@ func testX11Forwarding(t *testing.T, suite *integrationTestSuite) { display := make(chan string, 1) require.EventuallyWithT(t, func(t *assert.CollectT) { // enter 'printenv DISPLAY > /path/to/tmp/file' into the session (dumping the value of DISPLAY into the temp file) - _, err = keyboard.Write([]byte(fmt.Sprintf("printenv %v > %s\n\r", x11.DisplayEnv, tmpFile.Name()))) + _, err = fmt.Fprintf(keyboard, "printenv %v > %s\n\r", x11.DisplayEnv, tmpFile.Name()) assert.NoError(t, err) assert.Eventually(t, func() bool { diff --git a/integrations/access/mattermost/testlib/suite.go b/integrations/access/mattermost/testlib/suite.go index 5f05023b8f5dd..97dd25133c758 100644 --- a/integrations/access/mattermost/testlib/suite.go +++ b/integrations/access/mattermost/testlib/suite.go @@ -233,7 +233,7 @@ func (s *MattermostSuiteOSS) TestApproval() { require.Len(t, matches, 1) require.Len(t, matches[0], 3) assert.Equal(t, "okay", matches[0][1]) - assert.Equal(t, "", matches[0][2]) + assert.Empty(t, matches[0][2]) } // TestDenial tests that when a request is denied, its corresponding message @@ -398,7 +398,7 @@ func (s *MattermostSuiteEnterprise) TestApprovalByReview() { require.Len(t, matches, 1) require.Len(t, matches[0], 3) assert.Equal(t, "finally okay", matches[0][1]) - assert.Equal(t, "", matches[0][2]) + assert.Empty(t, matches[0][2]) } // TestDenialByReview tests that the message is updated after the access request @@ -466,7 +466,7 @@ func (s *MattermostSuiteEnterprise) TestDenialByReview() { require.Len(t, matches, 1) require.Len(t, matches[0], 3) assert.Equal(t, "finally not okay", matches[0][1]) - assert.Equal(t, "", matches[0][2]) + assert.Empty(t, matches[0][2]) } // TestExpiration tests that when a request expires, its corresponding message diff --git a/integrations/access/msteams/plugindata_test.go b/integrations/access/msteams/plugindata_test.go index 67b105ba5625e..0ca27b812183c 100644 --- a/integrations/access/msteams/plugindata_test.go +++ b/integrations/access/msteams/plugindata_test.go @@ -50,7 +50,7 @@ func TestEncodePluginData(t *testing.T) { assert.Equal(t, "3", dataMap["reviews_count"]) assert.Equal(t, "APPROVED", dataMap["resolution"]) assert.Equal(t, "foo ok", dataMap["resolve_reason"]) - assert.Equal(t, "", dataMap["resources"]) + assert.Empty(t, dataMap["resources"]) assert.Equal( t, messageData, diff --git a/integrations/access/pagerduty/client.go b/integrations/access/pagerduty/client.go index 51adfb38f5aed..1f5edb654f4eb 100644 --- a/integrations/access/pagerduty/client.go +++ b/integrations/access/pagerduty/client.go @@ -370,7 +370,7 @@ func (p *Pagerduty) FilterOnCallPolicies(ctx context.Context, userID string, esc anyData = anyData || len(result.OnCalls) > 0 for _, onCall := range result.OnCalls { - if !(onCall.User.Type == "user_reference" && onCall.User.ID == userID) { + if onCall.User.Type != "user_reference" || onCall.User.ID != userID { continue } diff --git a/integrations/access/pagerduty/testlib/fake_pagerduty.go b/integrations/access/pagerduty/testlib/fake_pagerduty.go index 18a2a6ae24361..e72bcde98e896 100644 --- a/integrations/access/pagerduty/testlib/fake_pagerduty.go +++ b/integrations/access/pagerduty/testlib/fake_pagerduty.go @@ -260,7 +260,7 @@ func NewFakePagerduty(concurrency int) *FakePagerduty { } // Filter by service_ids - if serviceIDSet.Len() > 0 && !(incident.Service.Type == "service_reference" && serviceIDSet.Contains(incident.Service.ID)) { + if serviceIDSet.Len() > 0 && (incident.Service.Type != "service_reference" || !serviceIDSet.Contains(incident.Service.ID)) { return true } @@ -377,12 +377,12 @@ func NewFakePagerduty(concurrency int) *FakePagerduty { return true } // Filter by user_ids - if userIDSet.Len() > 0 && !(onCall.User.Type == "user_reference" && userIDSet.Contains(onCall.User.ID)) { + if userIDSet.Len() > 0 && (onCall.User.Type != "user_reference" || !userIDSet.Contains(onCall.User.ID)) { return true } // Filter by escalation_policy_ids - if policyIDSet.Len() > 0 && !(onCall.EscalationPolicy.Type == "escalation_policy_reference" && policyIDSet.Contains(onCall.EscalationPolicy.ID)) { + if policyIDSet.Len() > 0 && (onCall.EscalationPolicy.Type != "escalation_policy_reference" || !policyIDSet.Contains(onCall.EscalationPolicy.ID)) { return true } diff --git a/integrations/event-handler/state_test.go b/integrations/event-handler/state_test.go index ae1965f9a10cc..8a5a66ba3cc8e 100644 --- a/integrations/event-handler/state_test.go +++ b/integrations/event-handler/state_test.go @@ -65,8 +65,8 @@ func TestStatePersist(t *testing.T) { require.NoError(t, erri) assert.Nil(t, startTime) - assert.Equal(t, "", cursor) - assert.Equal(t, "", id) + assert.Empty(t, cursor) + assert.Empty(t, id) errc = state.SetCursor("testCursor") erri = state.SetID("testId") diff --git a/integrations/operator/controllers/reconcilers/generic.go b/integrations/operator/controllers/reconcilers/generic.go index f0a1d88682c2e..635431748b2c2 100644 --- a/integrations/operator/controllers/reconcilers/generic.go +++ b/integrations/operator/controllers/reconcilers/generic.go @@ -25,7 +25,6 @@ import ( "github.com/gravitational/trace" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -55,7 +54,7 @@ type Adapter[T Resource] interface { type KubernetesCR[T Resource] interface { kclient.Object ToTeleport() T - StatusConditions() *[]v1.Condition + StatusConditions() *[]metav1.Condition } // resourceClient is a CRUD client for a specific Teleport Resource. diff --git a/integrations/operator/controllers/resources/testlib/env.go b/integrations/operator/controllers/resources/testlib/env.go index 2c503ed69817a..37cf29ec53f1a 100644 --- a/integrations/operator/controllers/resources/testlib/env.go +++ b/integrations/operator/controllers/resources/testlib/env.go @@ -38,7 +38,6 @@ import ( "k8s.io/client-go/rest" "k8s.io/utils/ptr" ctrl "sigs.k8s.io/controller-runtime" - ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" kclient "sigs.k8s.io/controller-runtime/pkg/client" ctrlconfig "sigs.k8s.io/controller-runtime/pkg/config" "sigs.k8s.io/controller-runtime/pkg/envtest" @@ -205,7 +204,7 @@ func (s *TestSetup) StartKubernetesOperator(t *testing.T) { SkipNameValidation: ptr.To(true), }, // We enable cache to ensure the tests are close to how the manager is created when running in a real cluster - Client: ctrlclient.Options{Cache: &ctrlclient.CacheOptions{Unstructured: true}}, + Client: kclient.Options{Cache: &kclient.CacheOptions{Unstructured: true}}, }) require.NoError(t, err) diff --git a/integrations/terraform/tfschema/time_type.go b/integrations/terraform/tfschema/time_type.go index d2873898c2b61..70718c8c5134f 100644 --- a/integrations/terraform/tfschema/time_type.go +++ b/integrations/terraform/tfschema/time_type.go @@ -194,7 +194,7 @@ func (t TimeValue) Equal(other attr.Value) bool { return false } - return t.Value == o.Value + return t.Value.Equal(o.Value) } // IsNull returns true if receiver is null diff --git a/lib/auth/apiserver.go b/lib/auth/apiserver.go index 5e350abbccb74..903efe88318ab 100644 --- a/lib/auth/apiserver.go +++ b/lib/auth/apiserver.go @@ -31,7 +31,7 @@ import ( "github.com/jonboulle/clockwork" "github.com/julienschmidt/httprouter" - apidefaults "github.com/gravitational/teleport/api/defaults" + "github.com/gravitational/teleport/api/defaults" "github.com/gravitational/teleport/api/types" apievents "github.com/gravitational/teleport/api/types/events" "github.com/gravitational/teleport/lib/auth/authclient" @@ -68,10 +68,10 @@ type APIConfig struct { // CheckAndSetDefaults checks and sets default values func (a *APIConfig) CheckAndSetDefaults() error { if a.KeepAlivePeriod == 0 { - a.KeepAlivePeriod = apidefaults.ServerKeepAliveTTL() + a.KeepAlivePeriod = defaults.ServerKeepAliveTTL() } if a.KeepAliveCount == 0 { - a.KeepAliveCount = apidefaults.KeepAliveCountMax + a.KeepAliveCount = defaults.KeepAliveCountMax } if a.Authorizer == nil { return trace.BadParameter("authorizer is missing") diff --git a/lib/auth/auth.go b/lib/auth/auth.go index 4a849a9ec19ef..edf4449dd578c 100644 --- a/lib/auth/auth.go +++ b/lib/auth/auth.go @@ -451,7 +451,7 @@ func NewServer(cfg *InitConfig, opts ...ServerOption) (*Server, error) { } } else if cfg.KeyStoreConfig.GCPKMS != (servicecfg.GCPKMSConfig{}) { if !modules.GetModules().Features().GetEntitlement(entitlements.HSM).Enabled { - return nil, fmt.Errorf("Google Cloud KMS support requires a license with the HSM feature enabled: %w", ErrRequiresEnterprise) + return nil, fmt.Errorf("GCP KMS support requires a license with the HSM feature enabled: %w", ErrRequiresEnterprise) } } else if cfg.KeyStoreConfig.AWSKMS != nil { if !modules.GetModules().Features().GetEntitlement(entitlements.HSM).Enabled { @@ -3096,7 +3096,7 @@ func generateCert(ctx context.Context, a *Server, req certRequest, caType types. } if len(req.checker.GetAllowedResourceIDs()) > 0 && modules.GetModules().BuildType() != modules.BuildEnterprise { - return nil, fmt.Errorf("Resource Access Requests: %w", ErrRequiresEnterprise) + return nil, fmt.Errorf("resource access requests: %w", ErrRequiresEnterprise) } // Reject the cert request if there is a matching lock in force. @@ -6585,7 +6585,7 @@ func (a *Server) CreateSessionTracker(ctx context.Context, tracker types.Session for _, policySet := range tracker.GetHostPolicySets() { if len(policySet.RequireSessionJoin) != 0 { if modules.GetModules().BuildType() != modules.BuildEnterprise { - return nil, fmt.Errorf("Moderated Sessions: %w", ErrRequiresEnterprise) + return nil, fmt.Errorf("moderated sessions: %w", ErrRequiresEnterprise) } } } diff --git a/lib/auth/auth_with_roles.go b/lib/auth/auth_with_roles.go index 1a1788381c827..b73a78424b120 100644 --- a/lib/auth/auth_with_roles.go +++ b/lib/auth/auth_with_roles.go @@ -50,7 +50,6 @@ import ( apievents "github.com/gravitational/teleport/api/types/events" "github.com/gravitational/teleport/api/types/wrappers" "github.com/gravitational/teleport/api/utils" - apiutils "github.com/gravitational/teleport/api/utils" "github.com/gravitational/teleport/api/utils/keys/hardwarekey" "github.com/gravitational/teleport/entitlements" "github.com/gravitational/teleport/lib/auth/authclient" @@ -1679,7 +1678,7 @@ func (a *ServerWithRoles) GetSSHTargets(ctx context.Context, req *proto.GetSSHTa caseInsensitiveRouting = cfg.GetCaseInsensitiveRouting() } - matcher, err := apiutils.NewSSHRouteMatcherFromConfig(apiutils.SSHRouteMatcherConfig{ + matcher, err := utils.NewSSHRouteMatcherFromConfig(utils.SSHRouteMatcherConfig{ Host: req.Host, Port: req.Port, CaseInsensitive: caseInsensitiveRouting, @@ -3147,7 +3146,7 @@ func (a *ServerWithRoles) desiredAccessInfoForUser(ctx context.Context, req *pro } } } - finalRequestIDs = apiutils.Deduplicate(finalRequestIDs) + finalRequestIDs = utils.Deduplicate(finalRequestIDs) // Replace req.AccessRequests with final filtered values, these will be // encoded into the cert. @@ -3182,7 +3181,7 @@ func (a *ServerWithRoles) desiredAccessInfoForUser(ctx context.Context, req *pro accessInfo.AllowedResourceIDs = requestedResourceIDs } } - accessInfo.Roles = apiutils.Deduplicate(accessInfo.Roles) + accessInfo.Roles = utils.Deduplicate(accessInfo.Roles) return accessInfo, nil } diff --git a/lib/auth/auth_with_roles_test.go b/lib/auth/auth_with_roles_test.go index 33adc1df125f0..c55e45b9a2c78 100644 --- a/lib/auth/auth_with_roles_test.go +++ b/lib/auth/auth_with_roles_test.go @@ -163,8 +163,8 @@ func TestGenerateUserCerts_MFAVerifiedFieldSet(t *testing.T) { require.NoError(t, err) mfaVerified := sshCert.Permissions.Extensions[teleport.CertExtensionMFAVerified] - switch { - case mfaResponse == nil: + switch mfaResponse { + case nil: require.Empty(t, mfaVerified, "GenerateUserCerts returned certificate with non-empty CertExtensionMFAVerified") default: require.Equal(t, mfaVerified, u.totpDev.MFA.Id, "GenerateUserCerts returned certificate with unexpected CertExtensionMFAVerified") @@ -2912,7 +2912,7 @@ func TestGetAndList_DatabaseServers(t *testing.T) { require.NoError(t, err) servers, err = clt.GetDatabaseServers(ctx, apidefaults.Namespace) require.NoError(t, err) - require.EqualValues(t, len(testServers), len(servers)) + require.Len(t, testServers, len(servers)) require.Empty(t, cmp.Diff(testServers, servers)) resp, err = clt.ListResources(ctx, listRequest) require.NoError(t, err) @@ -2956,7 +2956,7 @@ func TestGetAndList_DatabaseServers(t *testing.T) { require.NoError(t, err) servers, err = clt.GetDatabaseServers(ctx, apidefaults.Namespace) require.NoError(t, err) - require.EqualValues(t, len(testServers[1:]), len(servers)) + require.Len(t, testServers[1:], len(servers)) require.Empty(t, cmp.Diff(testServers[1:], servers)) resp, err = clt.ListResources(ctx, listRequest) require.NoError(t, err) @@ -3039,7 +3039,7 @@ func TestGetAndList_ApplicationServers(t *testing.T) { require.NoError(t, err) servers, err = clt.GetApplicationServers(ctx, apidefaults.Namespace) require.NoError(t, err) - require.EqualValues(t, len(testServers), len(servers)) + require.Len(t, testServers, len(servers)) require.Empty(t, cmp.Diff(testServers, servers)) resp, err = clt.ListResources(ctx, listRequest) require.NoError(t, err) @@ -3083,7 +3083,7 @@ func TestGetAndList_ApplicationServers(t *testing.T) { require.NoError(t, err) servers, err = clt.GetApplicationServers(ctx, apidefaults.Namespace) require.NoError(t, err) - require.EqualValues(t, len(testServers[1:]), len(servers)) + require.Len(t, testServers[1:], len(servers)) require.Empty(t, cmp.Diff(testServers[1:], servers)) resp, err = clt.ListResources(ctx, listRequest) require.NoError(t, err) @@ -3247,7 +3247,7 @@ func TestGetAndList_AppServersAndSAMLIdPServiceProviders(t *testing.T) { require.NoError(t, err) servers, err = clt.GetApplicationServers(ctx, apidefaults.Namespace) require.NoError(t, err) - require.EqualValues(t, len(testAppServers[1:]), len(servers)) + require.Len(t, testAppServers[1:], len(servers)) require.Empty(t, cmp.Diff(testAppServers[1:], servers)) resp, err = clt.ListResources(ctx, listRequest) require.NoError(t, err) @@ -3322,7 +3322,7 @@ func TestListSAMLIdPServiceProviderAndListResources(t *testing.T) { sps, _, err := clt.ListSAMLIdPServiceProviders(ctx, 0, "") require.NoError(t, err) - require.EqualValues(t, len(testServiceProviders), len(sps)) + require.Len(t, testServiceProviders, len(sps)) require.Empty(t, cmp.Diff(testServiceProviders, sps)) resp, err := clt.ListResources(ctx, listRequest) require.NoError(t, err) @@ -4458,7 +4458,7 @@ func TestGetAndList_WindowsDesktops(t *testing.T) { require.NoError(t, err) desktops, err = clt.GetWindowsDesktops(ctx, types.WindowsDesktopFilter{}) require.NoError(t, err) - require.EqualValues(t, len(testDesktops), len(desktops)) + require.Len(t, testDesktops, len(desktops)) require.Empty(t, cmp.Diff(testDesktops, desktops)) resp, err = clt.ListResources(ctx, listRequest) @@ -4513,7 +4513,7 @@ func TestGetAndList_WindowsDesktops(t *testing.T) { desktops, err = clt.GetWindowsDesktops(ctx, types.WindowsDesktopFilter{}) require.NoError(t, err) - require.EqualValues(t, len(testDesktops[1:]), len(desktops)) + require.Len(t, testDesktops[1:], len(desktops)) require.Empty(t, cmp.Diff(testDesktops[1:], desktops)) resp, err = clt.ListResources(ctx, listRequest) diff --git a/lib/auth/autoupdate/autoupdatev1/service.go b/lib/auth/autoupdate/autoupdatev1/service.go index 31d9962fb22d4..01be297d26702 100644 --- a/lib/auth/autoupdate/autoupdatev1/service.go +++ b/lib/auth/autoupdate/autoupdatev1/service.go @@ -540,7 +540,7 @@ func (s *Service) CreateAutoUpdateAgentRollout(ctx context.Context, req *autoupd // This is not ideal as it forces local tctl usage and can be bypassed if the user is very creative. // In the future, if we expand the permission system and make cloud // a first class citizen, we'll want to update this permission check. - if !(authz.HasBuiltinRole(*authCtx, string(types.RoleAuth)) || authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin))) { + if !authz.HasBuiltinRole(*authCtx, string(types.RoleAuth)) && !authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin)) { return nil, trace.AccessDenied("this request can be only executed by an auth server") } @@ -569,7 +569,7 @@ func (s *Service) UpdateAutoUpdateAgentRollout(ctx context.Context, req *autoupd // This is not ideal as it forces local tctl usage and can be bypassed if the user is very creative. // In the future, if we expand the permission system and make cloud // a first class citizen, we'll want to update this permission check. - if !(authz.HasBuiltinRole(*authCtx, string(types.RoleAuth)) || authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin))) { + if !authz.HasBuiltinRole(*authCtx, string(types.RoleAuth)) && !authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin)) { return nil, trace.AccessDenied("this request can be only executed by an auth server") } @@ -598,7 +598,7 @@ func (s *Service) UpsertAutoUpdateAgentRollout(ctx context.Context, req *autoupd // This is not ideal as it forces local tctl usage and can be bypassed if the user is very creative. // In the future, if we expand the permission system and make cloud // a first class citizen, we'll want to update this permission check. - if !(authz.HasBuiltinRole(*authCtx, string(types.RoleAuth)) || authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin))) { + if !authz.HasBuiltinRole(*authCtx, string(types.RoleAuth)) && !authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin)) { return nil, trace.AccessDenied("this request can be only executed by an auth server") } @@ -627,7 +627,7 @@ func (s *Service) DeleteAutoUpdateAgentRollout(ctx context.Context, req *autoupd // This is not ideal as it forces local tctl usage and can be bypassed if the user is very creative. // In the future, if we expand the permission system and make cloud // a first class citizen, we'll want to update this permission check. - if !(authz.HasBuiltinRole(*authCtx, string(types.RoleAuth)) || authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin))) { + if !authz.HasBuiltinRole(*authCtx, string(types.RoleAuth)) && !authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin)) { return nil, trace.AccessDenied("this request can be only executed by an auth server") } diff --git a/lib/auth/bot_test.go b/lib/auth/bot_test.go index 66588f6e6ac97..3fe68065c6ab4 100644 --- a/lib/auth/bot_test.go +++ b/lib/auth/bot_test.go @@ -66,7 +66,6 @@ import ( "github.com/gravitational/teleport/lib/events/eventstest" "github.com/gravitational/teleport/lib/fixtures" "github.com/gravitational/teleport/lib/kube/token" - kubetoken "github.com/gravitational/teleport/lib/kube/token" "github.com/gravitational/teleport/lib/reversetunnelclient" "github.com/gravitational/teleport/lib/tbot/identity" "github.com/gravitational/teleport/lib/tlsca" @@ -917,9 +916,9 @@ func TestRegisterBot_BotInstanceRejoin(t *testing.T) { k8sReadFileFunc := func(name string) ([]byte, error) { return []byte(k8sTokenName), nil } - a.k8sJWKSValidator = func(_ time.Time, _ []byte, _ string, token string) (*token.ValidationResult, error) { - if token == k8sTokenName { - return &kubetoken.ValidationResult{Username: "system:serviceaccount:static-jwks:matching"}, nil + a.k8sJWKSValidator = func(_ time.Time, _ []byte, _ string, tkn string) (*token.ValidationResult, error) { + if tkn == k8sTokenName { + return &token.ValidationResult{Username: "system:serviceaccount:static-jwks:matching"}, nil } return nil, errMockInvalidToken @@ -1074,9 +1073,9 @@ func TestRegisterBotWithInvalidInstanceID(t *testing.T) { botName := "bot" k8sTokenName := "jwks-matching-service-account" - a.k8sJWKSValidator = func(_ time.Time, _ []byte, _ string, token string) (*token.ValidationResult, error) { - if token == k8sTokenName { - return &kubetoken.ValidationResult{Username: "system:serviceaccount:static-jwks:matching"}, nil + a.k8sJWKSValidator = func(_ time.Time, _ []byte, _ string, tkn string) (*token.ValidationResult, error) { + if tkn == k8sTokenName { + return &token.ValidationResult{Username: "system:serviceaccount:static-jwks:matching"}, nil } return nil, errMockInvalidToken diff --git a/lib/auth/crownjewel/crownjewelv1/service.go b/lib/auth/crownjewel/crownjewelv1/service.go index b78cfa29f3129..109fad797082f 100644 --- a/lib/auth/crownjewel/crownjewelv1/service.go +++ b/lib/auth/crownjewel/crownjewelv1/service.go @@ -30,7 +30,6 @@ import ( crownjewelv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/crownjewel/v1" "github.com/gravitational/teleport/api/types" "github.com/gravitational/teleport/api/types/events" - apievents "github.com/gravitational/teleport/api/types/events" "github.com/gravitational/teleport/lib/auth/crownjewel" "github.com/gravitational/teleport/lib/authz" libevents "github.com/gravitational/teleport/lib/events" @@ -128,15 +127,15 @@ func (s *Service) CreateCrownJewel(ctx context.Context, req *crownjewelv1.Create } func (s *Service) emitCreateAuditEvent(ctx context.Context, req *crownjewelv1.CrownJewel, authCtx *authz.Context, err error) { - if auditErr := s.emitter.EmitAuditEvent(ctx, &apievents.CrownJewelCreate{ - Metadata: apievents.Metadata{ + if auditErr := s.emitter.EmitAuditEvent(ctx, &events.CrownJewelCreate{ + Metadata: events.Metadata{ Type: libevents.CrownJewelCreateEvent, Code: libevents.CrownJewelCreateCode, }, UserMetadata: authCtx.GetUserMetadata(), ConnectionMetadata: authz.ConnectionMetadata(ctx), Status: eventStatus(err), - ResourceMetadata: apievents.ResourceMetadata{ + ResourceMetadata: events.ResourceMetadata{ Name: req.GetMetadata().GetName(), Expires: getExpires(req.GetMetadata().GetExpires()), UpdatedBy: authCtx.Identity.GetIdentity().Username, @@ -220,15 +219,15 @@ func (s *Service) UpdateCrownJewel(ctx context.Context, req *crownjewelv1.Update } func (s *Service) emitUpdateAuditEvent(ctx context.Context, old, new *crownjewelv1.CrownJewel, authCtx *authz.Context, err error) { - if auditErr := s.emitter.EmitAuditEvent(ctx, &apievents.CrownJewelUpdate{ - Metadata: apievents.Metadata{ + if auditErr := s.emitter.EmitAuditEvent(ctx, &events.CrownJewelUpdate{ + Metadata: events.Metadata{ Type: libevents.CrownJewelUpdateEvent, Code: libevents.CrownJewelUpdateCode, }, UserMetadata: authCtx.GetUserMetadata(), ConnectionMetadata: authz.ConnectionMetadata(ctx), Status: eventStatus(err), - ResourceMetadata: apievents.ResourceMetadata{ + ResourceMetadata: events.ResourceMetadata{ Name: new.GetMetadata().GetName(), Expires: getExpires(new.GetMetadata().GetExpires()), UpdatedBy: authCtx.Identity.GetIdentity().Username, @@ -300,15 +299,15 @@ func (s *Service) DeleteCrownJewel(ctx context.Context, req *crownjewelv1.Delete err = s.backend.DeleteCrownJewel(ctx, req.GetName()) - if auditErr := s.emitter.EmitAuditEvent(ctx, &apievents.CrownJewelDelete{ - Metadata: apievents.Metadata{ + if auditErr := s.emitter.EmitAuditEvent(ctx, &events.CrownJewelDelete{ + Metadata: events.Metadata{ Type: libevents.CrownJewelDeleteEvent, Code: libevents.CrownJewelDeleteCode, }, UserMetadata: authCtx.GetUserMetadata(), ConnectionMetadata: authz.ConnectionMetadata(ctx), Status: eventStatus(err), - ResourceMetadata: apievents.ResourceMetadata{ + ResourceMetadata: events.ResourceMetadata{ Name: req.GetName(), UpdatedBy: authCtx.Identity.GetIdentity().Username, }, @@ -323,13 +322,13 @@ func (s *Service) DeleteCrownJewel(ctx context.Context, req *crownjewelv1.Delete return &emptypb.Empty{}, nil } -func eventStatus(err error) apievents.Status { +func eventStatus(err error) events.Status { var msg string if err != nil { msg = err.Error() } - return apievents.Status{ + return events.Status{ Success: err == nil, Error: msg, UserMessage: msg, diff --git a/lib/auth/grpcserver.go b/lib/auth/grpcserver.go index dba0fb588f7dd..6bb84f8adbf4e 100644 --- a/lib/auth/grpcserver.go +++ b/lib/auth/grpcserver.go @@ -3434,8 +3434,7 @@ func (g *GRPCServer) GetEvents(ctx context.Context, req *authpb.GetEventsRequest return nil, trace.Wrap(err) } - var res *authpb.Events = &authpb.Events{} - + res := &authpb.Events{} encodedEvents := make([]*apievents.OneOf, 0, len(rawEvents)) for _, rawEvent := range rawEvents { @@ -3469,8 +3468,7 @@ func (g *GRPCServer) GetSessionEvents(ctx context.Context, req *authpb.GetSessio return nil, trace.Wrap(err) } - var res *authpb.Events = &authpb.Events{} - + res := &authpb.Events{} encodedEvents := make([]*apievents.OneOf, 0, len(rawEvents)) for _, rawEvent := range rawEvents { diff --git a/lib/auth/grpcserver_test.go b/lib/auth/grpcserver_test.go index bc710572e3033..c3431263a8eff 100644 --- a/lib/auth/grpcserver_test.go +++ b/lib/auth/grpcserver_test.go @@ -1719,7 +1719,7 @@ func TestGenerateUserCerts_singleUseCerts(t *testing.T) { require.Equal(t, []string{teleport.UsageAppsOnly}, identity.Usage) require.Equal(t, "app-a", identity.RouteToApp.Name) // session ID should be set to a random ID, corresponding to an app session. - require.NotZero(t, identity.RouteToApp.SessionID) + require.NotEmpty(t, identity.RouteToApp.SessionID) }, }, }, @@ -1760,7 +1760,7 @@ func TestGenerateUserCerts_singleUseCerts(t *testing.T) { require.Equal(t, "app-a", identity.RouteToApp.Name) require.Equal(t, 1337, identity.RouteToApp.TargetPort) // session ID should be set to a random ID, corresponding to an app session. - require.NotZero(t, identity.RouteToApp.SessionID) + require.NotEmpty(t, identity.RouteToApp.SessionID) }, }, }, @@ -1877,7 +1877,7 @@ func TestGenerateUserCerts_singleUseCerts(t *testing.T) { require.Equal(t, []string{teleport.UsageAppsOnly}, identity.Usage) require.Equal(t, "app-a", identity.RouteToApp.Name) // session ID should be set to a random ID, corresponding to an app session. - require.NotZero(t, identity.RouteToApp.SessionID) + require.NotEmpty(t, identity.RouteToApp.SessionID) }, }, }, @@ -2187,7 +2187,7 @@ func TestGenerateUserCerts_singleUseCerts(t *testing.T) { require.Equal(t, []string{teleport.UsageAppsOnly}, identity.Usage) require.Equal(t, "app-b", identity.RouteToApp.Name) // session ID should be set to a random ID, corresponding to an app session. - require.NotZero(t, identity.RouteToApp.SessionID) + require.NotEmpty(t, identity.RouteToApp.SessionID) }, }, }, diff --git a/lib/auth/keystore/aws_kms_test.go b/lib/auth/keystore/aws_kms_test.go index 2b689bda7031d..12fb7e89335cd 100644 --- a/lib/auth/keystore/aws_kms_test.go +++ b/lib/auth/keystore/aws_kms_test.go @@ -323,7 +323,7 @@ func TestAWSKeyCreationParameters(t *testing.T) { "TeleportCluster": clusterName.GetClusterName(), } } - require.Equal(t, len(tc.tags), len(tagsOut.Tags)) + require.Len(t, tc.tags, len(tagsOut.Tags)) for _, tag := range tagsOut.Tags { v := tc.tags[aws.ToString(tag.TagKey)] require.Equal(t, v, aws.ToString(tag.TagValue)) diff --git a/lib/auth/keystore/testhelpers.go b/lib/auth/keystore/testhelpers.go index ff6592cd32a2b..1bb11eae9765d 100644 --- a/lib/auth/keystore/testhelpers.go +++ b/lib/auth/keystore/testhelpers.go @@ -160,9 +160,7 @@ func softHSMTestConfig(t *testing.T) (servicecfg.KeystoreConfig, bool) { require.NoError(t, err) // write config file - _, err = configFile.WriteString(fmt.Sprintf( - "directories.tokendir = %s\nobjectstore.backend = file\nlog.level = DEBUG\n", - tokenDir)) + _, err = fmt.Fprintf(configFile, "directories.tokendir = %s\nobjectstore.backend = file\nlog.level = DEBUG\n", tokenDir) require.NoError(t, err) require.NoError(t, configFile.Close()) @@ -171,7 +169,7 @@ func softHSMTestConfig(t *testing.T) (servicecfg.KeystoreConfig, bool) { } // create test token (max length is 32 chars) - tokenLabel := strings.Replace(uuid.NewString(), "-", "", -1) + tokenLabel := strings.ReplaceAll(uuid.NewString(), "-", "") cmd := exec.Command("softhsm2-util", "--init-token", "--free", "--label", tokenLabel, "--so-pin", "password", "--pin", "password") t.Logf("Running command: %q", cmd) if err := cmd.Run(); err != nil { diff --git a/lib/auth/machineid/machineidv1/bot_service.go b/lib/auth/machineid/machineidv1/bot_service.go index 73f9e9fc67388..139612f54b056 100644 --- a/lib/auth/machineid/machineidv1/bot_service.go +++ b/lib/auth/machineid/machineidv1/bot_service.go @@ -497,8 +497,8 @@ func (bs *BotService) UpdateBot( } for _, path := range req.UpdateMask.Paths { - switch { - case path == "spec.roles": + switch path { + case "spec.roles": if slices.Contains(req.Bot.Spec.Roles, "") { return nil, trace.BadParameter( "spec.roles: must not contain empty strings", @@ -507,7 +507,7 @@ func (bs *BotService) UpdateBot( role.SetImpersonateConditions(types.Allow, types.ImpersonateConditions{ Roles: req.Bot.Spec.Roles, }) - case path == "spec.traits": + case "spec.traits": traits := map[string][]string{} for _, t := range req.Bot.Spec.Traits { if len(t.Values) == 0 { @@ -519,7 +519,7 @@ func (bs *BotService) UpdateBot( traits[t.Name] = append(traits[t.Name], t.Values...) } user.SetTraits(traits) - case path == "spec.max_session_ttl": + case "spec.max_session_ttl": opts := role.GetOptions() opts.MaxSessionTTL = types.Duration(req.Bot.Spec.MaxSessionTtl.AsDuration()) role.SetOptions(opts) diff --git a/lib/auth/notification_test.go b/lib/auth/notification_test.go index 4e429761194aa..c738f2d663dda 100644 --- a/lib/auth/notification_test.go +++ b/lib/auth/notification_test.go @@ -366,7 +366,7 @@ func TestNotifications(t *testing.T) { // Verify that all the notifications are in the list and in correct order. require.Equal(t, auditorExpectedNotifications, notificationsToTitlesList(t, finalOut)) // Verify that we've reached the end of both lists. - require.Equal(t, "", resp.NextPageToken) + require.Empty(t, resp.NextPageToken) // Mark "auditor-2" and "auditor-5,manager-2" as dismissed. _, err = auditorClient.UpsertUserNotificationState(ctx, auditorUsername, ¬ificationsv1.UserNotificationState{ @@ -410,7 +410,7 @@ func TestNotifications(t *testing.T) { require.Equal(t, managerExpectedNotifications, notificationsToTitlesList(t, resp.Notifications)) // Verify that we've reached the end of both lists. - require.Equal(t, "", resp.NextPageToken) + require.Empty(t, resp.NextPageToken) // Mark "manager-8-expires" as clicked. _, err = managerClient.UpsertUserNotificationState(ctx, managerUsername, ¬ificationsv1.UserNotificationState{ diff --git a/lib/auth/users/usersv1/service_test.go b/lib/auth/users/usersv1/service_test.go index 9ee52efdf14c1..c93a8e6b73174 100644 --- a/lib/auth/users/usersv1/service_test.go +++ b/lib/auth/users/usersv1/service_test.go @@ -520,7 +520,7 @@ func TestListUsers(t *testing.T) { next = resp.NextPageToken } - assert.Equal(t, len(createdUsers), len(listedUsers), "expected to eventually retrieve all users from listing") + assert.Len(t, createdUsers, len(listedUsers), "expected to eventually retrieve all users from listing") assert.Empty(t, cmp.Diff(createdUsers, listedUsers, cmpopts.SortSlices(func(a, b *types.UserV2) bool { return a.GetName() < b.GetName() }), cmpopts.IgnoreFields(types.UserSpecV2{}, "LocalAuth"), @@ -538,7 +538,7 @@ func TestListUsers(t *testing.T) { next = resp.NextPageToken } - assert.Equal(t, len(createdUsers), len(listedUsersWithSecrets), "expected to eventually retrieve all users from listing") + assert.Len(t, createdUsers, len(listedUsersWithSecrets), "expected to eventually retrieve all users from listing") assert.Empty(t, cmp.Diff(createdUsers, listedUsersWithSecrets, cmpopts.SortSlices(func(a, b *types.UserV2) bool { return a.GetName() < b.GetName() }), )) diff --git a/lib/auth/webauthncli/api.go b/lib/auth/webauthncli/api.go index 8278c77a03634..d06902b4a3752 100644 --- a/lib/auth/webauthncli/api.go +++ b/lib/auth/webauthncli/api.go @@ -38,7 +38,7 @@ import ( // authenticate with a non-registered security key. // The error message is meant to be displayed to end-users, thus it breaks the // usual Go error conventions (capitalized sentences, punctuation). -var ErrUsingNonRegisteredDevice = errors.New("You are using a security key that is not registered with Teleport. Try a different security key.") +var ErrUsingNonRegisteredDevice = errors.New("you are using a security key that is not registered with Teleport - try a different security key") // AuthenticatorAttachment allows callers to choose a specific attachment. type AuthenticatorAttachment int diff --git a/lib/autoupdate/agent/setup.go b/lib/autoupdate/agent/setup.go index 940647afc5dd3..2161fbff8be32 100644 --- a/lib/autoupdate/agent/setup.go +++ b/lib/autoupdate/agent/setup.go @@ -35,7 +35,6 @@ import ( "gopkg.in/yaml.v3" "github.com/gravitational/teleport/lib/defaults" - libdefaults "github.com/gravitational/teleport/lib/defaults" libutils "github.com/gravitational/teleport/lib/utils" ) @@ -504,13 +503,13 @@ func (ns *Namespace) overrideFromConfig(ctx context.Context) { switch t := cfg.Teleport; { case t.ProxyServer != "": addr = t.ProxyServer - port = libdefaults.HTTPListenPort + port = defaults.HTTPListenPort case t.AuthServer != "": addr = t.AuthServer - port = libdefaults.AuthListenPort + port = defaults.AuthListenPort case len(t.AuthServers) > 0: addr = t.AuthServers[0] - port = libdefaults.AuthListenPort + port = defaults.AuthListenPort default: ns.log.DebugContext(ctx, "Unable to find proxy in Teleport config", "config", path, errorKey, err) return diff --git a/lib/autoupdate/rollout/client_test.go b/lib/autoupdate/rollout/client_test.go index 782251a562025..660cf0ae8f2a0 100644 --- a/lib/autoupdate/rollout/client_test.go +++ b/lib/autoupdate/rollout/client_test.go @@ -85,8 +85,8 @@ func (m mockClient) checkIfEmpty(t *testing.T) { func newMockClient(t *testing.T, stubs mockClientStubs) *mockClient { // Fail early if there's a mismatch - require.Equal(t, len(stubs.createRolloutAnswers), len(stubs.createRolloutExpects), "invalid stubs, create validations and answers slices are not the same length") - require.Equal(t, len(stubs.updateRolloutAnswers), len(stubs.updateRolloutExpects), "invalid stubs, update validations and answers slices are not the same length") + require.Len(t, stubs.createRolloutAnswers, len(stubs.createRolloutExpects), "invalid stubs, create validations and answers slices are not the same length") + require.Len(t, stubs.updateRolloutAnswers, len(stubs.updateRolloutExpects), "invalid stubs, update validations and answers slices are not the same length") return &mockClient{ getAutoUpdateConfig: &getHandler[*autoupdate.AutoUpdateConfig]{t, stubs.configAnswers}, diff --git a/lib/autoupdate/rollout/metrics.go b/lib/autoupdate/rollout/metrics.go index 0f68ef756510e..1fbd3e00f5cc1 100644 --- a/lib/autoupdate/rollout/metrics.go +++ b/lib/autoupdate/rollout/metrics.go @@ -337,7 +337,7 @@ func (m *metrics) observeRollout(rollout *autoupdatepb.AutoUpdateAgentRollout, n m.setStrategyMetric(rollout.GetSpec().GetStrategy(), m.rolloutStrategy) - if to := rollout.GetStatus().GetTimeOverride().AsTime(); !(to.IsZero() || to.Unix() == 0) { + if to := rollout.GetStatus().GetTimeOverride().AsTime(); !to.IsZero() && to.Unix() != 0 { m.rolloutTimeOverride.Set(float64(to.Second())) } else { m.rolloutTimeOverride.Set(0) diff --git a/lib/autoupdate/rollout/reconciler.go b/lib/autoupdate/rollout/reconciler.go index 96ebf8791f257..cddd023f4e9b2 100644 --- a/lib/autoupdate/rollout/reconciler.go +++ b/lib/autoupdate/rollout/reconciler.go @@ -321,7 +321,7 @@ func (r *reconciler) computeStatus( // If timeOverride is set to a non-zero value (we have two potential zeros, go time's zero and timestamppb's zero) // we use this instead of the clock's time. - if timeOverride := status.GetTimeOverride().AsTime(); !(timeOverride.IsZero() || timeOverride.Unix() == 0) { + if timeOverride := status.GetTimeOverride().AsTime(); !timeOverride.IsZero() && timeOverride.Unix() != 0 { r.log.DebugContext(ctx, "reconciling with synthetic time instead of real time", "time_override", timeOverride, "real_time", now, diff --git a/lib/backend/memory/memory.go b/lib/backend/memory/memory.go index 58a5364958eed..c037610fe5429 100644 --- a/lib/backend/memory/memory.go +++ b/lib/backend/memory/memory.go @@ -467,10 +467,7 @@ func (m *Memory) removeExpired() int { removed := 0 now := m.Clock().Now().UTC() - for { - if len(*m.heap) == 0 { - break - } + for len(*m.heap) != 0 { item := m.heap.PeekEl() if now.Before(item.Expires) { break diff --git a/lib/backend/pgbk/wal2json.go b/lib/backend/pgbk/wal2json.go index f9e1b095867e4..d52db87ebea66 100644 --- a/lib/backend/pgbk/wal2json.go +++ b/lib/backend/pgbk/wal2json.go @@ -112,12 +112,8 @@ func (w *wal2jsonMessage) Events() ([]backend.Event, error) { switch w.Action { case "B", "C", "M": return nil, nil - default: - return nil, trace.BadParameter("unexpected action %q", w.Action) - case "T": return nil, trace.BadParameter("received truncate for table kv") - case "I": key, err := w.newCol("key").Bytea() if err != nil { @@ -145,7 +141,6 @@ func (w *wal2jsonMessage) Events() ([]backend.Event, error) { Revision: revisionToString(revision), }, }}, nil - case "D": key, err := w.oldCol("key").Bytea() if err != nil { @@ -157,7 +152,6 @@ func (w *wal2jsonMessage) Events() ([]backend.Event, error) { Key: backend.KeyFromString(string(key)), }, }}, nil - case "U": // on an UPDATE, an unmodified TOASTed column might be missing from // "columns", but it should be present in "identity" (and this also @@ -218,6 +212,8 @@ func (w *wal2jsonMessage) Events() ([]backend.Event, error) { Revision: revisionToString(revision), }, }}, nil + default: + return nil, trace.BadParameter("unexpected action %q", w.Action) } } diff --git a/lib/bitbucket/token_source_test.go b/lib/bitbucket/token_source_test.go index bef39ae24645c..3f9c5bb6e000b 100644 --- a/lib/bitbucket/token_source_test.go +++ b/lib/bitbucket/token_source_test.go @@ -43,6 +43,6 @@ func TestIDTokenSource_GetIDToken(t *testing.T) { tok, err := its.GetIDToken() require.Error(t, err) require.True(t, trace.IsBadParameter(err)) - require.Equal(t, "", tok) + require.Empty(t, tok) }) } diff --git a/lib/cache/collections.go b/lib/cache/collections.go index ab38cd08ee1ff..69ca476134ad4 100644 --- a/lib/cache/collections.go +++ b/lib/cache/collections.go @@ -1148,7 +1148,7 @@ func (e certAuthorityExecutor) getAll(ctx context.Context, cache *Cache, loadSec // if caType was added in this major version we might get a BadParameter // error if we're connecting to an older upstream that doesn't know about it if err != nil { - if !(types.IsUnsupportedAuthorityErr(err) && caType.NewlyAdded()) { + if !types.IsUnsupportedAuthorityErr(err) || !caType.NewlyAdded() { return nil, trace.Wrap(err) } continue diff --git a/lib/client/debug/debug_test.go b/lib/client/debug/debug_test.go index fd1dbe663b31a..52ced041ca0d6 100644 --- a/lib/client/debug/debug_test.go +++ b/lib/client/debug/debug_test.go @@ -87,7 +87,7 @@ func TestGetReadiness(t *testing.T) { out, err := clt.GetReadiness(ctx) require.True(t, trace.IsNotFound(err)) - require.Equal(t, "", out.Status) + require.Empty(t, out.Status) require.False(t, out.Ready) require.Equal(t, 0, out.PID) }) @@ -100,7 +100,7 @@ func TestGetReadiness(t *testing.T) { out, err := clt.GetReadiness(ctx) var netError net.Error require.ErrorAs(t, err, &netError) - require.Equal(t, "", out.Status) + require.Empty(t, out.Status) require.False(t, out.Ready) require.Equal(t, 0, out.PID) }) @@ -113,7 +113,7 @@ func TestGetReadiness(t *testing.T) { out, err := clt.GetReadiness(ctx) require.ErrorIs(t, err, os.ErrNotExist) - require.Equal(t, "", out.Status) + require.Empty(t, out.Status) require.False(t, out.Ready) require.Equal(t, 0, out.PID) }) diff --git a/lib/cloud/azure/kubernetes.go b/lib/cloud/azure/kubernetes.go index c9a6ddaf4d7c9..fd0225c9ede3f 100644 --- a/lib/cloud/azure/kubernetes.go +++ b/lib/cloud/azure/kubernetes.go @@ -336,8 +336,8 @@ func (c *aksClient) getAzureADCredentials(ctx context.Context, cluster ClusterCr // calls the ListClusterAdminCrdentials endpoint to return the admin static credentials. adminCfg, err := c.getAdminCredentials(ctx, cluster.ResourceGroup, cluster.ResourceName) - switch { - case err == nil: + switch err { + case nil: // given the admin credentials, the agent will try to create the ClusterRole and // ClusterRoleBinding objects in the AKS cluster. if adminCredentialsErr = c.grantAccessWithAdminCredentials(ctx, adminCfg, groupID); adminCredentialsErr == nil { diff --git a/lib/config/configuration_test.go b/lib/config/configuration_test.go index 3c89eb1a03c67..a1a7f6f0807be 100644 --- a/lib/config/configuration_test.go +++ b/lib/config/configuration_test.go @@ -780,7 +780,7 @@ func TestApplyConfig(t *testing.T) { require.Equal(t, "tcp://peerhost:1234", cfg.Proxy.PeerAddress.FullAddress()) require.Equal(t, "tcp://peer.example:1234", cfg.Proxy.PeerPublicAddr.FullAddress()) require.True(t, cfg.Proxy.IdP.SAMLIdP.Enabled) - require.Equal(t, "", cfg.Proxy.IdP.SAMLIdP.BaseURL) + require.Empty(t, cfg.Proxy.IdP.SAMLIdP.BaseURL) require.Equal(t, "tcp://127.0.0.1:3000", cfg.DiagnosticAddr.FullAddress()) diff --git a/lib/config/fileconf.go b/lib/config/fileconf.go index 27bd1cef22cda..5fbac2cd97462 100644 --- a/lib/config/fileconf.go +++ b/lib/config/fileconf.go @@ -142,7 +142,7 @@ func ReadConfig(reader io.Reader) (*FileConfig, error) { if err := yaml.UnmarshalStrict(bytes, &fc); err != nil { // Remove all newlines in the YAML error, to avoid escaping when printing. - return nil, trace.BadParameter("failed parsing the config file: %s", strings.Replace(err.Error(), "\n", "", -1)) + return nil, trace.BadParameter("failed parsing the config file: %s", strings.ReplaceAll(err.Error(), "\n", "")) } if err := fc.CheckAndSetDefaults(); err != nil { return nil, trace.BadParameter("failed to parse Teleport configuration: %v", err) diff --git a/lib/devicetrust/native/device_linux.go b/lib/devicetrust/native/device_linux.go index 69eb82845da51..0bdbb97817003 100644 --- a/lib/devicetrust/native/device_linux.go +++ b/lib/devicetrust/native/device_linux.go @@ -109,9 +109,8 @@ func rewriteTPMPermissionError(err error) error { Debug("TPM: Replacing TPM permission error with a more friendly one") return errors.New("" + - "Failed to open the TPM device. " + - "Consider assigning the user to the `tss` group or creating equivalent udev rules. " + - "See https://goteleport.com/docs/admin-guides/access-controls/device-trust/device-management/#troubleshooting.") + "failed to open the TPM device, " + + "consider assigning the user to the `tss` group or creating equivalent udev rules") } // cddFuncs is used to mock various data collection functions for testing. diff --git a/lib/events/dynamic_test.go b/lib/events/dynamic_test.go index 51a389d34b518..6ed6b99bcf7e4 100644 --- a/lib/events/dynamic_test.go +++ b/lib/events/dynamic_test.go @@ -55,8 +55,8 @@ func TestDynamicTypeNotSet(t *testing.T) { require.Equal(t, UnknownEvent, event.GetType()) require.Equal(t, UnknownCode, event.GetCode()) unknownEvent := event.(*events.Unknown) - require.Equal(t, "", unknownEvent.UnknownType) - require.Equal(t, "", unknownEvent.UnknownCode) + require.Empty(t, unknownEvent.UnknownType) + require.Empty(t, unknownEvent.UnknownCode) } // TestDynamicTypeUnknown checks that we correctly translate known events into the correct proto type. diff --git a/lib/events/emitter.go b/lib/events/emitter.go index a790eb1329428..c12e58f492f0b 100644 --- a/lib/events/emitter.go +++ b/lib/events/emitter.go @@ -252,7 +252,7 @@ func (w *WriterEmitter) EmitAuditEvent(ctx context.Context, event apievents.Audi // Teleport Cloud treats this as a no-op. func NewLoggingEmitter(cloud bool) *LoggingEmitter { return &LoggingEmitter{ - emit: !(modules.GetModules().Features().Cloud || cloud), + emit: !modules.GetModules().Features().Cloud && !cloud, } } diff --git a/lib/events/filesessions/fileasync_chaos_test.go b/lib/events/filesessions/fileasync_chaos_test.go index 107bceca6772a..0c0c97c11180f 100644 --- a/lib/events/filesessions/fileasync_chaos_test.go +++ b/lib/events/filesessions/fileasync_chaos_test.go @@ -183,7 +183,7 @@ func TestChaosUpload(t *testing.T) { state := streams[event.SessionID] outEvents := readStream(ctx, t, event.UploadID, memUploader) - require.Equal(t, len(state.events), len(outEvents), fmt.Sprintf("event: %v", event)) + require.Len(t, state.events, len(outEvents), fmt.Sprintf("event: %v", event)) case <-ctx.Done(): t.Fatal("Timeout waiting for async upload, try `go test -v` to get more logs for details") } diff --git a/lib/events/recorder/recorder.go b/lib/events/recorder/recorder.go index b2bf1be6ecbf9..3559df2175b20 100644 --- a/lib/events/recorder/recorder.go +++ b/lib/events/recorder/recorder.go @@ -126,7 +126,7 @@ func New(cfg Config) (events.SessionPreparerRecorder, error) { return events.NewSessionPreparerRecorder(preparer, events.NewDiscardRecorder()), nil } - var streamer events.Streamer = cfg.SyncStreamer + streamer := cfg.SyncStreamer if !services.IsRecordSync(cfg.RecordingCfg.GetMode()) { uploadDir := filepath.Join( cfg.DataDir, teleport.LogsDir, teleport.ComponentUpload, diff --git a/lib/events/session_writer_test.go b/lib/events/session_writer_test.go index d0b9fa72189eb..c8345731352b8 100644 --- a/lib/events/session_writer_test.go +++ b/lib/events/session_writer_test.go @@ -142,7 +142,7 @@ func TestSessionWriter(t *testing.T) { outEvents := test.collectEvents(t) - require.Equal(t, len(inEvents), len(outEvents)) + require.Len(t, inEvents, len(outEvents)) require.Equal(t, inEvents, outEvents) require.Equal(t, 0, int(streamResumed.Load()), "Stream not resumed.") require.Equal(t, 2, int(streamCreated.Load()), "Stream created twice.") @@ -199,7 +199,7 @@ func TestSessionWriter(t *testing.T) { outEvents := test.collectEvents(t) - require.Equal(t, len(inEvents), len(outEvents)) + require.Len(t, inEvents, len(outEvents)) require.Equal(t, inEvents, outEvents) require.Equal(t, 1, int(streamResumed.Load()), "Stream resumed once.") require.Equal(t, 1, int(streamCreated.Load()), "Stream created once.") @@ -291,7 +291,7 @@ func TestSessionWriter(t *testing.T) { require.NoError(t, test.writer.RecordEvent(test.ctx, event)) } test.Close(context.Background()) - require.Equal(t, len(inEvents), len(emittedEvents)) + require.Len(t, inEvents, len(emittedEvents)) for _, event := range emittedEvents { require.Equal(t, "cluster", event.GetClusterName()) } diff --git a/lib/gitlab/token_source_test.go b/lib/gitlab/token_source_test.go index e869f5efdaeea..11079a22b7b2f 100644 --- a/lib/gitlab/token_source_test.go +++ b/lib/gitlab/token_source_test.go @@ -67,7 +67,7 @@ func TestIDTokenSource_GetIDToken(t *testing.T) { tok, err := its.GetIDToken() require.Error(t, err) require.True(t, trace.IsBadParameter(err)) - require.Equal(t, "", tok) + require.Empty(t, tok) }) t.Run("overridden env value present", func(t *testing.T) { diff --git a/lib/integrations/awsoidc/clientsv1_test.go b/lib/integrations/awsoidc/clientsv1_test.go index 66a350ebe67a6..5518ab28e5b23 100644 --- a/lib/integrations/awsoidc/clientsv1_test.go +++ b/lib/integrations/awsoidc/clientsv1_test.go @@ -99,7 +99,7 @@ func TestNewSessionV1(t *testing.T) { integration: "myawsintegration", expectedErr: require.NoError, sessionValidator: func(t *testing.T, s *session.Session) { - require.Equal(t, "", aws.StringValue(s.Config.Region)) + require.Empty(t, aws.StringValue(s.Config.Region)) }, }, { diff --git a/lib/integrations/awsoidc/eks_enroll_clusters_test.go b/lib/integrations/awsoidc/eks_enroll_clusters_test.go index 46e1ac8e169b3..a84103238b8e4 100644 --- a/lib/integrations/awsoidc/eks_enroll_clusters_test.go +++ b/lib/integrations/awsoidc/eks_enroll_clusters_test.go @@ -217,11 +217,12 @@ func TestEnrollEKSClusters(t *testing.T) { responseCheck: func(t *testing.T, response *EnrollEKSClusterResponse) { require.Len(t, response.Results, 2) for _, result := range response.Results { - if result.ClusterName == "EKS1" { + switch result.ClusterName { + case "EKS1": require.NoError(t, result.Error, "cluster not found") - } else if result.ClusterName == "EKS3" { + case "EKS3": require.ErrorContains(t, result.Error, "cluster not found") - } else { + default: require.Fail(t, "unexpected cluster present in the response") } } diff --git a/lib/integrations/awsoidc/listdatabases.go b/lib/integrations/awsoidc/listdatabases.go index 8298ec7aef609..66fe5c4134088 100644 --- a/lib/integrations/awsoidc/listdatabases.go +++ b/lib/integrations/awsoidc/listdatabases.go @@ -70,7 +70,7 @@ func (req *ListDatabasesRequest) CheckAndSetDefaults() error { return trace.BadParameter("region is required") } - if !(req.RDSType == rdsTypeCluster || req.RDSType == rdsTypeInstance) { + if req.RDSType != rdsTypeCluster && req.RDSType != rdsTypeInstance { return trace.BadParameter("invalid rds type, supported values: instance, cluster") } diff --git a/lib/inventory/controller.go b/lib/inventory/controller.go index db95df7ad9e44..d514015744962 100644 --- a/lib/inventory/controller.go +++ b/lib/inventory/controller.go @@ -947,7 +947,7 @@ func (c *Controller) handleKubernetesServerHB(handle *upstreamHandle, kubernetes // the auth layer verifies that a stream's hello message matches the identity and capabilities of the // client cert. after that point it is our responsibility to ensure that heartbeated information is // consistent with the identity and capabilities claimed in the initial hello. - if !(handle.HasService(types.RoleKube) || handle.HasService(types.RoleProxy)) { + if !handle.HasService(types.RoleKube) && !handle.HasService(types.RoleProxy) { return trace.AccessDenied("control stream not configured to support kubernetes server heartbeats") } if kubernetesServer.GetHostID() != handle.Hello().ServerID { diff --git a/lib/kube/grpc/websocket_client_test.go b/lib/kube/grpc/websocket_client_test.go index e4dbeb4cbeb63..444de6a9eab85 100644 --- a/lib/kube/grpc/websocket_client_test.go +++ b/lib/kube/grpc/websocket_client_test.go @@ -342,7 +342,7 @@ func (e *wsStreamClient) stream(conn *gwebsocket.Conn, options clientremotecomma } e.mu.Lock() // the stdout and stderr streams receive the last stdin input and we must trim it. - s := strings.Replace(string(buf[1:]), e.cacheBuff.String(), "", -1) + s := strings.ReplaceAll(string(buf[1:]), e.cacheBuff.String(), "") e.mu.Unlock() _, err = w.Write([]byte(s)) if err != nil { diff --git a/lib/kube/proxy/websocket_client_test.go b/lib/kube/proxy/websocket_client_test.go index c37a2658c2799..a593abdbbbb65 100644 --- a/lib/kube/proxy/websocket_client_test.go +++ b/lib/kube/proxy/websocket_client_test.go @@ -336,7 +336,7 @@ func (e *wsStreamClient) stream(conn *gwebsocket.Conn, options clientremotecomma } e.mu.Lock() // the stdout and stderr streams receive the last stdin input and we must trim it. - s := strings.Replace(string(buf[1:]), e.cacheBuff.String(), "", -1) + s := strings.ReplaceAll(string(buf[1:]), e.cacheBuff.String(), "") e.mu.Unlock() _, err = w.Write([]byte(s)) if err != nil { diff --git a/lib/limiter/internal/ratelimit/tokenbucket.go b/lib/limiter/internal/ratelimit/tokenbucket.go index 8a3395e90854a..f6d5e931ab18b 100644 --- a/lib/limiter/internal/ratelimit/tokenbucket.go +++ b/lib/limiter/internal/ratelimit/tokenbucket.go @@ -144,7 +144,7 @@ func (tb *tokenBucket) consume(tokens int64) (time.Duration, error) { tb.updateAvailableTokens() tb.lastConsumed = 0 if tokens > tb.burst { - return UndefinedDelay, fmt.Errorf("Requested tokens larger than max tokens") + return UndefinedDelay, fmt.Errorf("requested tokens larger than max tokens") } if tb.availableTokens < tokens { return tb.timeUntilAvailable(tokens), nil diff --git a/lib/multiplexer/multiplexer_test.go b/lib/multiplexer/multiplexer_test.go index 4843b56bc5a10..e91a115b401ad 100644 --- a/lib/multiplexer/multiplexer_test.go +++ b/lib/multiplexer/multiplexer_test.go @@ -1179,7 +1179,7 @@ func TestProtocolString(t *testing.T) { got := Protocol(i).String() switch i { case -1, len(protocolStrings) + 1: - require.Equal(t, "", got) + require.Empty(t, got) default: require.Equal(t, protocolStrings[Protocol(i)], got) } diff --git a/lib/proxy/peer/client_test.go b/lib/proxy/peer/client_test.go index 03e472b4078db..6ed0abb156fb7 100644 --- a/lib/proxy/peer/client_test.go +++ b/lib/proxy/peer/client_test.go @@ -28,7 +28,6 @@ import ( "google.golang.org/grpc/connectivity" "github.com/gravitational/teleport/api/client/proto" - clientapi "github.com/gravitational/teleport/api/client/proto" "github.com/gravitational/teleport/api/types" "github.com/gravitational/teleport/lib/proxy/peer/internal" "github.com/gravitational/teleport/lib/utils" @@ -157,7 +156,7 @@ func TestCAChange(t *testing.T) { require.IsType(t, (*grpcClientConn)(nil), conn) ctx, cancel := context.WithCancel(context.Background()) defer cancel() - stream, err := clientapi.NewProxyServiceClient(conn.(*grpcClientConn).cc).DialNode(ctx) + stream, err := proto.NewProxyServiceClient(conn.(*grpcClientConn).cc).DialNode(ctx) require.NoError(t, err) require.NotNil(t, stream) @@ -179,7 +178,7 @@ func TestCAChange(t *testing.T) { require.NoError(t, err) require.NotNil(t, conn) require.IsType(t, (*grpcClientConn)(nil), conn) - stream, err = clientapi.NewProxyServiceClient(conn.(*grpcClientConn).cc).DialNode(ctx) + stream, err = proto.NewProxyServiceClient(conn.(*grpcClientConn).cc).DialNode(ctx) require.Error(t, err) require.Nil(t, stream) @@ -197,7 +196,7 @@ func TestCAChange(t *testing.T) { require.NoError(t, err) require.NotNil(t, conn) require.IsType(t, (*grpcClientConn)(nil), conn) - stream, err = clientapi.NewProxyServiceClient(conn.(*grpcClientConn).cc).DialNode(ctx) + stream, err = proto.NewProxyServiceClient(conn.(*grpcClientConn).cc).DialNode(ctx) require.NoError(t, err) require.NotNil(t, stream) } diff --git a/lib/proxy/peer/quic/quic.go b/lib/proxy/peer/quic/quic.go index 26b5ab8bf2394..05f2ef582fd46 100644 --- a/lib/proxy/peer/quic/quic.go +++ b/lib/proxy/peer/quic/quic.go @@ -168,7 +168,7 @@ const ( // marshalSized returns the wire encoding of the given [proto.Message] prefixed // by its length encoded as a little endian 32-bit integer. func marshalSized(m proto.Message) ([]byte, error) { - var size int = proto.MarshalOptions{}.Size(m) + size := proto.MarshalOptions{}.Size(m) // we're going to allocate 4+size, so size can't exceed MaxInt-4 // (overflowing would be confusing at best, a runtime panic at worst) if size > math.MaxInt-4 { diff --git a/lib/resumption/managedconn.go b/lib/resumption/managedconn.go index a37380759c7f0..a8efee0a287f7 100644 --- a/lib/resumption/managedconn.go +++ b/lib/resumption/managedconn.go @@ -406,10 +406,7 @@ type deadline struct { // its data with cond.L, which is assumed to be held by the caller. func (d *deadline) setDeadlineLocked(t time.Time, cond *sync.Cond, clock clockwork.Clock) { if d.timer != nil { - for { - if d.stopped { - break - } + for !d.stopped { if d.timer.Stop() { d.stopped = true break diff --git a/lib/reversetunnel/agentpool.go b/lib/reversetunnel/agentpool.go index 25a59cc1cdebe..72531d3651660 100644 --- a/lib/reversetunnel/agentpool.go +++ b/lib/reversetunnel/agentpool.go @@ -38,7 +38,6 @@ import ( "github.com/gravitational/teleport/api/client" "github.com/gravitational/teleport/api/client/webclient" "github.com/gravitational/teleport/api/defaults" - apidefaults "github.com/gravitational/teleport/api/defaults" "github.com/gravitational/teleport/api/types" "github.com/gravitational/teleport/api/utils/retryutils" "github.com/gravitational/teleport/api/utils/sshutils" @@ -564,7 +563,7 @@ func (p *AgentPool) handleLocalTransport(ctx context.Context, channel ssh.Channe case <-ctx.Done(): go ssh.DiscardRequests(reqC) return - case <-time.After(apidefaults.DefaultIOTimeout): + case <-time.After(defaults.DefaultIOTimeout): go ssh.DiscardRequests(reqC) p.log.Warn("Timed out waiting for transport dial request.") return diff --git a/lib/reversetunnel/localsite.go b/lib/reversetunnel/localsite.go index 6482e09ff33ec..9ac5f9a1994a5 100644 --- a/lib/reversetunnel/localsite.go +++ b/lib/reversetunnel/localsite.go @@ -281,11 +281,11 @@ func (s *localSite) Dial(params reversetunnelclient.DialParams) (net.Conn, error } func shouldSendSignedPROXYHeader(signer multiplexer.PROXYHeaderSigner, useTunnel, isAgentlessNode bool, srcAddr, dstAddr net.Addr) bool { - return !(signer == nil || - useTunnel || - isAgentlessNode || - srcAddr == nil || - dstAddr == nil) + return signer != nil && + !useTunnel && + !isAgentlessNode && + srcAddr != nil && + dstAddr != nil } func (s *localSite) maybeSendSignedPROXYHeader(params reversetunnelclient.DialParams, conn net.Conn, useTunnel bool) error { diff --git a/lib/service/service.go b/lib/service/service.go index 4a9de1a38508e..7f9034f429473 100644 --- a/lib/service/service.go +++ b/lib/service/service.go @@ -3285,7 +3285,7 @@ func (process *TeleportProcess) RegisterWithAuthServer(role types.SystemRole, ev serviceName := strings.ToLower(role.String()) process.RegisterCriticalFunc(fmt.Sprintf("register.%v", serviceName), func() error { - if role.IsLocalService() && !(process.instanceRoleExpected(role) || process.hostedPluginRoleExpected(role)) { + if role.IsLocalService() && !process.instanceRoleExpected(role) && !process.hostedPluginRoleExpected(role) { // if you hit this error, your probably forgot to call SetExpectedInstanceRole inside of // the registerExpectedServices function, or forgot to call SetExpectedHostedPluginRole during // the hosted plugin init process. diff --git a/lib/services/local/crown_jewels_test.go b/lib/services/local/crown_jewels_test.go index 8474b8847bd55..144f399d14754 100644 --- a/lib/services/local/crown_jewels_test.go +++ b/lib/services/local/crown_jewels_test.go @@ -132,7 +132,7 @@ func TestGetCrownJewel(t *testing.T) { protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"), protocmp.Transform(), } - require.Equal(t, "", cmp.Diff(tt.wantObj, obj, cmpOpts...)) + require.Empty(t, cmp.Diff(tt.wantObj, obj, cmpOpts...)) }) } } @@ -238,7 +238,7 @@ func TestListCrownJewel(t *testing.T) { protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"), protocmp.Transform(), } - require.Equal(t, "", cmp.Diff(getObject(t, i), elements[i], cmpOpts...)) + require.Empty(t, cmp.Diff(getObject(t, i), elements[i], cmpOpts...)) } }) @@ -262,7 +262,7 @@ func TestListCrownJewel(t *testing.T) { protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"), protocmp.Transform(), } - require.Equal(t, "", cmp.Diff(getObject(t, i), elements[i], cmpOpts...)) + require.Empty(t, cmp.Diff(getObject(t, i), elements[i], cmpOpts...)) } }) }) diff --git a/lib/services/local/databaseobject_test.go b/lib/services/local/databaseobject_test.go index 01805ffe476c7..448f12579e7ba 100644 --- a/lib/services/local/databaseobject_test.go +++ b/lib/services/local/databaseobject_test.go @@ -145,7 +145,7 @@ func TestGetDatabaseObject(t *testing.T) { protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"), protocmp.Transform(), } - require.Equal(t, "", cmp.Diff(tt.wantObj, obj, cmpOpts...)) + require.Empty(t, cmp.Diff(tt.wantObj, obj, cmpOpts...)) }) } } @@ -231,7 +231,7 @@ func TestListDatabaseObjects(t *testing.T) { protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"), protocmp.Transform(), } - require.Equal(t, "", cmp.Diff(getObject(t, i), elements[i], cmpOpts...)) + require.Empty(t, cmp.Diff(getObject(t, i), elements[i], cmpOpts...)) } }) @@ -255,7 +255,7 @@ func TestListDatabaseObjects(t *testing.T) { protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"), protocmp.Transform(), } - require.Equal(t, "", cmp.Diff(getObject(t, i), elements[i], cmpOpts...)) + require.Empty(t, cmp.Diff(getObject(t, i), elements[i], cmpOpts...)) } }) }) diff --git a/lib/services/local/databaseobjectimportrule_test.go b/lib/services/local/databaseobjectimportrule_test.go index d522329275803..6a0502d8f1314 100644 --- a/lib/services/local/databaseobjectimportrule_test.go +++ b/lib/services/local/databaseobjectimportrule_test.go @@ -34,7 +34,6 @@ import ( headerv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/header/v1" "github.com/gravitational/teleport/api/types" "github.com/gravitational/teleport/api/types/label" - apilabels "github.com/gravitational/teleport/api/types/label" "github.com/gravitational/teleport/lib/backend/memory" "github.com/gravitational/teleport/lib/services" "github.com/gravitational/teleport/lib/srv/db/common/databaseobjectimportrule" @@ -163,7 +162,7 @@ func TestDatabaseObjectImportRuleCRUD(t *testing.T) { // Delete all import rules. lst, nextToken, err := service.ListDatabaseObjectImportRules(ctx, 200, "") require.NoError(t, err) - require.Equal(t, "", nextToken) + require.Empty(t, nextToken) for _, rule := range lst { err = service.DeleteDatabaseObjectImportRule(ctx, rule.GetMetadata().GetName()) require.NoError(t, err) @@ -177,7 +176,7 @@ func TestDatabaseObjectImportRuleCRUD(t *testing.T) { func TestMarshalDatabaseObjectImportRuleRoundTrip(t *testing.T) { spec := &databaseobjectimportrulev1.DatabaseObjectImportRuleSpec{ Priority: 30, - DatabaseLabels: apilabels.FromMap(map[string][]string{"env": {"staging", "prod"}, "owner_org": {"trading"}}), + DatabaseLabels: label.FromMap(map[string][]string{"env": {"staging", "prod"}, "owner_org": {"trading"}}), Mappings: []*databaseobjectimportrulev1.DatabaseObjectImportRuleMapping{ { Scope: &databaseobjectimportrulev1.DatabaseObjectImportScope{ diff --git a/lib/services/local/generic/generic_test.go b/lib/services/local/generic/generic_test.go index 5b540aee69fbe..d28959a0de17c 100644 --- a/lib/services/local/generic/generic_test.go +++ b/lib/services/local/generic/generic_test.go @@ -452,7 +452,7 @@ func TestGenericListResourcesWithFilter(t *testing.T) { require.Empty(t, cmp.Diff([]*testResource{r1}, page, cmpopts.IgnoreFields(types.Metadata{}, "Revision"), )) - require.Equal(t, "", nextKey) + require.Empty(t, nextKey) page, nextKey, err = service.ListResourcesWithFilter(ctx, 1, "", func(r *testResource) bool { return r.Metadata.Name == "r2" @@ -461,7 +461,7 @@ func TestGenericListResourcesWithFilter(t *testing.T) { require.Empty(t, cmp.Diff([]*testResource{r2}, page, cmpopts.IgnoreFields(types.Metadata{}, "Revision"), )) - require.Equal(t, "", nextKey) + require.Empty(t, nextKey) } func TestGenericListResourcesWithFilterForScale(t *testing.T) { diff --git a/lib/services/local/statichostuser_test.go b/lib/services/local/statichostuser_test.go index d4eb610973cee..2a2b2e0cc0df3 100644 --- a/lib/services/local/statichostuser_test.go +++ b/lib/services/local/statichostuser_test.go @@ -116,7 +116,7 @@ func TestGetStaticHostUser(t *testing.T) { protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"), protocmp.Transform(), } - require.Equal(t, "", cmp.Diff(tc.wantObj, obj, cmpOpts...)) + require.Empty(t, cmp.Diff(tc.wantObj, obj, cmpOpts...)) } }) } @@ -219,7 +219,7 @@ func TestListStaticHostUsers(t *testing.T) { protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"), protocmp.Transform(), } - require.Equal(t, "", cmp.Diff(getStaticHostUser(i), elements[i], cmpOpts...)) + require.Empty(t, cmp.Diff(getStaticHostUser(i), elements[i], cmpOpts...)) } }) @@ -243,7 +243,7 @@ func TestListStaticHostUsers(t *testing.T) { protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"), protocmp.Transform(), } - require.Equal(t, "", cmp.Diff(getStaticHostUser(i), elements[i], cmpOpts...)) + require.Empty(t, cmp.Diff(getStaticHostUser(i), elements[i], cmpOpts...)) } }) }) diff --git a/lib/services/local/unstable_test.go b/lib/services/local/unstable_test.go index 5e647b8f484e7..97b8b8e434627 100644 --- a/lib/services/local/unstable_test.go +++ b/lib/services/local/unstable_test.go @@ -72,7 +72,7 @@ func TestSystemRoleAssertions(t *testing.T) { assertions, err := unstable.GetSystemRoleAssertions(ctx, serverID, assertionID) require.NoError(t, err) - require.Equal(t, len(expect), len(assertions.SystemRoles)) + require.Len(t, expect, len(assertions.SystemRoles)) require.Subset(t, expect, assertions.SystemRoles) } } diff --git a/lib/services/local/user_task_test.go b/lib/services/local/user_task_test.go index 46a26160bae7c..03b9372071d5f 100644 --- a/lib/services/local/user_task_test.go +++ b/lib/services/local/user_task_test.go @@ -116,7 +116,7 @@ func TestGetUserTask(t *testing.T) { protocmp.IgnoreFields(&headerv1.Metadata{}, "revision"), protocmp.Transform(), } - require.Equal(t, "", cmp.Diff(tt.wantObj, obj, cmpOpts...)) + require.Empty(t, cmp.Diff(tt.wantObj, obj, cmpOpts...)) }) } } @@ -231,7 +231,7 @@ func TestListUserTask(t *testing.T) { require.Len(t, elements, count) slices.SortFunc(elements, sortUserTasksFn) - require.Equal(t, "", cmp.Diff(expectedElements, elements, cmpOpts...)) + require.Empty(t, cmp.Diff(expectedElements, elements, cmpOpts...)) }) t.Run("paginated", func(t *testing.T) { @@ -251,7 +251,7 @@ func TestListUserTask(t *testing.T) { require.Len(t, expectedElements, len(elements)) slices.SortFunc(elements, sortUserTasksFn) - require.Equal(t, "", cmp.Diff(expectedElements, elements, cmpOpts...)) + require.Empty(t, cmp.Diff(expectedElements, elements, cmpOpts...)) }) }) } diff --git a/lib/services/oidc_test.go b/lib/services/oidc_test.go index 86be24382cfcf..1fd5454ef8b65 100644 --- a/lib/services/oidc_test.go +++ b/lib/services/oidc_test.go @@ -159,7 +159,7 @@ func TestOIDCCheckAndSetDefaults(t *testing.T) { }, expect: func(t *testing.T, c types.OIDCConnector, err error) { require.NoError(t, err) - require.Equal(t, "", c.GetPrompt()) + require.Empty(t, c.GetPrompt()) }, }, { desc: "invalid claims to roles", diff --git a/lib/services/parser.go b/lib/services/parser.go index 694a7faa5bff0..55ad8c7ab43d0 100644 --- a/lib/services/parser.go +++ b/lib/services/parser.go @@ -271,7 +271,7 @@ func (l *LogAction) Log(level, format string, args ...interface{}) predicate.Boo } else { writer = log.StandardLogger().WriterLevel(ilevel) } - writer.Write([]byte(fmt.Sprintf(format, args...))) + fmt.Fprintf(writer, format, args...) return true } } diff --git a/lib/services/statichostuser.go b/lib/services/statichostuser.go index 599cb2cd83cbf..b3a21c7bb8cde 100644 --- a/lib/services/statichostuser.go +++ b/lib/services/statichostuser.go @@ -70,7 +70,7 @@ func ValidateStaticHostUser(u *userprovisioningpb.StaticHostUser) error { return trace.BadParameter("either NodeLabels or NodeLabelsExpression must be set") } for _, label := range matcher.NodeLabels { - if label.Name == types.Wildcard && !(len(label.Values) == 1 && label.Values[0] == types.Wildcard) { + if label.Name == types.Wildcard && (len(label.Values) != 1 || label.Values[0] != types.Wildcard) { return trace.BadParameter("selector *: is not supported") } } diff --git a/lib/services/suite/suite.go b/lib/services/suite/suite.go index 5321fc5143dfc..e7fedad6b77a8 100644 --- a/lib/services/suite/suite.go +++ b/lib/services/suite/suite.go @@ -220,7 +220,7 @@ func (s *ServicesTestSuite) Users() services.UsersService { } func userSlicesEqual(t *testing.T, a []types.User, b []types.User) { - require.EqualValuesf(t, len(a), len(b), "a: %#v b: %#v", a, b) + require.Lenf(t, a, len(b), "a: %#v b: %#v", a, b) sort.Sort(services.Users(a)) sort.Sort(services.Users(b)) diff --git a/lib/spacelift/token_source_test.go b/lib/spacelift/token_source_test.go index 8ae1589459af3..281d9dc151946 100644 --- a/lib/spacelift/token_source_test.go +++ b/lib/spacelift/token_source_test.go @@ -49,6 +49,6 @@ func TestIDTokenSource_GetIDToken(t *testing.T) { tok, err := its.GetIDToken() require.Error(t, err) require.True(t, trace.IsBadParameter(err)) - require.Equal(t, "", tok) + require.Empty(t, tok) }) } diff --git a/lib/srv/alpnproxy/local_proxy.go b/lib/srv/alpnproxy/local_proxy.go index 481e0b0813a6d..8af4895502916 100644 --- a/lib/srv/alpnproxy/local_proxy.go +++ b/lib/srv/alpnproxy/local_proxy.go @@ -321,8 +321,8 @@ func (l *LocalProxy) makeHTTPReverseProxy(certs ...tls.Certificate) *httputil.Re errHeader := response.Header.Get(commonApp.TeleportAPIErrorHeader) if errHeader != "" { // TODO: find a cleaner way of formatting the error. - errHeader = strings.Replace(errHeader, " \t", "\n\t", -1) - errHeader = strings.Replace(errHeader, " User Message:", "\n\n\tUser Message:", -1) + errHeader = strings.ReplaceAll(errHeader, " \t", "\n\t") + errHeader = strings.ReplaceAll(errHeader, " User Message:", "\n\n\tUser Message:") l.cfg.Log.Warn(errHeader) } for _, infoHeader := range response.Header.Values(commonApp.TeleportAPIInfoHeader) { diff --git a/lib/srv/app/cloud_test.go b/lib/srv/app/cloud_test.go index 5911b18fe0639..11ff7da2a678e 100644 --- a/lib/srv/app/cloud_test.go +++ b/lib/srv/app/cloud_test.go @@ -240,7 +240,7 @@ func TestCloudGetAWSSigninToken(t *testing.T) { values := r.URL.Query() require.Equal(t, "getSigninToken", values.Get("Action")) require.Equal(t, `{"sessionId":"keyid","sessionKey":"accesskey","sessionToken":"sessiontoken"}`, values.Get("Session")) - require.Equal(t, "", values.Get("SessionDuration")) + require.Empty(t, values.Get("SessionDuration")) w.Write([]byte(`{"SigninToken":"generated-token"}`)) }), expectedToken: "generated-token", diff --git a/lib/srv/ctx.go b/lib/srv/ctx.go index c640aa9bdd014..8ce45574e94bd 100644 --- a/lib/srv/ctx.go +++ b/lib/srv/ctx.go @@ -1142,7 +1142,7 @@ func closeAll(closers ...io.Closer) error { } func newUaccMetadata(c *ServerContext) (*UaccMetadata, error) { - addr := c.ConnectionContext.ServerConn.Conn.RemoteAddr() + addr := c.ConnectionContext.ServerConn.RemoteAddr() hostname, _, err := net.SplitHostPort(addr.String()) if err != nil { return nil, trace.Wrap(err) diff --git a/lib/srv/db/cassandra/protocol/conn.go b/lib/srv/db/cassandra/protocol/conn.go index 33b09e6a848ca..4e161aba80089 100644 --- a/lib/srv/db/cassandra/protocol/conn.go +++ b/lib/srv/db/cassandra/protocol/conn.go @@ -239,7 +239,7 @@ func (c *Conn) writeSegment(outgoing *frame.Frame, wr io.Writer) error { // maybeSwitchToModernLayout is used to switch to modern framing layout. // If received frame is a Ready frame or Authenticate frame, it will switch to modern framing layout. func (c *Conn) maybeSwitchToModernLayout(fr *frame.Frame) { - if !(isReady(fr) || isAuthenticate(fr)) { + if !isReady(fr) && !isAuthenticate(fr) { return } if !c.modernLayoutRead { diff --git a/lib/srv/db/elasticsearch/fuzz_test.go b/lib/srv/db/elasticsearch/fuzz_test.go index da1a3c512f658..cc651703c5a2f 100644 --- a/lib/srv/db/elasticsearch/fuzz_test.go +++ b/lib/srv/db/elasticsearch/fuzz_test.go @@ -19,11 +19,12 @@ package elasticsearch import ( - "io" "log/slog" "testing" "github.com/stretchr/testify/require" + + logutils "github.com/gravitational/teleport/lib/utils/log" ) func FuzzGetQueryFromRequestBody(f *testing.F) { @@ -41,7 +42,7 @@ func FuzzGetQueryFromRequestBody(f *testing.F) { mkEngine := func() *Engine { e := &Engine{} - e.Log = slog.New(slog.NewTextHandler(io.Discard, nil)) + e.Log = slog.New(logutils.DiscardHandler{}) return e } diff --git a/lib/srv/db/sqlserver/protocol/protocol_test.go b/lib/srv/db/sqlserver/protocol/protocol_test.go index 829b2ca30e121..a774c118c344d 100644 --- a/lib/srv/db/sqlserver/protocol/protocol_test.go +++ b/lib/srv/db/sqlserver/protocol/protocol_test.go @@ -51,7 +51,7 @@ func TestReadLogin7(t *testing.T) { packet, err := ReadLogin7Packet(bytes.NewBuffer(fixtures.Login7)) require.NoError(t, err) require.Equal(t, "sa", packet.Username()) - require.Equal(t, "", packet.Database()) + require.Empty(t, packet.Database()) } // TestErrorResponse verifies writing error response. diff --git a/lib/srv/db/watcher_test.go b/lib/srv/db/watcher_test.go index cef21ea90ff2f..2a7d0bdb27e60 100644 --- a/lib/srv/db/watcher_test.go +++ b/lib/srv/db/watcher_test.go @@ -384,7 +384,7 @@ func assertReconciledResource(t *testing.T, ch chan types.Databases, databases t select { case d := <-ch: sort.Sort(d) - require.Equal(t, len(databases), len(d)) + require.Len(t, databases, len(d)) require.Empty(t, cmp.Diff(databases, d, cmpopts.IgnoreFields(types.Metadata{}, "Revision"), cmpopts.IgnoreFields(types.DatabaseStatusV3{}, "CACert"), diff --git a/lib/srv/discovery/fetchers/kube_services_test.go b/lib/srv/discovery/fetchers/kube_services_test.go index 4502c0ab0b6ff..5ad789066d8c9 100644 --- a/lib/srv/discovery/fetchers/kube_services_test.go +++ b/lib/srv/discovery/fetchers/kube_services_test.go @@ -298,7 +298,7 @@ func TestKubeAppFetcher_Get(t *testing.T) { result, err := fetcher.Get(context.Background()) require.NoError(t, err) - require.Equal(t, len(tt.expected), len(result)) + require.Len(t, tt.expected, len(result)) slices.SortFunc(result, func(a, b types.ResourceWithLabels) int { return strings.Compare(a.GetName(), b.GetName()) }) diff --git a/lib/srv/exec_test.go b/lib/srv/exec_test.go index fffa01dd0891b..2146f57975fa1 100644 --- a/lib/srv/exec_test.go +++ b/lib/srv/exec_test.go @@ -123,7 +123,7 @@ func TestEmitExecAuditEvent(t *testing.T) { require.Equal(t, "xxx", execEvent.SessionID) require.Equal(t, "10.0.0.5:4817", execEvent.RemoteAddr) require.Equal(t, "127.0.0.1:3022", execEvent.LocalAddr) - require.NotZero(t, events.EventID) + require.NotEmpty(t, events.EventID) } } diff --git a/lib/srv/regular/sshserver.go b/lib/srv/regular/sshserver.go index ddbe0eb638c32..27aa6dd0d3874 100644 --- a/lib/srv/regular/sshserver.go +++ b/lib/srv/regular/sshserver.go @@ -2396,11 +2396,11 @@ func (s *Server) parseSubsystemRequest(req *ssh.Request, ctx *srv.ServerContext) } } - switch { + switch r.Name { // DELETE IN 15.0.0 (deprecated, tsh will not be using this anymore) - case r.Name == teleport.GetHomeDirSubsystem: + case teleport.GetHomeDirSubsystem: return newHomeDirSubsys(), nil - case r.Name == teleport.SFTPSubsystem: + case teleport.SFTPSubsystem: err := ctx.CheckSFTPAllowed(s.reg) if err != nil { s.emitAuditEventWithLog(context.Background(), &apievents.SFTP{ diff --git a/lib/srv/regular/sshserver_test.go b/lib/srv/regular/sshserver_test.go index 3071625b686b0..fb4c5decda02c 100644 --- a/lib/srv/regular/sshserver_test.go +++ b/lib/srv/regular/sshserver_test.go @@ -1410,7 +1410,7 @@ func x11EchoSession(ctx context.Context, t *testing.T, clt *tracessh.Client) x11 display := make(chan string, 1) require.EventuallyWithT(t, func(t *assert.CollectT) { // enter 'printenv DISPLAY > /path/to/tmp/file' into the session (dumping the value of DISPLAY into the temp file) - _, err = keyboard.Write([]byte(fmt.Sprintf("printenv %v > %s\n\r", x11.DisplayEnv, tmpFile.Name()))) + _, err = fmt.Fprintf(keyboard, "printenv %v > %s\n\r", x11.DisplayEnv, tmpFile.Name()) assert.NoError(t, err) assert.Eventually(t, func() bool { @@ -3051,7 +3051,7 @@ func TestTargetMetadata(t *testing.T) { metadata := sshSrv.TargetMetadata() require.Equal(t, nodeID, metadata.ServerID) require.Equal(t, apidefaults.Namespace, metadata.ServerNamespace) - require.Equal(t, "", metadata.ServerAddr) + require.Empty(t, metadata.ServerAddr) require.Equal(t, "localhost", metadata.ServerHostname) require.Contains(t, metadata.ServerLabels, "foo") diff --git a/lib/srv/sess.go b/lib/srv/sess.go index 4a8ed1dbae2e2..357095d61385e 100644 --- a/lib/srv/sess.go +++ b/lib/srv/sess.go @@ -349,7 +349,7 @@ func (s *SessionRegistry) UpsertHostUser(identityContext IdentityContext, obtain if err != nil { log.DebugContext(ctx, "Error creating user", "error", err) - if errors.Is(err, unmanagedUserErr) { + if errors.Is(err, errUnmanagedUser) { log.WarnContext(ctx, "User is not managed by teleport. Either manually delete the user from this machine or update the host_groups defined in their role to include 'teleport-keep'. https://goteleport.com/docs/enroll-resources/server-access/guides/host-user-creation/#migrating-unmanaged-users") return false, nil, nil } @@ -1861,14 +1861,8 @@ func (s *session) expandFileTransferRequestPath(p string) (string, error) { expanded := filepath.Clean(p) dir := filepath.Dir(expanded) - var tildePrefixed bool - var noBaseDir bool - if dir == "~" { - tildePrefixed = true - } else if dir == "." { - noBaseDir = true - } - + tildePrefixed := dir == "~" + noBaseDir := dir == "." if tildePrefixed || noBaseDir { localUser, err := user.Lookup(s.login) if err != nil { diff --git a/lib/srv/statichostusers.go b/lib/srv/statichostusers.go index ec39cfb44064e..a9f22afe0baf7 100644 --- a/lib/srv/statichostusers.go +++ b/lib/srv/statichostusers.go @@ -26,7 +26,7 @@ import ( "github.com/gravitational/trace" "github.com/jonboulle/clockwork" - userprovisioningpb "github.com/gravitational/teleport/api/gen/proto/go/teleport/userprovisioning/v2" + userprovisioningv2 "github.com/gravitational/teleport/api/gen/proto/go/teleport/userprovisioning/v2" "github.com/gravitational/teleport/api/types" "github.com/gravitational/teleport/api/types/label" apiutils "github.com/gravitational/teleport/api/utils" @@ -189,7 +189,7 @@ func (s *StaticHostUserHandler) run(ctx context.Context) error { slog.WarnContext(ctx, "Unexpected resource type.", "resource", event.Resource) continue } - hostUser, ok := r.Unwrap().(*userprovisioningpb.StaticHostUser) + hostUser, ok := r.Unwrap().(*userprovisioningv2.StaticHostUser) if !ok { slog.WarnContext(ctx, "Unexpected resource type.", "resource", event.Resource) continue @@ -210,8 +210,8 @@ func (s *StaticHostUserHandler) run(ctx context.Context) error { } } -func (s *StaticHostUserHandler) handleNewHostUser(ctx context.Context, hostUser *userprovisioningpb.StaticHostUser) error { - var createUser *userprovisioningpb.Matcher +func (s *StaticHostUserHandler) handleNewHostUser(ctx context.Context, hostUser *userprovisioningv2.StaticHostUser) error { + var createUser *userprovisioningv2.Matcher login := hostUser.GetMetadata().Name server := s.server.GetInfo() for _, matcher := range hostUser.Spec.Matchers { diff --git a/lib/srv/usermgmt.go b/lib/srv/usermgmt.go index 8714665f76929..b15ba51b248f9 100644 --- a/lib/srv/usermgmt.go +++ b/lib/srv/usermgmt.go @@ -269,11 +269,11 @@ func (u *HostSudoersManagement) RemoveSudoers(name string) error { return nil } -// unmanagedUserErr is returned when attempting to modify or interact with a user that is not managed by Teleport. -var unmanagedUserErr = errors.New("user not managed by teleport") +// errUnmanagedUser is returned when attempting to modify or interact with a user that is not managed by Teleport. +var errUnmanagedUser = errors.New("user not managed by teleport") -// staticConversionErr is returned when attempting to convert a managed host user to or from a static host user -var staticConversionErr = errors.New("managed host users can not be converted to or from a static host user") +// errStaticConversion is returned when attempting to convert a managed host user to or from a static host user +var errStaticConversion = errors.New("managed host users can not be converted to or from a static host user") func (u *HostUserManagement) updateUser(hostUser HostUser, ui services.HostUsersInfo) error { ctx := u.ctx @@ -436,13 +436,13 @@ func (u *HostUserManagement) UpsertUser(name string, ui services.HostUsersInfo) log.DebugContext(u.ctx, "Resolving groups for user") groups, err := ResolveGroups(log, hostUser, ui) if err != nil { - if errors.Is(err, staticConversionErr) { + if errors.Is(err, errStaticConversion) { log.DebugContext(u.ctx, "Aborting host user creation, can't convert between auto-provisioned and static host users.", "login", name) } - if errors.Is(err, unmanagedUserErr) { + if errors.Is(err, errUnmanagedUser) { log.DebugContext(u.ctx, "Aborting host user creation, can't update unmanaged user unless explicitly migrating.", "login", name) } @@ -736,11 +736,11 @@ func ResolveGroups(logger *slog.Logger, hostUser *HostUser, ui services.HostUser inStaticMode := ui.Mode == services.HostUserModeStatic if (inStaticMode && managedUser) || (!inStaticMode && staticUser) { - return nil, trace.Wrap(staticConversionErr) + return nil, trace.Wrap(errStaticConversion) } - if !(managedUser || staticUser || migrateStaticUser || migrateKeepUser) { - return nil, trace.Wrap(unmanagedUserErr) + if !managedUser && !staticUser && !migrateStaticUser && !migrateKeepUser { + return nil, trace.Wrap(errUnmanagedUser) } groups[teleportGroup] = struct{}{} diff --git a/lib/srv/usermgmt_test.go b/lib/srv/usermgmt_test.go index f88f48fe93cf1..988f1335d149e 100644 --- a/lib/srv/usermgmt_test.go +++ b/lib/srv/usermgmt_test.go @@ -249,7 +249,7 @@ func TestUserMgmt_CreateTemporaryUser(t *testing.T) { // an existing, unmanaged user should not be changed closer, err = users.UpsertUser("simon", userinfo) - require.ErrorIs(t, err, unmanagedUserErr) + require.ErrorIs(t, err, errUnmanagedUser) require.Equal(t, nil, closer) } @@ -298,12 +298,12 @@ func TestUserMgmtSudoers_CreateTemporaryUser(t *testing.T) { _, err := users.UpsertUser("testuser", services.HostUsersInfo{ Mode: services.HostUserModeDrop, }) - require.ErrorIs(t, err, unmanagedUserErr) + require.ErrorIs(t, err, errUnmanagedUser) backend.CreateGroup(types.TeleportDropGroup, "") _, err = users.UpsertUser("testuser", services.HostUsersInfo{ Mode: services.HostUserModeDrop, }) - require.ErrorIs(t, err, unmanagedUserErr) + require.ErrorIs(t, err, errUnmanagedUser) }) } @@ -450,7 +450,7 @@ func Test_UpdateUserGroups_Keep(t *testing.T) { // Do not convert the managed user to static. userinfo.Mode = services.HostUserModeStatic closer, err = users.UpsertUser("alice", userinfo) - assert.ErrorIs(t, err, staticConversionErr) + assert.ErrorIs(t, err, errStaticConversion) assert.Equal(t, nil, closer) assert.Equal(t, 1, backend.setUserGroupsCalls) assert.ElementsMatch(t, append(userinfo.Groups, types.TeleportKeepGroup), backend.users["alice"]) @@ -506,7 +506,7 @@ func Test_UpdateUserGroups_Drop(t *testing.T) { // Do not convert the managed user to static. userinfo.Mode = services.HostUserModeStatic closer, err = users.UpsertUser("alice", userinfo) - assert.ErrorIs(t, err, staticConversionErr) + assert.ErrorIs(t, err, errStaticConversion) assert.Equal(t, nil, closer) assert.Equal(t, 1, backend.setUserGroupsCalls) assert.ElementsMatch(t, append(userinfo.Groups, types.TeleportDropGroup), backend.users["alice"]) @@ -558,7 +558,7 @@ func Test_UpdateUserGroups_Static(t *testing.T) { // Do not convert to KEEP. userinfo.Mode = services.HostUserModeKeep closer, err = users.UpsertUser("alice", userinfo) - assert.ErrorIs(t, err, staticConversionErr) + assert.ErrorIs(t, err, errStaticConversion) assert.Equal(t, nil, closer) assert.Equal(t, 1, backend.setUserGroupsCalls) assert.ElementsMatch(t, append(slices.Clone(allGroups[2:]), types.TeleportStaticGroup), backend.users["alice"]) @@ -566,7 +566,7 @@ func Test_UpdateUserGroups_Static(t *testing.T) { // Do not convert to INSECURE_DROP. userinfo.Mode = services.HostUserModeDrop closer, err = users.UpsertUser("alice", userinfo) - assert.ErrorIs(t, err, staticConversionErr) + assert.ErrorIs(t, err, errStaticConversion) assert.Equal(t, nil, closer) assert.Equal(t, 1, backend.setUserGroupsCalls) assert.ElementsMatch(t, append(slices.Clone(allGroups[2:]), types.TeleportStaticGroup), backend.users["alice"]) @@ -587,7 +587,7 @@ func Test_DontManageExistingUser(t *testing.T) { // Update user in DROP mode closer, err := users.UpsertUser("alice", userinfo) - assert.ErrorIs(t, err, unmanagedUserErr) + assert.ErrorIs(t, err, errUnmanagedUser) assert.Equal(t, nil, closer) assert.Zero(t, backend.setUserGroupsCalls) assert.ElementsMatch(t, allGroups, backend.users["alice"]) @@ -595,7 +595,7 @@ func Test_DontManageExistingUser(t *testing.T) { // Update user in KEEP mode userinfo.Mode = services.HostUserModeKeep closer, err = users.UpsertUser("alice", userinfo) - assert.ErrorIs(t, err, unmanagedUserErr) + assert.ErrorIs(t, err, errUnmanagedUser) assert.Equal(t, nil, closer) assert.Zero(t, backend.setUserGroupsCalls) assert.ElementsMatch(t, allGroups, backend.users["alice"]) @@ -603,7 +603,7 @@ func Test_DontManageExistingUser(t *testing.T) { // Update static user userinfo.Mode = services.HostUserModeStatic closer, err = users.UpsertUser("alice", userinfo) - assert.ErrorIs(t, err, unmanagedUserErr) + assert.ErrorIs(t, err, errUnmanagedUser) assert.Equal(t, nil, closer) assert.Zero(t, backend.setUserGroupsCalls) assert.ElementsMatch(t, allGroups, backend.users["alice"]) @@ -645,7 +645,7 @@ func Test_DontUpdateUnmanagedUsers(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { closer, err := users.UpsertUser("alice", tc.userinfo) - assert.ErrorIs(t, err, unmanagedUserErr) + assert.ErrorIs(t, err, errUnmanagedUser) assert.Equal(t, nil, closer) assert.Zero(t, backend.setUserGroupsCalls) assert.ElementsMatch(t, allGroups[2:], backend.users["alice"]) @@ -694,7 +694,7 @@ func Test_AllowExplicitlyManageExistingUsers(t *testing.T) { userinfo.Mode = services.HostUserModeDrop userinfo.TakeOwnership = false closer, err = users.UpsertUser("alice-drop", userinfo) - assert.ErrorIs(t, err, unmanagedUserErr) + assert.ErrorIs(t, err, errUnmanagedUser) assert.Equal(t, nil, closer) assert.Equal(t, 2, backend.setUserGroupsCalls) assert.Empty(t, backend.users["alice-drop"]) @@ -920,7 +920,7 @@ func TestHostUsersResolveGroups(t *testing.T) { }, expectGroups: nil, - expectErr: staticConversionErr, + expectErr: errStaticConversion, }, { name: "don't convert keep to static", @@ -938,7 +938,7 @@ func TestHostUsersResolveGroups(t *testing.T) { }, expectGroups: nil, - expectErr: staticConversionErr, + expectErr: errStaticConversion, }, { name: "don't convert static to keep", @@ -956,7 +956,7 @@ func TestHostUsersResolveGroups(t *testing.T) { }, expectGroups: nil, - expectErr: staticConversionErr, + expectErr: errStaticConversion, }, { name: "don't convert static to drop", @@ -973,7 +973,7 @@ func TestHostUsersResolveGroups(t *testing.T) { }, expectGroups: nil, - expectErr: staticConversionErr, + expectErr: errStaticConversion, }, { name: "don't update unmanaged user in drop mode", @@ -991,7 +991,7 @@ func TestHostUsersResolveGroups(t *testing.T) { }, expectGroups: nil, - expectErr: unmanagedUserErr, + expectErr: errUnmanagedUser, }, { name: "don't update unmanaged user in keep mode", @@ -1007,7 +1007,7 @@ func TestHostUsersResolveGroups(t *testing.T) { }, expectGroups: nil, - expectErr: unmanagedUserErr, + expectErr: errUnmanagedUser, }, { name: "don't update unmanaged user in static mode", @@ -1023,7 +1023,7 @@ func TestHostUsersResolveGroups(t *testing.T) { }, expectGroups: nil, - expectErr: unmanagedUserErr, + expectErr: errUnmanagedUser, }, { name: "take over unmanaged user in keep mode when migrating", diff --git a/lib/sshutils/x11/display.go b/lib/sshutils/x11/display.go index 459c8674e0628..e821eeebce4d7 100644 --- a/lib/sshutils/x11/display.go +++ b/lib/sshutils/x11/display.go @@ -180,7 +180,7 @@ func ParseDisplay(displayString string) (Display, error) { // check the display for illegal characters in case of code injection attempt allowedSpecialChars := ":/.-_" // chars used for hostname or display delimiters. for _, c := range displayString { - if !(unicode.IsLetter(c) || unicode.IsNumber(c) || strings.ContainsRune(allowedSpecialChars, c)) { + if !unicode.IsLetter(c) && !unicode.IsNumber(c) && !strings.ContainsRune(allowedSpecialChars, c) { return Display{}, trace.BadParameter("display contains invalid character %q", c) } } diff --git a/lib/tbot/botfs/fs_linux.go b/lib/tbot/botfs/fs_linux.go index fb3a0734ac566..e7d1097d3bfba 100644 --- a/lib/tbot/botfs/fs_linux.go +++ b/lib/tbot/botfs/fs_linux.go @@ -450,7 +450,7 @@ func ConfigureLegacyACL(path string, owner *user.User, opts *ACLOptions) error { // resolveACLReaderSelector attempts to convert an ACL selector into a // platform-specific acl.Entry that can be applied to a file. func resolveACLReaderSelector(s *ACLSelector, dir bool) (acl.Entry, error) { - var perm fs.FileMode = modeACLRead + perm := modeACLRead if dir { perm = modeACLReadExecute } diff --git a/lib/tbot/config/config.go b/lib/tbot/config/config.go index cbcaf994cb027..9577e1a2c4e00 100644 --- a/lib/tbot/config/config.go +++ b/lib/tbot/config/config.go @@ -635,7 +635,7 @@ func ReadConfig(reader io.ReadSeeker, manualMigration bool) (*BotConfig, error) } decoder := yaml.NewDecoder(reader) if err := decoder.Decode(&version); err != nil { - return nil, trace.BadParameter("failed parsing config file version: %s", strings.Replace(err.Error(), "\n", "", -1)) + return nil, trace.BadParameter("failed parsing config file version: %s", strings.ReplaceAll(err.Error(), "\n", "")) } // Reset reader and decoder @@ -652,7 +652,7 @@ func ReadConfig(reader io.ReadSeeker, manualMigration bool) (*BotConfig, error) } config := &configV1{} if err := decoder.Decode(config); err != nil { - return nil, trace.BadParameter("failed parsing config file: %s", strings.Replace(err.Error(), "\n", "", -1)) + return nil, trace.BadParameter("failed parsing config file: %s", strings.ReplaceAll(err.Error(), "\n", "")) } latestConfig, err := config.migrate() if err != nil { @@ -669,7 +669,7 @@ func ReadConfig(reader io.ReadSeeker, manualMigration bool) (*BotConfig, error) decoder.KnownFields(true) config := &BotConfig{} if err := decoder.Decode(config); err != nil { - return nil, trace.BadParameter("failed parsing config file: %s", strings.Replace(err.Error(), "\n", "", -1)) + return nil, trace.BadParameter("failed parsing config file: %s", strings.ReplaceAll(err.Error(), "\n", "")) } return config, nil default: diff --git a/lib/teleterm/config.go b/lib/teleterm/config.go index 3c4fa7d284fda..f1260c9d17cc6 100644 --- a/lib/teleterm/config.go +++ b/lib/teleterm/config.go @@ -72,7 +72,7 @@ func (c *Config) CheckAndSetDefaults() error { return trace.Wrap(err) } - if !(addr.Network() == "unix" || addr.Network() == "tcp") { + if addr.Network() != "unix" && addr.Network() != "tcp" { return trace.BadParameter("network address should start with unix:// or tcp:// or be empty (tcp:// is used in that case)") } diff --git a/lib/teleterm/daemon/daemon.go b/lib/teleterm/daemon/daemon.go index 8d81c4859efef..829381c43b4da 100644 --- a/lib/teleterm/daemon/daemon.go +++ b/lib/teleterm/daemon/daemon.go @@ -834,7 +834,7 @@ func (s *Service) AssumeRole(ctx context.Context, req *api.AssumeRoleRequest) er defer s.gatewaysMu.RUnlock() for _, gw := range s.gateways { targetURI := gw.TargetURI() - if !(targetURI.IsKube() && targetURI.GetRootClusterURI() == cluster.URI) { + if !targetURI.IsKube() && targetURI.GetRootClusterURI() != cluster.URI { continue } kubeGw, err := gateway.AsKube(gw) diff --git a/lib/teleterm/daemon/mfaprompt.go b/lib/teleterm/daemon/mfaprompt.go index 1b90edd7a88f0..8d7cee331642e 100644 --- a/lib/teleterm/daemon/mfaprompt.go +++ b/lib/teleterm/daemon/mfaprompt.go @@ -76,7 +76,7 @@ func (p *mfaPrompt) Run(ctx context.Context, chal *proto.MFAAuthenticateChalleng promptSSO := chal.SSOChallenge != nil && p.cfg.SSOMFACeremony != nil // No prompt to run, no-op. - if !(promptOTP || promptWebauthn || promptSSO) { + if !promptOTP && !promptWebauthn && !promptSSO { return &proto.MFAAuthenticateResponse{}, nil } diff --git a/lib/teleterm/gateway/config.go b/lib/teleterm/gateway/config.go index 978cbf58d5ae3..7a657cf4983dc 100644 --- a/lib/teleterm/gateway/config.go +++ b/lib/teleterm/gateway/config.go @@ -106,7 +106,7 @@ type OnExpiredCertFunc func(context.Context, Gateway) (tls.Certificate, error) // CheckAndSetDefaults checks and sets the defaults func (c *Config) CheckAndSetDefaults() error { - if !(c.TargetURI.IsDB() || c.TargetURI.IsKube() || c.TargetURI.IsApp()) { + if !c.TargetURI.IsDB() && !c.TargetURI.IsKube() && !c.TargetURI.IsApp() { return trace.BadParameter("unsupported gateway target %v", c.TargetURI) } diff --git a/lib/terraformcloud/token_source_test.go b/lib/terraformcloud/token_source_test.go index 3d8eb611cc5b6..ce9acb4aa1e56 100644 --- a/lib/terraformcloud/token_source_test.go +++ b/lib/terraformcloud/token_source_test.go @@ -56,7 +56,7 @@ func TestIDTokenSource_GetIDToken(t *testing.T) { tok, err := its.GetIDToken() require.Error(t, err) require.True(t, trace.IsBadParameter(err)) - require.Equal(t, "", tok) + require.Empty(t, tok) }) }) @@ -86,7 +86,7 @@ func TestIDTokenSource_GetIDToken(t *testing.T) { tok, err := its.GetIDToken() require.Error(t, err) require.True(t, trace.IsBadParameter(err)) - require.Equal(t, "", tok) + require.Empty(t, tok) }) }) diff --git a/lib/utils/cli_test.go b/lib/utils/cli_test.go index 1c2e031c4d312..bf1200b9334c5 100644 --- a/lib/utils/cli_test.go +++ b/lib/utils/cli_test.go @@ -29,6 +29,8 @@ import ( "github.com/alecthomas/kingpin/v2" "github.com/gravitational/trace" "github.com/stretchr/testify/require" + + logutils "github.com/gravitational/teleport/lib/utils/log" ) func TestUserMessageFromError(t *testing.T) { @@ -37,7 +39,7 @@ func TestUserMessageFromError(t *testing.T) { var leveler slog.LevelVar leveler.Set(slog.LevelInfo) - slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: &leveler}))) + slog.SetDefault(slog.New(logutils.DiscardHandler{})) t.Cleanup(func() { slog.SetDefault(defaultLogger) }) diff --git a/lib/utils/fields_test.go b/lib/utils/fields_test.go index f56434a945487..d96ee1fdf9ce9 100644 --- a/lib/utils/fields_test.go +++ b/lib/utils/fields_test.go @@ -45,7 +45,7 @@ func TestFields(t *testing.T) { require.Equal(t, 1, f.GetInt("one")) require.Equal(t, 0, f.GetInt("two")) require.Equal(t, "vincent", f.GetString("name")) - require.Equal(t, "", f.GetString("city")) + require.Empty(t, f.GetString("city")) require.Equal(t, now, f.GetTime("time")) require.Equal(t, sliceString, f.GetStrings("strings")) require.Equal(t, sliceString, f.GetStrings("strings2")) diff --git a/lib/utils/fncache_test.go b/lib/utils/fncache_test.go index 9572059d387c2..4e3e5341975f1 100644 --- a/lib/utils/fncache_test.go +++ b/lib/utils/fncache_test.go @@ -125,7 +125,7 @@ func TestFnCacheConcurrentReads(t *testing.T) { require.NoError(t, first.err) val := first.val.(string) - require.NotZero(t, val) + require.NotEmpty(t, val) for i := 0; i < (workers - 1); i++ { r := <-results diff --git a/lib/utils/http_test.go b/lib/utils/http_test.go index 01c53dd816ca9..22bf011495ccc 100644 --- a/lib/utils/http_test.go +++ b/lib/utils/http_test.go @@ -50,8 +50,8 @@ func TestGetAnyHeader(t *testing.T) { header.Set("aaa", "a1") header.Set("bbb", "b1") - require.Equal(t, "", GetAnyHeader(header)) - require.Equal(t, "", GetAnyHeader(header, "ccc")) + require.Empty(t, GetAnyHeader(header)) + require.Empty(t, GetAnyHeader(header, "ccc")) require.Equal(t, "a1", GetAnyHeader(header, "aaa")) require.Equal(t, "a1", GetAnyHeader(header, "ccc", "aaa")) require.Equal(t, "b1", GetAnyHeader(header, "bbb", "aaa")) diff --git a/lib/utils/interval/multi_test.go b/lib/utils/interval/multi_test.go index 3ef8b1f17ad56..56a9953a9964c 100644 --- a/lib/utils/interval/multi_test.go +++ b/lib/utils/interval/multi_test.go @@ -117,7 +117,7 @@ func TestMultiIntervalBasics(t *testing.T) { for i := 0; i < 60; i++ { tick := <-interval.Next() require.False(t, tick.Time.IsZero()) - require.True(t, tick.Time.After(prevT) || tick.Time == prevT) + require.True(t, tick.Time.After(prevT) || tick.Time.Equal(prevT)) prevT = tick.Time switch tick.Key { case "fast": @@ -172,7 +172,7 @@ func TestMultiIntervalVariableDuration(t *testing.T) { for i := 0; i < 60; i++ { tick := <-interval.Next() require.False(t, tick.Time.IsZero()) - require.True(t, tick.Time.After(prevT) || tick.Time == prevT) + require.True(t, tick.Time.After(prevT) || tick.Time.Equal(prevT)) prevT = tick.Time switch tick.Key { case "foo": diff --git a/lib/utils/iterators_test.go b/lib/utils/iterators_test.go index 18b179389e603..c05252a153d56 100644 --- a/lib/utils/iterators_test.go +++ b/lib/utils/iterators_test.go @@ -110,7 +110,7 @@ func TestMockBackendLister_List(t *testing.T) { pageToken = nextToken } - require.Equal(t, "", pageToken) + require.Empty(t, pageToken) pageToken = "" results, nextToken, err := mock.List(ctx, 2, pageToken) @@ -126,7 +126,7 @@ func TestMockBackendLister_List(t *testing.T) { results, nextToken, err = mock.List(ctx, 2, nextToken) require.NoError(t, err) require.Equal(t, []int{5}, results) - require.Equal(t, "", nextToken) + require.Empty(t, nextToken) } type mockBackendLister struct { diff --git a/lib/utils/log/formatter_test.go b/lib/utils/log/formatter_test.go index e11a9f63620fb..6a22f08e2bd99 100644 --- a/lib/utils/log/formatter_test.go +++ b/lib/utils/log/formatter_test.go @@ -48,7 +48,7 @@ import ( const message = "Adding diagnostic debugging handlers.\t To connect with profiler, use go tool pprof diag_addr." var ( - logErr = errors.New("the quick brown fox jumped really high") + errLog = errors.New("the quick brown fox jumped really high") addr = fakeAddr{addr: "127.0.0.1:1234"} fields = logrus.Fields{ @@ -156,14 +156,14 @@ func TestOutput(t *testing.T) { slogLogger := slog.New(NewSlogTextHandler(&slogOutput, slogConfig)).With(teleport.ComponentKey, "test") // Add some fields and output the message at the desired log level via logrus. - l := entry.WithField("test", 123).WithField("animal", "llama\n").WithField("error", logErr) + l := entry.WithField("test", 123).WithField("animal", "llama\n").WithField("error", errLog) logrusTestLogLineNumber := func() int { l.WithField("diag_addr", &addr).WithField(teleport.ComponentFields, fields).Log(test.logrusLevel, message) return getCallerLineNumber() - 1 // Get the line number of this call, and assume the log call is right above it }() // Add some fields and output the message at the desired log level via slog. - l2 := slogLogger.With("test", 123).With("animal", "llama\n").With("error", logErr) + l2 := slogLogger.With("test", 123).With("animal", "llama\n").With("error", errLog) slogTestLogLineNumber := func() int { l2.With(teleport.ComponentFields, fields).Log(context.Background(), test.slogLevel, message, "diag_addr", &addr) return getCallerLineNumber() - 1 // Get the line number of this call, and assume the log call is right above it @@ -275,14 +275,14 @@ func TestOutput(t *testing.T) { slogLogger := slog.New(NewSlogJSONHandler(&slogOutput, SlogJSONHandlerConfig{Level: test.slogLevel})).With(teleport.ComponentKey, "test") // Add some fields and output the message at the desired log level via logrus. - l := entry.WithField("test", 123).WithField("animal", "llama").WithField("error", trace.Wrap(logErr)) + l := entry.WithField("test", 123).WithField("animal", "llama").WithField("error", trace.Wrap(errLog)) logrusTestLogLineNumber := func() int { l.WithField("diag_addr", addr.String()).Log(test.logrusLevel, message) return getCallerLineNumber() - 1 // Get the line number of this call, and assume the log call is right above it }() // Add some fields and output the message at the desired log level via slog. - l2 := slogLogger.With("test", 123).With("animal", "llama").With("error", trace.Wrap(logErr)) + l2 := slogLogger.With("test", 123).With("animal", "llama").With("error", trace.Wrap(errLog)) slogTestLogLineNumber := func() int { l2.Log(context.Background(), test.slogLevel, message, "diag_addr", &addr) return getCallerLineNumber() - 1 // Get the line number of this call, and assume the log call is right above it @@ -358,7 +358,7 @@ func BenchmarkFormatter(b *testing.B) { entry := logger.WithField(teleport.ComponentKey, "test") for i := 0; i < b.N; i++ { - l := entry.WithField("test", 123).WithField("animal", "llama\n").WithField("error", logErr) + l := entry.WithField("test", 123).WithField("animal", "llama\n").WithField("error", errLog) l.WithField("diag_addr", &addr).WithField(teleport.ComponentFields, fields).Info(message) } }) @@ -374,7 +374,7 @@ func BenchmarkFormatter(b *testing.B) { entry := logger.WithField(teleport.ComponentKey, "test") for i := 0; i < b.N; i++ { - l := entry.WithField("test", 123).WithField("animal", "llama\n").WithField("error", logErr) + l := entry.WithField("test", 123).WithField("animal", "llama\n").WithField("error", errLog) l.WithField("diag_addr", &addr).WithField(teleport.ComponentFields, fields).Info(message) } }) @@ -382,47 +382,51 @@ func BenchmarkFormatter(b *testing.B) { b.Run("slog", func(b *testing.B) { b.Run("default_text", func(b *testing.B) { - logger := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{ + var output bytes.Buffer + logger := slog.New(slog.NewTextHandler(&output, &slog.HandlerOptions{ AddSource: true, Level: slog.LevelDebug, })).With(teleport.ComponentKey, "test") b.ResetTimer() for i := 0; i < b.N; i++ { - l := logger.With("test", 123).With("animal", "llama\n").With("error", logErr) + l := logger.With("test", 123).With("animal", "llama\n").With("error", errLog) l.With(teleport.ComponentFields, fields).InfoContext(ctx, message, "diag_addr", &addr) } }) b.Run("text", func(b *testing.B) { - logger := slog.New(NewSlogTextHandler(io.Discard, SlogTextHandlerConfig{Level: slog.LevelDebug, EnableColors: true})).With(teleport.ComponentKey, "test") + var output bytes.Buffer + logger := slog.New(NewSlogTextHandler(&output, SlogTextHandlerConfig{Level: slog.LevelDebug, EnableColors: true})).With(teleport.ComponentKey, "test") b.ResetTimer() for i := 0; i < b.N; i++ { - l := logger.With("test", 123).With("animal", "llama\n").With("error", logErr) + l := logger.With("test", 123).With("animal", "llama\n").With("error", errLog) l.With(teleport.ComponentFields, fields).InfoContext(ctx, message, "diag_addr", &addr) } }) b.Run("default_json", func(b *testing.B) { - logger := slog.New(slog.NewJSONHandler(io.Discard, &slog.HandlerOptions{ + var output bytes.Buffer + logger := slog.New(slog.NewJSONHandler(&output, &slog.HandlerOptions{ AddSource: true, Level: slog.LevelDebug, })).With(teleport.ComponentKey, "test") b.ResetTimer() for i := 0; i < b.N; i++ { - l := logger.With("test", 123).With("animal", "llama\n").With("error", logErr) + l := logger.With("test", 123).With("animal", "llama\n").With("error", errLog) l.With(teleport.ComponentFields, fields).InfoContext(ctx, message, "diag_addr", &addr) } }) b.Run("json", func(b *testing.B) { - logger := slog.New(NewSlogJSONHandler(io.Discard, SlogJSONHandlerConfig{Level: slog.LevelDebug})).With(teleport.ComponentKey, "test") + var output bytes.Buffer + logger := slog.New(NewSlogJSONHandler(&output, SlogJSONHandlerConfig{Level: slog.LevelDebug})).With(teleport.ComponentKey, "test") b.ResetTimer() for i := 0; i < b.N; i++ { - l := logger.With("test", 123).With("animal", "llama\n").With("error", logErr) + l := logger.With("test", 123).With("animal", "llama\n").With("error", errLog) l.With(teleport.ComponentFields, fields).InfoContext(ctx, message, "diag_addr", &addr) } }) diff --git a/lib/utils/stream/zip.go b/lib/utils/stream/zip.go index 5be21bc22814b..7de7f0804b4ca 100644 --- a/lib/utils/stream/zip.go +++ b/lib/utils/stream/zip.go @@ -77,7 +77,8 @@ func (z *ZipStreams[T, V]) Process() error { for hasLeader && hasFollower { cmp := z.compareKeys(leaderItem, followerItem) - if cmp == -1 { + switch cmp { + case -1: // leader > follower - follower is missing if err := z.onMissing(leaderItem); err != nil { return trace.Wrap(err) @@ -87,13 +88,13 @@ func (z *ZipStreams[T, V]) Process() error { if hasLeader { leaderItem = z.leader.Item() } - } else if cmp == 1 { + case 1: // leader < follower - advancde hasFollower = z.follower.Next() if hasFollower { followerItem = z.follower.Item() } - } else { + default: // leader == follower if err := z.onEqualKeys(leaderItem, followerItem); err != nil { return trace.Wrap(err) diff --git a/lib/versioncontrol/upgradewindow/upgradewindow_test.go b/lib/versioncontrol/upgradewindow/upgradewindow_test.go index 7b724708652f4..3adb1bc9e9569 100644 --- a/lib/versioncontrol/upgradewindow/upgradewindow_test.go +++ b/lib/versioncontrol/upgradewindow/upgradewindow_test.go @@ -85,13 +85,13 @@ func TestKubeControllerDriver(t *testing.T) { err = driver.Reset(ctx) require.NoError(t, err) - require.Equal(t, "", bk.data[key]) + require.Empty(t, bk.data[key]) // verify reset of empty schedule has no effect err = driver.Reset(ctx) require.NoError(t, err) - require.Equal(t, "", bk.data[key]) + require.Empty(t, bk.data[key]) // setup another fake schedule err = driver.Sync(ctx, proto.ExportUpgradeWindowsResponse{ @@ -105,7 +105,7 @@ func TestKubeControllerDriver(t *testing.T) { err = driver.Sync(ctx, proto.ExportUpgradeWindowsResponse{}) require.NoError(t, err) - require.Equal(t, "", bk.data[key]) + require.Empty(t, bk.data[key]) } // TestSystemdUnitDriver verifies the basic behavior of the systemd unit export driver. @@ -156,7 +156,7 @@ func TestSystemdUnitDriver(t *testing.T) { sb, err = os.ReadFile(schedPath) require.NoError(t, err) - require.Equal(t, "", string(sb)) + require.Empty(t, string(sb)) // verify that duplicate resets succeed err = driver.Reset(ctx) @@ -179,7 +179,7 @@ func TestSystemdUnitDriver(t *testing.T) { sb, err = os.ReadFile(schedPath) require.NoError(t, err) - require.Equal(t, "", string(sb)) + require.Empty(t, string(sb)) } // fakeDriver is used to inject custom behavior into a dummy Driver instance. diff --git a/lib/vnet/ipbits.go b/lib/vnet/ipbits.go index 692ebf808ebc6..571842d0337b9 100644 --- a/lib/vnet/ipbits.go +++ b/lib/vnet/ipbits.go @@ -19,7 +19,6 @@ package vnet import ( "crypto/rand" "encoding/binary" - "fmt" mathrand "math/rand/v2" "net" @@ -101,7 +100,7 @@ func randomFreeIPv4InNet(ipNet *net.IPNet, free func(ipv4) bool) (ipv4, error) { break } } - return 0, trace.Wrap(fmt.Errorf("Exhausted all IPs in range %q", ipNet.String())) + return 0, trace.Errorf("exhausted all IPs in range %q", ipNet.String()) } // ipv4 holds a v4 IP address as a uint32 so we can do math on it. diff --git a/lib/vnet/ipbits_test.go b/lib/vnet/ipbits_test.go index ec0bc92644b34..7b1d4fa741715 100644 --- a/lib/vnet/ipbits_test.go +++ b/lib/vnet/ipbits_test.go @@ -52,5 +52,5 @@ func TestRandomFreeIPv4InNet(t *testing.T) { // Try to assign 1 more IP. _, err = randomFreeIPv4InNet(ipNet, ipIsFree) - require.ErrorContains(t, err, "Exhausted all IPs in range") + require.ErrorContains(t, err, "exhausted all IPs in range") } diff --git a/lib/web/apiserver_test.go b/lib/web/apiserver_test.go index 01039e51c5428..330c7ec00bfb1 100644 --- a/lib/web/apiserver_test.go +++ b/lib/web/apiserver_test.go @@ -81,7 +81,6 @@ import ( "github.com/gravitational/teleport" "github.com/gravitational/teleport/api/breaker" authproto "github.com/gravitational/teleport/api/client/proto" - clientproto "github.com/gravitational/teleport/api/client/proto" "github.com/gravitational/teleport/api/client/webclient" "github.com/gravitational/teleport/api/constants" apidefaults "github.com/gravitational/teleport/api/defaults" @@ -1457,7 +1456,7 @@ func TestUnifiedResourcesGet(t *testing.T) { res = clusterNodesGetResponse{} require.NoError(t, json.Unmarshal(re.Bytes(), &res)) require.Len(t, res.Items, 15) - require.NotEqual(t, "", res.StartKey) + require.NotEmpty(t, res.StartKey) // should return second page and have no third page query = url.Values{"sort": []string{"name"}, "limit": []string{"15"}} @@ -1467,7 +1466,7 @@ func TestUnifiedResourcesGet(t *testing.T) { res = clusterNodesGetResponse{} require.NoError(t, json.Unmarshal(re.Bytes(), &res)) require.Len(t, res.Items, 11) - require.Equal(t, "", res.StartKey) + require.Empty(t, res.StartKey) // Only list valid AWS Roles for AWS Apps query = url.Values{ @@ -8097,7 +8096,7 @@ func addCSRFCookieToReq(req *http.Request, token string) { func removeSpace(in string) string { for _, c := range []string{"\n", "\r", "\t"} { - in = strings.Replace(in, c, " ", -1) + in = strings.ReplaceAll(in, c, " ") } return strings.TrimSpace(in) } @@ -9249,7 +9248,7 @@ func startKubeWithoutCleanup(ctx context.Context, t *testing.T, cfg startKubeOpt }) require.NoError(t, err) - inventoryHandle := inventory.NewDownstreamHandle(client.InventoryControlStream, clientproto.UpstreamInventoryHello{ + inventoryHandle := inventory.NewDownstreamHandle(client.InventoryControlStream, authproto.UpstreamInventoryHello{ ServerID: hostID, Version: teleport.Version, Services: []types.SystemRole{role}, @@ -10956,15 +10955,15 @@ func Test_setEntitlementsWithLegacyLogic(t *testing.T) { clusterFeatures: authproto.Features{ AccessControls: false, AccessGraph: false, - AccessList: &clientproto.AccessListFeature{ + AccessList: &authproto.AccessListFeature{ CreateLimit: 10, }, - AccessMonitoring: &clientproto.AccessMonitoringFeature{ + AccessMonitoring: &authproto.AccessMonitoringFeature{ Enabled: false, MaxReportRangeLimit: 20, }, AccessMonitoringConfigured: false, - AccessRequests: &clientproto.AccessRequestsFeature{ + AccessRequests: &authproto.AccessRequestsFeature{ MonthlyRequestLimit: 30, }, AdvancedAccessWorkflows: false, @@ -10975,7 +10974,7 @@ func Test_setEntitlementsWithLegacyLogic(t *testing.T) { CustomTheme: "theme", DB: false, Desktop: false, - DeviceTrust: &clientproto.DeviceTrustFeature{ + DeviceTrust: &authproto.DeviceTrustFeature{ Enabled: false, DevicesUsageLimit: 40, }, @@ -11123,21 +11122,21 @@ func Test_setEntitlementsWithLegacyLogic(t *testing.T) { MobileDeviceManagement: true, OIDC: true, SAML: true, - AccessRequests: &clientproto.AccessRequestsFeature{ + AccessRequests: &authproto.AccessRequestsFeature{ MonthlyRequestLimit: 88, }, - AccessList: &clientproto.AccessListFeature{ + AccessList: &authproto.AccessListFeature{ CreateLimit: 88, }, - AccessMonitoring: &clientproto.AccessMonitoringFeature{ + AccessMonitoring: &authproto.AccessMonitoringFeature{ Enabled: true, MaxReportRangeLimit: 88, }, - DeviceTrust: &clientproto.DeviceTrustFeature{ + DeviceTrust: &authproto.DeviceTrustFeature{ Enabled: true, DevicesUsageLimit: 88, }, - Policy: &clientproto.PolicyFeature{ + Policy: &authproto.PolicyFeature{ Enabled: true, }, }, @@ -11243,21 +11242,21 @@ func Test_setEntitlementsWithLegacyLogic(t *testing.T) { MobileDeviceManagement: true, OIDC: true, SAML: true, - AccessRequests: &clientproto.AccessRequestsFeature{ + AccessRequests: &authproto.AccessRequestsFeature{ MonthlyRequestLimit: 88, }, - AccessList: &clientproto.AccessListFeature{ + AccessList: &authproto.AccessListFeature{ CreateLimit: 88, }, - AccessMonitoring: &clientproto.AccessMonitoringFeature{ + AccessMonitoring: &authproto.AccessMonitoringFeature{ Enabled: true, MaxReportRangeLimit: 88, }, - DeviceTrust: &clientproto.DeviceTrustFeature{ + DeviceTrust: &authproto.DeviceTrustFeature{ Enabled: true, DevicesUsageLimit: 88, }, - Policy: &clientproto.PolicyFeature{ + Policy: &authproto.PolicyFeature{ Enabled: true, }, }, @@ -11357,11 +11356,11 @@ func Test_setEntitlementsWithLegacyLogic(t *testing.T) { PremiumSupport: true, }, clusterFeatures: authproto.Features{ - DeviceTrust: &clientproto.DeviceTrustFeature{}, - AccessRequests: &clientproto.AccessRequestsFeature{}, - AccessList: &clientproto.AccessListFeature{}, - AccessMonitoring: &clientproto.AccessMonitoringFeature{}, - Policy: &clientproto.PolicyFeature{}, + DeviceTrust: &authproto.DeviceTrustFeature{}, + AccessRequests: &authproto.AccessRequestsFeature{}, + AccessList: &authproto.AccessListFeature{}, + AccessMonitoring: &authproto.AccessMonitoringFeature{}, + Policy: &authproto.PolicyFeature{}, }, expected: &webclient.WebConfig{ Auth: webclient.WebConfigAuthSettings{ diff --git a/lib/web/databases.go b/lib/web/databases.go index ad834a3e8669d..b99ef0da14198 100644 --- a/lib/web/databases.go +++ b/lib/web/databases.go @@ -41,7 +41,6 @@ import ( oteltrace "go.opentelemetry.io/otel/trace" "github.com/gravitational/teleport/api/client/proto" - clientproto "github.com/gravitational/teleport/api/client/proto" "github.com/gravitational/teleport/api/constants" "github.com/gravitational/teleport/api/types" "github.com/gravitational/teleport/api/utils/keys" @@ -698,13 +697,13 @@ func (s *databaseInteractiveSession) issueCerts() (*tls.Certificate, error) { routeToDatabase := s.route() - certsReq := clientproto.UserCertsRequest{ + certsReq := proto.UserCertsRequest{ TLSPublicKey: publicKeyPEM, Username: s.sctx.GetUser(), Expires: s.sctx.cfg.Session.GetExpiryTime(), Format: constants.CertificateFormatStandard, RouteToCluster: s.site.GetName(), - Usage: clientproto.UserCertsRequest_Database, + Usage: proto.UserCertsRequest_Database, RouteToDatabase: routeToDatabase, } @@ -713,8 +712,8 @@ func (s *databaseInteractiveSession) issueCerts() (*tls.Certificate, error) { RootAuthClient: s.sctx.cfg.RootClient, MFACeremony: newMFACeremony(s.stream.WSStream, s.sctx.cfg.RootClient.CreateAuthenticateChallenge, s.proxyAddr), MFAAgainstRoot: s.sctx.cfg.RootClusterName == s.site.GetName(), - MFARequiredReq: &clientproto.IsMFARequiredRequest{ - Target: &clientproto.IsMFARequiredRequest_Database{Database: &routeToDatabase}, + MFARequiredReq: &proto.IsMFARequiredRequest{ + Target: &proto.IsMFARequiredRequest_Database{Database: &routeToDatabase}, }, CertsReq: &certsReq, }) @@ -774,8 +773,8 @@ func (s *databaseInteractiveSession) makeReplConn() (*tls.Conn, error) { return tls.Client(s.replConn, tlsConfig), nil } -func (s *databaseInteractiveSession) route() clientproto.RouteToDatabase { - return clientproto.RouteToDatabase{ +func (s *databaseInteractiveSession) route() proto.RouteToDatabase { + return proto.RouteToDatabase{ Protocol: s.req.Protocol, ServiceName: s.req.ServiceName, Username: s.req.DatabaseUser, diff --git a/lib/web/kube.go b/lib/web/kube.go index 0ca7237056edd..7456a07ad0560 100644 --- a/lib/web/kube.go +++ b/lib/web/kube.go @@ -32,7 +32,6 @@ import ( "time" "github.com/gogo/protobuf/proto" - gogoproto "github.com/gogo/protobuf/proto" "github.com/gorilla/websocket" "github.com/gravitational/trace" "github.com/sirupsen/logrus" @@ -464,7 +463,7 @@ func (h *Handler) joinKubernetesSession( }, }) - envelopeBytes, err := gogoproto.Marshal(&terminal.Envelope{ + envelopeBytes, err := proto.Marshal(&terminal.Envelope{ Version: defaults.WebsocketVersion, Type: defaults.WebsocketSessionMetadata, Payload: string(sessionMetadataResponse), diff --git a/lib/web/notifications_test.go b/lib/web/notifications_test.go index 6e64a2ad3bafb..831f623e4f817 100644 --- a/lib/web/notifications_test.go +++ b/lib/web/notifications_test.go @@ -203,7 +203,7 @@ func TestNotifications(t *testing.T) { fetchedNotifications = append(fetchedNotifications, unmarshaledNotificationsResp.Notifications...) require.Equal(t, expectedNotifications, notificationsToTitlesList(t, fetchedNotifications)) - require.Equal(t, "", unmarshaledNotificationsResp.NextKey) + require.Empty(t, unmarshaledNotificationsResp.NextKey) require.Equal(t, lastSeenTimeString, unmarshaledNotificationsResp.UserLastSeenNotification) // Mark the most recent notification as clicked. diff --git a/lib/web/resources_test.go b/lib/web/resources_test.go index 99ea4121e6f44..a199392359075 100644 --- a/lib/web/resources_test.go +++ b/lib/web/resources_test.go @@ -419,7 +419,7 @@ func TestRoleCRUD(t *testing.T) { require.NoError(t, json.Unmarshal(resp.Bytes(), &getResponse), "invalid resource item received") assert.Equal(t, http.StatusOK, resp.Code(), "unexpected status code getting roles") - assert.Equal(t, "", getResponse.StartKey) + assert.Empty(t, getResponse.StartKey) for _, item := range getResponse.Items.([]interface{}) { assert.NotEqual(t, "test-role", item.(map[string]interface{})["name"], "expected test-role to be deleted") } @@ -536,7 +536,7 @@ func TestGithubConnectorsCRUD(t *testing.T) { assert.Equal(t, tt.wantConnectorType, connResponse.DefaultConnectorType) // Verify connectors list - require.Equal(t, len(tt.connectors), len(connResponse.Connectors)) + require.Len(t, tt.connectors, len(connResponse.Connectors)) for i, conn := range tt.connectors { expectedItem, err := ui.NewResourceItem(conn) require.NoError(t, err) diff --git a/lib/web/scripts.go b/lib/web/scripts.go index 7dc656958e1ad..3c15732bfcade 100644 --- a/lib/web/scripts.go +++ b/lib/web/scripts.go @@ -94,7 +94,7 @@ func (h *Handler) installScriptOptions(ctx context.Context) (scripts.InstallScri // if there's a rollout, we do new autoupdates _, rolloutErr := h.cfg.AccessPoint.GetAutoUpdateAgentRollout(ctx) - if rolloutErr != nil && !(trace.IsNotFound(rolloutErr) || trace.IsNotImplemented(rolloutErr)) { + if rolloutErr != nil && !trace.IsNotFound(rolloutErr) && !trace.IsNotImplemented(rolloutErr) { h.logger.WarnContext(ctx, "Failed to get rollout", "error", rolloutErr) return scripts.InstallScriptOptions{}, trace.Wrap(err, "failed to check the autoupdate agent rollout state") } diff --git a/tool/tbot/anonymous_telemetry_test.go b/tool/tbot/anonymous_telemetry_test.go index 0bdba1da01a16..5719ef17da428 100644 --- a/tool/tbot/anonymous_telemetry_test.go +++ b/tool/tbot/anonymous_telemetry_test.go @@ -91,7 +91,7 @@ func TestSendTelemetry(t *testing.T) { require.NoError(t, err) require.NotNil(t, mockClient.eventRequest) require.NotZero(t, mockClient.eventRequest.Timestamp) - require.NotZero(t, mockClient.eventRequest.DistinctId) + require.NotEmpty(t, mockClient.eventRequest.DistinctId) require.Equal(t, &prehogv1a.SubmitTbotEventRequest_Start{ Start: &prehogv1a.TbotStartEvent{ RunMode: prehogv1a.TbotStartEvent_RUN_MODE_ONE_SHOT, diff --git a/tool/tctl/common/resource_command_test.go b/tool/tctl/common/resource_command_test.go index f68022a6df146..cc156b960530c 100644 --- a/tool/tctl/common/resource_command_test.go +++ b/tool/tctl/common/resource_command_test.go @@ -1814,8 +1814,8 @@ version: v1 var expected databaseobjectimportrule.Resource require.NoError(t, yaml.Unmarshal([]byte(resourceYAML), &expected)) - require.Equal(t, "", cmp.Diff(expected, resources[0], cmpOpts...)) - require.Equal(t, "", cmp.Diff(databaseobjectimportrule.ResourceToProto(&expected), databaseobjectimportrule.ResourceToProto(&resources[0]), cmpOpts...)) + require.Empty(t, cmp.Diff(expected, resources[0], cmpOpts...)) + require.Empty(t, cmp.Diff(databaseobjectimportrule.ResourceToProto(&expected), databaseobjectimportrule.ResourceToProto(&resources[0]), cmpOpts...)) } func testCreateClusterNetworkingConfig(t *testing.T, clt *authclient.Client) { @@ -2099,8 +2099,8 @@ version: v1 var expected databaseobject.Resource require.NoError(t, yaml.Unmarshal([]byte(resourceYAML), &expected)) - require.Equal(t, "", cmp.Diff(expected, resources[0], cmpOpts...)) - require.Equal(t, "", cmp.Diff(databaseobject.ResourceToProto(&expected), databaseobject.ResourceToProto(&resources[0]), cmpOpts...)) + require.Empty(t, cmp.Diff(expected, resources[0], cmpOpts...)) + require.Empty(t, cmp.Diff(databaseobject.ResourceToProto(&expected), databaseobject.ResourceToProto(&resources[0]), cmpOpts...)) } // TestCreateEnterpriseResources asserts that tctl create diff --git a/tool/teleport/common/debug.go b/tool/teleport/common/debug.go index fda61c91e43b8..c993b78742f6a 100644 --- a/tool/teleport/common/debug.go +++ b/tool/teleport/common/debug.go @@ -196,7 +196,7 @@ func convertToReadableErr(err error, dataDir, socketPath string) error { switch { case errors.Is(err, context.Canceled): - return fmt.Errorf("Request canceled") + return trace.Errorf("request canceled") case trace.IsConnectionProblem(err): return trace.BadParameter("Unable to reach debug service socket at %q."+ "\n\nVerify if you have enough permissions to open the socket and if the path"+ diff --git a/tool/teleport/common/debug_test.go b/tool/teleport/common/debug_test.go index b90e98568d685..0a9187411133e 100644 --- a/tool/teleport/common/debug_test.go +++ b/tool/teleport/common/debug_test.go @@ -99,7 +99,7 @@ func TestCollectProfiles(t *testing.T) { require.Equal(t, expectedSeconds, profile.seconds) requestedProfiles = append(requestedProfiles, profile.name) } - require.Equal(t, len(test.expectedProfiles), len(requestedProfiles), "expected %d to be requested but got %d", len(test.expectedProfiles), len(requestedProfiles)) + require.Len(t, test.expectedProfiles, len(requestedProfiles), "expected %d to be requested but got %d", len(test.expectedProfiles), len(requestedProfiles)) reader, err := gzip.NewReader(&out) require.NoError(t, err) diff --git a/tool/teleport/common/teleport_test.go b/tool/teleport/common/teleport_test.go index 113a4d75519aa..3cfe1196f956f 100644 --- a/tool/teleport/common/teleport_test.go +++ b/tool/teleport/common/teleport_test.go @@ -161,7 +161,7 @@ func TestTeleportMain(t *testing.T) { InitOnly: true, }) require.Equal(t, "start", cmd) - require.Equal(t, len(bootstrapEntries), len(conf.Auth.BootstrapResources)) + require.Len(t, bootstrapEntries, len(conf.Auth.BootstrapResources)) for i, entry := range bootstrapEntries { require.Equal(t, entry.kind, conf.Auth.BootstrapResources[i].GetKind(), entry.fileName) require.Equal(t, entry.name, conf.Auth.BootstrapResources[i].GetName(), entry.fileName) @@ -174,7 +174,7 @@ func TestTeleportMain(t *testing.T) { InitOnly: true, }) require.Equal(t, "start", cmd) - require.Equal(t, len(bootstrapEntries), len(conf.Auth.ApplyOnStartupResources)) + require.Len(t, bootstrapEntries, len(conf.Auth.ApplyOnStartupResources)) for i, entry := range bootstrapEntries { require.Equal(t, entry.kind, conf.Auth.ApplyOnStartupResources[i].GetKind(), entry.fileName) require.Equal(t, entry.name, conf.Auth.ApplyOnStartupResources[i].GetName(), entry.fileName) diff --git a/tool/tsh/common/mfa.go b/tool/tsh/common/mfa.go index 404be014e1c0f..3fc32cd6151a3 100644 --- a/tool/tsh/common/mfa.go +++ b/tool/tsh/common/mfa.go @@ -32,6 +32,12 @@ import ( "strings" "time" + "github.com/alecthomas/kingpin/v2" + "github.com/ghodss/yaml" + "github.com/gravitational/trace" + "github.com/pquerna/otp" + "github.com/pquerna/otp/totp" + "github.com/gravitational/teleport" "github.com/gravitational/teleport/api/client/proto" "github.com/gravitational/teleport/api/constants" @@ -46,12 +52,6 @@ import ( "github.com/gravitational/teleport/lib/client" "github.com/gravitational/teleport/lib/defaults" "github.com/gravitational/teleport/lib/utils" - - "github.com/alecthomas/kingpin/v2" - "github.com/ghodss/yaml" - "github.com/gravitational/trace" - "github.com/pquerna/otp" - "github.com/pquerna/otp/totp" ) const ( diff --git a/tool/tsh/common/proxy.go b/tool/tsh/common/proxy.go index 5e813d9c46f80..ce9f5bc3f58f5 100644 --- a/tool/tsh/common/proxy.go +++ b/tool/tsh/common/proxy.go @@ -115,7 +115,7 @@ func formatCommand(cmd *exec.Cmd) string { var args []string for _, arg := range cmd.Args { // escape the potential quotes within - arg = strings.Replace(arg, `"`, `\"`, -1) + arg = strings.ReplaceAll(arg, `"`, `\"`) // if there is whitespace within, surround with quotes if strings.IndexFunc(arg, unicode.IsSpace) != -1 { diff --git a/tool/tsh/common/proxy_test.go b/tool/tsh/common/proxy_test.go index 7f6a39203ceab..f6d442a34400b 100644 --- a/tool/tsh/common/proxy_test.go +++ b/tool/tsh/common/proxy_test.go @@ -936,7 +936,7 @@ func TestList(t *testing.T) { var results []result require.NoError(t, json.Unmarshal(out, &results)) - require.Equal(t, len(expected), len(results)) + require.Len(t, expected, len(results)) for _, res := range results { node, ok := expected[res.Cluster] require.True(t, ok, "expected node to be present for cluster %s", res.Cluster) diff --git a/tool/tsh/common/tsh.go b/tool/tsh/common/tsh.go index dd2590f230398..b2bbf514f666f 100644 --- a/tool/tsh/common/tsh.go +++ b/tool/tsh/common/tsh.go @@ -3100,8 +3100,8 @@ func serializeDatabases(databases []types.Database, format string, accessChecker } var out []byte - switch { - case format == teleport.JSON: + switch format { + case teleport.JSON: out, err = utils.FastMarshalIndent(printObj, "", " ") default: out, err = yaml.Marshal(printObj) diff --git a/tool/tsh/common/tsh_test.go b/tool/tsh/common/tsh_test.go index c5790651f7006..16e02e1a153cb 100644 --- a/tool/tsh/common/tsh_test.go +++ b/tool/tsh/common/tsh_test.go @@ -2834,8 +2834,8 @@ func TestSSHHeadlessCLIFlags(t *testing.T) { assertErr: require.NoError, assertConfig: func(t require.TestingT, c *client.Config) { require.Equal(t, "other-proxy:3080", c.WebProxyAddr) - require.Equal(t, "", c.Username) - require.Equal(t, "", c.SiteName) + require.Empty(t, c.Username) + require.Empty(t, c.SiteName) }, }, { name: "NOK --headless with mismatched auth connector", diff --git a/tool/tsh/common/vnet_client_application.go b/tool/tsh/common/vnet_client_application.go index 4909a252f90d8..b9ee5c1ed4103 100644 --- a/tool/tsh/common/vnet_client_application.go +++ b/tool/tsh/common/vnet_client_application.go @@ -176,7 +176,7 @@ func (p *vnetClientApplication) retryWithRelogin(ctx context.Context, tc *client if p.loginMu.TryLock() { didLock = true } else { - return fmt.Errorf("not attempting re-login to cluster %s, another login is current in progress.", tc.SiteName) + return fmt.Errorf("not attempting re-login to cluster %s, another login is current in progress", tc.SiteName) } fmt.Printf("Login for cluster %s expired, attempting to log in again.\n", tc.SiteName) return nil