From 1a5b8b606f5af207e66d1fe808f8866aa62dae51 Mon Sep 17 00:00:00 2001 From: Caleb Doxsey Date: Thu, 2 May 2024 14:33:52 -0600 Subject: [PATCH] core/lint: upgrade golangci-lint, replace interface{} with any (#5099) * core/lint: upgrade golangci-lint, replace interface{} with any * regen proto --- .github/workflows/lint.yaml | 2 +- .tool-versions | 1 + Makefile | 2 +- authenticate/handlers_test.go | 10 ++-- authorize/access_tracker_test.go | 4 +- .../evaluator/google_cloud_serverless.go | 4 +- authorize/evaluator/headers_evaluator.go | 8 +-- authorize/evaluator/headers_evaluator_test.go | 6 +-- authorize/evaluator/policy_evaluator.go | 12 ++--- authorize/internal/store/store.go | 8 +-- config/autocert_test.go | 16 +++--- config/codec_type.go | 2 +- config/config_source_test.go | 2 +- config/custom.go | 54 +++++++++---------- config/custom_test.go | 12 ++--- config/envoyconfig/bootstrap.go | 2 +- config/envoyconfig/listeners_test.go | 2 +- config/envoyconfig/lua_test.go | 38 ++++++------- config/envoyconfig/routes.go | 2 +- config/http_test.go | 4 +- config/layered_test.go | 4 +- config/metrics_test.go | 2 +- config/options.go | 2 +- config/options_test.go | 4 +- config/policy_ppl_test.go | 6 +-- config/trace_test.go | 2 +- databroker/databroker_test.go | 2 +- integration/authorization_test.go | 2 +- .../cmd/pomerium-integration-tests/main.go | 4 +- integration/main_test.go | 2 +- integration/policy_test.go | 8 +-- internal/authenticateflow/authenticateflow.go | 2 +- internal/authenticateflow/stateful_test.go | 2 +- internal/autocert/manager.go | 2 +- internal/autocert/manager_test.go | 26 ++++----- internal/autocert/storage.go | 2 +- internal/controlplane/events_test.go | 4 +- internal/controlplane/xdsmgr/xdsmgr.go | 4 +- internal/controlplane/xdsmgr/xdsmgr_test.go | 4 +- internal/enabler/enabler_test.go | 4 +- internal/encoding/base64.go | 2 +- internal/encoding/econding.go | 4 +- internal/encoding/jws/jws.go | 6 +-- internal/handlers/signedout.go | 4 +- internal/handlers/signout.go | 4 +- internal/handlers/webauthn/webauthn.go | 2 +- internal/hashutil/hashutil.go | 4 +- internal/hashutil/hashutil_test.go | 2 +- internal/httputil/client.go | 2 +- internal/httputil/cookie_test.go | 10 ++-- internal/httputil/handlers.go | 2 +- internal/httputil/handlers_test.go | 10 ++-- internal/httputil/reproxy/reproxy_test.go | 4 +- internal/httputil/server_test.go | 12 ++--- internal/identity/claims.go | 14 ++--- internal/identity/manager/manager.go | 2 +- internal/identity/manager/schedulers_test.go | 4 +- internal/identity/mock_provider.go | 2 +- internal/identity/oauth/apple/apple.go | 2 +- internal/identity/oauth/github/github.go | 6 +-- internal/identity/oidc/azure/microsoft.go | 2 +- internal/identity/oidc/oidc.go | 4 +- internal/identity/oidc/refresh_test.go | 4 +- internal/identity/oidc/userinfo.go | 2 +- internal/identity/providers.go | 2 +- internal/log/grpc.go | 24 ++++----- internal/log/log.go | 4 +- internal/log/middleware_test.go | 18 +++---- internal/middleware/middleware_test.go | 6 +-- internal/sessions/cookie/cookie_store.go | 2 +- internal/sessions/cookie/cookie_store_test.go | 2 +- internal/sessions/cookie/middleware_test.go | 2 +- internal/sessions/header/middleware_test.go | 2 +- internal/sessions/middleware.go | 2 +- internal/sessions/middleware_test.go | 2 +- internal/sessions/mock/mock_store.go | 2 +- .../sessions/queryparam/middleware_test.go | 2 +- internal/sessions/queryparam/query_store.go | 2 +- internal/sessions/store.go | 2 +- internal/telemetry/metrics/grpc.go | 4 +- internal/telemetry/metrics/helpers_test.go | 2 +- internal/telemetry/metrics/http_test.go | 4 +- internal/telemetry/metrics/providers_test.go | 2 +- internal/testutil/testutil.go | 12 ++--- internal/urlutil/signed.go | 2 +- internal/zero/connect-mux/config.go | 2 +- internal/zero/controller/mux_log.go | 8 +-- internal/zero/reconciler/bundles_queue.go | 4 +- internal/zero/reconciler/service.go | 2 +- internal/zero/reconciler/sync.go | 4 +- internal/zero/token/cache_test.go | 4 +- pkg/cmd/pomerium/pomerium.go | 2 +- pkg/contextutil/contextutil.go | 2 +- pkg/cryptutil/hash_test.go | 2 +- pkg/cryptutil/jose.go | 6 +-- pkg/cryptutil/x509.go | 8 +-- pkg/fanout/fanout_test.go | 10 ++-- pkg/grpc/client.go | 2 +- pkg/grpc/client_test.go | 2 +- pkg/grpc/databroker/databroker_test.go | 2 +- pkg/grpc/databroker/leaser_test.go | 4 +- pkg/grpc/databroker/syncer_test.go | 6 +-- pkg/grpc/user/user.go | 4 +- pkg/grpcutil/client.go | 2 +- pkg/grpcutil/options.go | 6 +-- pkg/grpcutil/version.go | 4 +- pkg/httputil/serve.go | 2 +- pkg/httputil/serve_test.go | 2 +- pkg/policy/criteria/criteria.go | 4 +- pkg/policy/criteria/criteria_test.go | 10 ++-- pkg/policy/criteria/matchers_test.go | 4 +- pkg/policy/generator/generator_test.go | 2 +- pkg/policy/parser/parser.go | 2 +- pkg/protoutil/any.go | 2 +- pkg/protoutil/any_test.go | 6 +-- pkg/protoutil/crypt_test.go | 4 +- pkg/protoutil/struct.go | 2 +- pkg/protoutil/struct_test.go | 6 +-- pkg/protoutil/transform_test.go | 2 +- pkg/storage/cache.go | 4 +- pkg/storage/cache_test.go | 6 +-- pkg/storage/filter_test.go | 4 +- pkg/storage/index_test.go | 2 +- pkg/storage/inmemory/stream.go | 4 +- pkg/storage/postgres/filter.go | 2 +- pkg/storage/postgres/postgres.go | 8 +-- pkg/storage/storage.go | 2 +- pkg/storage/stream.go | 2 +- pkg/storage/stream_filter.go | 6 +-- pkg/storage/stream_filter_test.go | 2 +- pkg/telemetry/requestid/grpc_client.go | 2 +- pkg/telemetry/requestid/grpc_server.go | 4 +- pkg/webauthnutil/credential_storage_test.go | 4 +- pkg/webauthnutil/device_type_test.go | 4 +- proxy/proxy.go | 2 +- 135 files changed, 341 insertions(+), 340 deletions(-) diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index 55da758ae..6f3b5feec 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -22,5 +22,5 @@ jobs: - uses: golangci/golangci-lint-action@9d1e0624a798bb64f6c3cea93db47765312263dc with: - version: v1.55 + version: v1.57 args: --timeout=10m diff --git a/.tool-versions b/.tool-versions index f5264425d..562109625 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1 +1,2 @@ golang 1.22.0 +golangci-lint 1.57.2 diff --git a/Makefile b/Makefile index 9864ee5fd..0d88e0e2b 100644 --- a/Makefile +++ b/Makefile @@ -87,7 +87,7 @@ build-ui: yarn .PHONY: lint lint: ## Verifies `golint` passes. @echo "==> $@" - @go run github.com/golangci/golangci-lint/cmd/golangci-lint@v1.55.2 run ./... --fix + @go run github.com/golangci/golangci-lint/cmd/golangci-lint@v1.57.2 run ./... --fix .PHONY: test test: get-envoy ## Runs the go tests. diff --git a/authenticate/handlers_test.go b/authenticate/handlers_test.go index ad5eab915..a40c3b9e3 100644 --- a/authenticate/handlers_test.go +++ b/authenticate/handlers_test.go @@ -225,7 +225,7 @@ func TestAuthenticate_SignOut(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() a := &Authenticate{ - cfg: getAuthenticateConfig(WithGetIdentityProvider(func(options *config.Options, idpID string) (identity.Authenticator, error) { + cfg: getAuthenticateConfig(WithGetIdentityProvider(func(_ *config.Options, _ string) (identity.Authenticator, error) { return tt.provider, nil })), state: atomicutil.NewValue(&authenticateState{ @@ -280,7 +280,7 @@ func TestAuthenticate_SignOutDoesNotRequireSession(t *testing.T) { sessionStore := &mstore.Store{LoadError: errors.New("no session")} a := &Authenticate{ - cfg: getAuthenticateConfig(WithGetIdentityProvider(func(options *config.Options, idpID string) (identity.Authenticator, error) { + cfg: getAuthenticateConfig(WithGetIdentityProvider(func(_ *config.Options, _ string) (identity.Authenticator, error) { return identity.MockProvider{}, nil })), state: atomicutil.NewValue(&authenticateState{ @@ -355,7 +355,7 @@ func TestAuthenticate_OAuthCallback(t *testing.T) { } authURL, _ := url.Parse(tt.authenticateURL) a := &Authenticate{ - cfg: getAuthenticateConfig(WithGetIdentityProvider(func(options *config.Options, idpID string) (identity.Authenticator, error) { + cfg: getAuthenticateConfig(WithGetIdentityProvider(func(_ *config.Options, _ string) (identity.Authenticator, error) { return tt.provider, nil })), state: atomicutil.NewValue(&authenticateState{ @@ -401,7 +401,7 @@ func TestAuthenticate_OAuthCallback(t *testing.T) { func TestAuthenticate_SessionValidatorMiddleware(t *testing.T) { t.Parallel() - fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fn := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprintln(w, "RVSI FILIVS CAISAR") w.WriteHeader(http.StatusOK) @@ -467,7 +467,7 @@ func TestAuthenticate_SessionValidatorMiddleware(t *testing.T) { t.Fatal(err) } a := &Authenticate{ - cfg: getAuthenticateConfig(WithGetIdentityProvider(func(options *config.Options, idpID string) (identity.Authenticator, error) { + cfg: getAuthenticateConfig(WithGetIdentityProvider(func(_ *config.Options, _ string) (identity.Authenticator, error) { return tt.provider, nil })), state: atomicutil.NewValue(&authenticateState{ diff --git a/authorize/access_tracker_test.go b/authorize/access_tracker_test.go index a83ffd146..8f0926516 100644 --- a/authorize/access_tracker_test.go +++ b/authorize/access_tracker_test.go @@ -55,7 +55,7 @@ func TestAccessTracker(t *testing.T) { } tracker := NewAccessTracker(&testAccessTrackerProvider{ dataBrokerServiceClient: &mockDataBrokerServiceClient{ - get: func(ctx context.Context, in *databroker.GetRequest, opts ...grpc.CallOption) (*databroker.GetResponse, error) { + get: func(_ context.Context, in *databroker.GetRequest, _ ...grpc.CallOption) (*databroker.GetResponse, error) { mu.Lock() defer mu.Unlock() @@ -88,7 +88,7 @@ func TestAccessTracker(t *testing.T) { return nil, status.Errorf(codes.InvalidArgument, "unknown type: %s", in.GetType()) } }, - put: func(ctx context.Context, in *databroker.PutRequest, opts ...grpc.CallOption) (*databroker.PutResponse, error) { + put: func(_ context.Context, in *databroker.PutRequest, _ ...grpc.CallOption) (*databroker.PutResponse, error) { mu.Lock() defer mu.Unlock() diff --git a/authorize/evaluator/google_cloud_serverless.go b/authorize/evaluator/google_cloud_serverless.go index 7feaffa76..0834c6ca5 100644 --- a/authorize/evaluator/google_cloud_serverless.go +++ b/authorize/evaluator/google_cloud_serverless.go @@ -34,7 +34,7 @@ var ( types.Args(types.S, types.S), types.NewObject(nil, types.NewDynamicProperty(types.S, types.S)), ), - }, func(bctx rego.BuiltinContext, op1 *ast.Term, op2 *ast.Term) (*ast.Term, error) { + }, func(_ rego.BuiltinContext, op1 *ast.Term, op2 *ast.Term) (*ast.Term, error) { serviceAccount, ok := op1.Value.(ast.String) if !ok { return nil, fmt.Errorf("invalid service account type: %T", op1) @@ -65,7 +65,7 @@ type gcpIdentityTokenSource struct { } func (src *gcpIdentityTokenSource) Token() (*oauth2.Token, error) { - res, err, _ := src.singleflight.Do("", func() (interface{}, error) { + res, err, _ := src.singleflight.Do("", func() (any, error) { req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, GCPIdentityDocURL+"?"+url.Values{ "format": {"full"}, "audience": {src.audience}, diff --git a/authorize/evaluator/headers_evaluator.go b/authorize/evaluator/headers_evaluator.go index 532d9501c..f0244029e 100644 --- a/authorize/evaluator/headers_evaluator.go +++ b/authorize/evaluator/headers_evaluator.go @@ -62,7 +62,7 @@ var variableSubstitutionFunctionRegoOption = rego.Function2(®o.Function{ ), types.Named("output", types.S), ), -}, func(bctx rego.BuiltinContext, op1 *ast.Term, op2 *ast.Term) (*ast.Term, error) { +}, func(_ rego.BuiltinContext, op1 *ast.Term, op2 *ast.Term) (*ast.Term, error) { inputString, ok := op1.Value.(ast.String) if !ok { return nil, fmt.Errorf("invalid input_string type: %T", op1.Value) @@ -143,18 +143,18 @@ func (e *HeadersEvaluator) Evaluate(ctx context.Context, req *HeadersRequest) (* func (e *HeadersEvaluator) getHeader(vars rego.Vars) http.Header { h := make(http.Header) - m, ok := vars["result"].(map[string]interface{}) + m, ok := vars["result"].(map[string]any) if !ok { return h } - m, ok = m["identity_headers"].(map[string]interface{}) + m, ok = m["identity_headers"].(map[string]any) if !ok { return h } for k := range m { - vs, ok := m[k].([]interface{}) + vs, ok := m[k].([]any) if !ok { continue } diff --git a/authorize/evaluator/headers_evaluator_test.go b/authorize/evaluator/headers_evaluator_test.go index 5f8156c4a..d5036464d 100644 --- a/authorize/evaluator/headers_evaluator_test.go +++ b/authorize/evaluator/headers_evaluator_test.go @@ -62,8 +62,8 @@ func TestNewHeadersRequestFromPolicy_nil(t *testing.T) { func TestHeadersEvaluator(t *testing.T) { t.Parallel() - type A = []interface{} - type M = map[string]interface{} + type A = []any + type M = map[string]any signingKey, err := cryptutil.NewSigningKey() require.NoError(t, err) @@ -114,7 +114,7 @@ func TestHeadersEvaluator(t *testing.T) { // between numeric formats. d := json.NewDecoder(bytes.NewReader(decodeJWSPayload(t, jwtHeader))) d.UseNumber() - var jwtPayloadDecoded map[string]interface{} + var jwtPayloadDecoded map[string]any err = d.Decode(&jwtPayloadDecoded) require.NoError(t, err) diff --git a/authorize/evaluator/policy_evaluator.go b/authorize/evaluator/policy_evaluator.go index b81917c3a..6f2f2e949 100644 --- a/authorize/evaluator/policy_evaluator.go +++ b/authorize/evaluator/policy_evaluator.go @@ -43,7 +43,7 @@ func NewPolicyResponse() *PolicyResponse { type RuleResult struct { Value bool Reasons criteria.Reasons - AdditionalData map[string]interface{} + AdditionalData map[string]any } // NewRuleResult creates a new RuleResult. @@ -51,7 +51,7 @@ func NewRuleResult(value bool, reasons ...criteria.Reason) RuleResult { return RuleResult{ Value: value, Reasons: criteria.NewReasons(reasons...), - AdditionalData: map[string]interface{}{}, + AdditionalData: map[string]any{}, } } @@ -236,7 +236,7 @@ func (e *PolicyEvaluator) evaluateQuery(ctx context.Context, req *PolicyRequest, func (e *PolicyEvaluator) getRuleResult(name string, vars rego.Vars) (result RuleResult) { result = NewRuleResult(false) - m, ok := vars["result"].(map[string]interface{}) + m, ok := vars["result"].(map[string]any) if !ok { return result } @@ -244,10 +244,10 @@ func (e *PolicyEvaluator) getRuleResult(name string, vars rego.Vars) (result Rul switch t := m[name].(type) { case bool: result.Value = t - case []interface{}: + case []any: switch len(t) { case 3: - v, ok := t[2].(map[string]interface{}) + v, ok := t[2].(map[string]any) if ok { for k, vv := range v { result.AdditionalData[k] = vv @@ -256,7 +256,7 @@ func (e *PolicyEvaluator) getRuleResult(name string, vars rego.Vars) (result Rul fallthrough case 2: // fill in the reasons - v, ok := t[1].([]interface{}) + v, ok := t[1].([]any) if ok { for _, vv := range v { result.Reasons.Add(criteria.Reason(fmt.Sprint(vv))) diff --git a/authorize/internal/store/store.go b/authorize/internal/store/store.go index f9f9e08d3..e773ed4c8 100644 --- a/authorize/internal/store/store.go +++ b/authorize/internal/store/store.go @@ -58,7 +58,7 @@ func (s *Store) UpdateSigningKey(signingKey *jose.JSONWebKey) { s.write("/signing_key", signingKey) } -func (s *Store) write(rawPath string, value interface{}) { +func (s *Store) write(rawPath string, value any) { ctx := context.TODO() err := opastorage.Txn(ctx, s.Store, opastorage.WriteParams, func(txn opastorage.Transaction) error { return s.writeTxn(txn, rawPath, value) @@ -69,7 +69,7 @@ func (s *Store) write(rawPath string, value interface{}) { } } -func (s *Store) writeTxn(txn opastorage.Transaction, rawPath string, value interface{}) error { +func (s *Store) writeTxn(txn opastorage.Transaction, rawPath string, value any) error { p, ok := opastorage.ParsePath(rawPath) if !ok { return fmt.Errorf("invalid path") @@ -157,9 +157,9 @@ func (s *Store) GetDataBrokerRecordOption() func(*rego.Rego) { }) } -func toMap(msg proto.Message) map[string]interface{} { +func toMap(msg proto.Message) map[string]any { bs, _ := json.Marshal(msg) - var obj map[string]interface{} + var obj map[string]any _ = json.Unmarshal(bs, &obj) return obj } diff --git a/config/autocert_test.go b/config/autocert_test.go index 9dcfa508c..e6661814a 100644 --- a/config/autocert_test.go +++ b/config/autocert_test.go @@ -64,7 +64,7 @@ func TestAutocertOptions_Validate(t *testing.T) { cleanup func() } tests := map[string]func(t *testing.T) test{ - "ok/custom-ca": func(t *testing.T) test { + "ok/custom-ca": func(_ *testing.T) test { return test{ fields: fields{ CA: "test-ca.example.com/directory", @@ -72,7 +72,7 @@ func TestAutocertOptions_Validate(t *testing.T) { wantErr: false, } }, - "ok/eab": func(t *testing.T) test { + "ok/eab": func(_ *testing.T) test { return test{ fields: fields{ EABKeyID: "keyID", @@ -81,7 +81,7 @@ func TestAutocertOptions_Validate(t *testing.T) { wantErr: false, } }, - "ok/trusted-ca": func(t *testing.T) test { + "ok/trusted-ca": func(_ *testing.T) test { return test{ fields: fields{ TrustedCA: base64.StdEncoding.EncodeToString(certPEM), @@ -103,7 +103,7 @@ func TestAutocertOptions_Validate(t *testing.T) { cleanup: func() { os.Remove(f.Name()) }, } }, - "fail/missing-eab-key": func(t *testing.T) test { + "fail/missing-eab-key": func(_ *testing.T) test { return test{ fields: fields{ EABKeyID: "keyID", @@ -111,7 +111,7 @@ func TestAutocertOptions_Validate(t *testing.T) { wantErr: true, } }, - "fail/missing-eab-key-id": func(t *testing.T) test { + "fail/missing-eab-key-id": func(_ *testing.T) test { return test{ fields: fields{ EABMACKey: "29D7t6-mOuEV5vvBRX0UYF5T7x6fomidhM1kMJco-yw", @@ -119,7 +119,7 @@ func TestAutocertOptions_Validate(t *testing.T) { wantErr: true, } }, - "fail/invalid-mac-key": func(t *testing.T) test { + "fail/invalid-mac-key": func(_ *testing.T) test { return test{ fields: fields{ EABMACKey: ">invalid-base64-url-encoded-mac-key<", @@ -142,7 +142,7 @@ func TestAutocertOptions_Validate(t *testing.T) { cleanup: func() { os.Remove(f.Name()) }, } }, - "fail/trusted-ca-invalid-base64-pem": func(t *testing.T) test { + "fail/trusted-ca-invalid-base64-pem": func(_ *testing.T) test { return test{ fields: fields{ TrustedCA: ">invalid-base-64-data<", @@ -150,7 +150,7 @@ func TestAutocertOptions_Validate(t *testing.T) { wantErr: true, } }, - "fail/trusted-ca-missing-file": func(t *testing.T) test { + "fail/trusted-ca-missing-file": func(_ *testing.T) test { return test{ fields: fields{ TrustedCAFile: "some-non-existing-file", diff --git a/config/codec_type.go b/config/codec_type.go index d450c1738..860b15011 100644 --- a/config/codec_type.go +++ b/config/codec_type.go @@ -57,7 +57,7 @@ func (codecType CodecType) ToEnvoy() envoy_http_connection_manager.HttpConnectio } func decodeCodecTypeHookFunc() mapstructure.DecodeHookFunc { - return func(f, t reflect.Type, data interface{}) (interface{}, error) { + return func(_, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(CodecType("")) { return data, nil } diff --git a/config/config_source_test.go b/config/config_source_test.go index 0ef9ed20e..86b8af406 100644 --- a/config/config_source_test.go +++ b/config/config_source_test.go @@ -38,7 +38,7 @@ func TestFileWatcherSource(t *testing.T) { src := NewFileWatcherSource(ctx, ssrc) var closeOnce sync.Once ch := make(chan struct{}) - src.OnConfigChange(context.Background(), func(ctx context.Context, cfg *Config) { + src.OnConfigChange(context.Background(), func(_ context.Context, _ *Config) { closeOnce.Do(func() { close(ch) }) diff --git a/config/custom.go b/config/custom.go index c08359824..5581edda6 100644 --- a/config/custom.go +++ b/config/custom.go @@ -24,7 +24,7 @@ import ( ) func decodeNullBoolHookFunc() mapstructure.DecodeHookFunc { - return func(f, t reflect.Type, data interface{}) (interface{}, error) { + return func(_, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(null.Bool{}) { return data, nil } @@ -57,7 +57,7 @@ func NewJWTClaimHeaders(claims ...string) JWTClaimHeaders { // UnmarshalJSON unmarshals JSON data into the JWTClaimHeaders. func (hdrs *JWTClaimHeaders) UnmarshalJSON(data []byte) error { - var m map[string]interface{} + var m map[string]any if json.Unmarshal(data, &m) == nil { *hdrs = make(map[string]string) for k, v := range m { @@ -67,7 +67,7 @@ func (hdrs *JWTClaimHeaders) UnmarshalJSON(data []byte) error { return nil } - var a []interface{} + var a []any if json.Unmarshal(data, &a) == nil { var vs []string for _, v := range a { @@ -89,8 +89,8 @@ func (hdrs *JWTClaimHeaders) UnmarshalJSON(data []byte) error { } // UnmarshalYAML uses UnmarshalJSON to unmarshal YAML data into the JWTClaimHeaders. -func (hdrs *JWTClaimHeaders) UnmarshalYAML(unmarshal func(interface{}) error) error { - var i interface{} +func (hdrs *JWTClaimHeaders) UnmarshalYAML(unmarshal func(any) error) error { + var i any err := unmarshal(&i) if err != nil { return err @@ -110,7 +110,7 @@ func (hdrs *JWTClaimHeaders) UnmarshalYAML(unmarshal func(interface{}) error) er } func decodeJWTClaimHeadersHookFunc() mapstructure.DecodeHookFunc { - return func(f, t reflect.Type, data interface{}) (interface{}, error) { + return func(_, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(JWTClaimHeaders{}) { return data, nil } @@ -198,8 +198,8 @@ func (slc *StringSlice) UnmarshalJSON(data []byte) error { // UnmarshalYAML unmarshals a YAML document into the string slice. UnmarshalJSON is // reused as the actual implementation. -func (slc *StringSlice) UnmarshalYAML(unmarshal func(interface{}) error) error { - var i interface{} +func (slc *StringSlice) UnmarshalYAML(unmarshal func(any) error) error { + var i any err := unmarshal(&i) if err != nil { return err @@ -350,8 +350,8 @@ func (ppl *PPLPolicy) UnmarshalJSON(data []byte) error { } // UnmarshalYAML parses YAML into a PPL policy. -func (ppl *PPLPolicy) UnmarshalYAML(unmarshal func(interface{}) error) error { - var i interface{} +func (ppl *PPLPolicy) UnmarshalYAML(unmarshal func(any) error) error { + var i any err := unmarshal(&i) if err != nil { return err @@ -364,7 +364,7 @@ func (ppl *PPLPolicy) UnmarshalYAML(unmarshal func(interface{}) error) error { } func decodePPLPolicyHookFunc() mapstructure.DecodeHookFunc { - return func(f, t reflect.Type, data interface{}) (interface{}, error) { + return func(_, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(&PPLPolicy{}) { return data, nil } @@ -383,7 +383,7 @@ func decodePPLPolicyHookFunc() mapstructure.DecodeHookFunc { // DecodePolicyBase64Hook returns a mapstructure decode hook for base64 data. func DecodePolicyBase64Hook() mapstructure.DecodeHookFunc { - return func(f, t reflect.Type, data interface{}) (interface{}, error) { + return func(_, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf([]Policy{}) { return data, nil } @@ -402,7 +402,7 @@ func DecodePolicyBase64Hook() mapstructure.DecodeHookFunc { return nil, fmt.Errorf("base64 decoding policy data: %w", err) } - var out []map[interface{}]interface{} + var out []map[any]any if err = yaml.Unmarshal(bytes, &out); err != nil { return nil, fmt.Errorf("parsing base64-encoded policy data as yaml: %w", err) } @@ -413,7 +413,7 @@ func DecodePolicyBase64Hook() mapstructure.DecodeHookFunc { // DecodePolicyHookFunc returns a Decode Hook for mapstructure. func DecodePolicyHookFunc() mapstructure.DecodeHookFunc { - return func(f, t reflect.Type, data interface{}) (interface{}, error) { + return func(_, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(Policy{}) { return data, nil } @@ -424,7 +424,7 @@ func DecodePolicyHookFunc() mapstructure.DecodeHookFunc { if err != nil { return nil, err } - ms, ok := mp.(map[string]interface{}) + ms, ok := mp.(map[string]any) if !ok { return nil, errKeysMustBeStrings } @@ -433,8 +433,8 @@ func DecodePolicyHookFunc() mapstructure.DecodeHookFunc { } } -func parsePolicy(src map[string]interface{}) (out map[string]interface{}, err error) { - out = make(map[string]interface{}, len(src)) +func parsePolicy(src map[string]any) (out map[string]any, err error) { + out = make(map[string]any, len(src)) for k, v := range src { if k == toKey { if v, err = parseTo(v); err != nil { @@ -453,7 +453,7 @@ func parsePolicy(src map[string]interface{}) (out map[string]interface{}, err er return out, nil } -func parseTo(raw interface{}) ([]WeightedURL, error) { +func parseTo(raw any) ([]WeightedURL, error) { rawBS, err := json.Marshal(raw) if err != nil { return nil, err @@ -488,7 +488,7 @@ func weightedString(str string) (string, uint32, error) { // parseEnvoyClusterOpts parses src as envoy cluster spec https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/cluster/v3/cluster.proto // on top of some pre-filled default values -func parseEnvoyClusterOpts(src map[string]interface{}) (*envoy_config_cluster_v3.Cluster, error) { +func parseEnvoyClusterOpts(src map[string]any) (*envoy_config_cluster_v3.Cluster, error) { c := new(envoy_config_cluster_v3.Cluster) if err := parseJSONPB(src, c, protoPartial); err != nil { return nil, err @@ -499,7 +499,7 @@ func parseEnvoyClusterOpts(src map[string]interface{}) (*envoy_config_cluster_v3 // parseJSONPB takes an intermediate representation and parses it using protobuf parser // that correctly handles oneof and other data types -func parseJSONPB(src map[string]interface{}, dst proto.Message, opts protojson.UnmarshalOptions) error { +func parseJSONPB(src map[string]any, dst proto.Message, opts protojson.UnmarshalOptions) error { data, err := json.Marshal(src) if err != nil { return err @@ -510,7 +510,7 @@ func parseJSONPB(src map[string]interface{}, dst proto.Message, opts protojson.U // decodeSANMatcherHookFunc returns a decode hook for the SANMatcher type. func decodeSANMatcherHookFunc() mapstructure.DecodeHookFunc { - return func(f, t reflect.Type, data interface{}) (interface{}, error) { + return func(_, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(SANMatcher{}) { return data, nil } @@ -543,11 +543,11 @@ func decodeStringToMapHookFunc() mapstructure.DecodeHookFunc { }) } -// serializable converts mapstructure nested map into map[string]interface{} that is serializable to JSON -func serializable(in interface{}) (interface{}, error) { +// serializable converts mapstructure nested map into map[string]any that is serializable to JSON +func serializable(in any) (any, error) { switch typed := in.(type) { - case map[interface{}]interface{}: - m := make(map[string]interface{}) + case map[any]any: + m := make(map[string]any) for k, v := range typed { kstr, ok := k.(string) if !ok { @@ -560,8 +560,8 @@ func serializable(in interface{}) (interface{}, error) { m[kstr] = val } return m, nil - case []interface{}: - out := make([]interface{}, 0, len(typed)) + case []any: + out := make([]any, 0, len(typed)) for _, elem := range typed { val, err := serializable(elem) if err != nil { diff --git a/config/custom_test.go b/config/custom_test.go index e556c0d65..c829a03b0 100644 --- a/config/custom_test.go +++ b/config/custom_test.go @@ -136,7 +136,7 @@ func TestSerializable(t *testing.T) { data, err := base64.StdEncoding.DecodeString("aGVhbHRoX2NoZWNrOgogIHRpbWVvdXQ6IDVzCiAgaW50ZXJ2YWw6IDYwcwogIGhlYWx0aHlUaHJlc2hvbGQ6IDEKICB1bmhlYWx0aHlUaHJlc2hvbGQ6IDIKICBodHRwX2hlYWx0aF9jaGVjazogCiAgICBob3N0OiAiaHR0cDovL2xvY2FsaG9zdDo4MDgwIgogICAgcGF0aDogIi8iCg==") require.NoError(t, err, "decode") - var mi map[interface{}]interface{} + var mi map[any]any err = yaml.Unmarshal(data, &mi) require.NoError(t, err, "unmarshal") @@ -158,11 +158,11 @@ func TestDecodePPLPolicyHookFunc(t *testing.T) { }) require.NoError(t, err) - err = decoder.Decode(map[string]interface{}{ - "policy": map[string]interface{}{ - "allow": map[string]interface{}{ - "or": []map[string]interface{}{ - {"email": map[string]interface{}{ + err = decoder.Decode(map[string]any{ + "policy": map[string]any{ + "allow": map[string]any{ + "or": []map[string]any{ + {"email": map[string]any{ "is": "user1@example.com", }}, }, diff --git a/config/envoyconfig/bootstrap.go b/config/envoyconfig/bootstrap.go index 720b0c84e..370c54a25 100644 --- a/config/envoyconfig/bootstrap.go +++ b/config/envoyconfig/bootstrap.go @@ -149,7 +149,7 @@ func (b *Builder) BuildBootstrapDynamicResources( // BuildBootstrapLayeredRuntime builds the layered runtime for the envoy bootstrap. func (b *Builder) BuildBootstrapLayeredRuntime() (*envoy_config_bootstrap_v3.LayeredRuntime, error) { - layer, err := structpb.NewStruct(map[string]interface{}{ + layer, err := structpb.NewStruct(map[string]any{ "re2": map[string]any{ "max_program_size": map[string]any{ "error_level": 1024 * 1024, diff --git a/config/envoyconfig/listeners_test.go b/config/envoyconfig/listeners_test.go index 50f866bf5..dec1c0f59 100644 --- a/config/envoyconfig/listeners_test.go +++ b/config/envoyconfig/listeners_test.go @@ -32,7 +32,7 @@ var ( testDataTemplate = template.Must(template.ParseFS(testDataFS, "testdata/*.json")) ) -func testData(t *testing.T, name string, data interface{}) string { +func testData(t *testing.T, name string, data any) string { t.Helper() var buf bytes.Buffer err := testDataTemplate.ExecuteTemplate(&buf, name, data) diff --git a/config/envoyconfig/lua_test.go b/config/envoyconfig/lua_test.go index 8b3f8d7d2..37ce0e75c 100644 --- a/config/envoyconfig/lua_test.go +++ b/config/envoyconfig/lua_test.go @@ -26,11 +26,11 @@ func TestLuaCleanUpstream(t *testing.T) { "x-pomerium-authorization": "JWT", "cookie": "cookieA=aaa_pomerium=123; cookieb=bbb; _pomerium=ey;_pomerium_test1=stillhere ; _pomerium_test2=stillhere", } - metadata := map[string]interface{}{ + metadata := map[string]any{ "remove_pomerium_authorization": true, "remove_pomerium_cookie": "_pomerium", } - dynamicMetadata := map[string]map[string]interface{}{} + dynamicMetadata := map[string]map[string]any{} handle := newLuaResponseHandle(L, headers, metadata, dynamicMetadata) err = L.CallByParam(lua.P{ @@ -59,14 +59,14 @@ func TestLuaRewriteHeaders(t *testing.T) { headers := map[string]string{ "Location": "https://domain-with-dashes:8080/two/some/uri/", } - metadata := map[string]interface{}{ - "rewrite_response_headers": []interface{}{ - map[string]interface{}{ + metadata := map[string]any{ + "rewrite_response_headers": []any{ + map[string]any{ "header": "Location", "prefix": "https://domain-with-dashes:8080/two/", "value": "https://frontend/one/", }, - map[string]interface{}{ + map[string]any{ "header": "SomeOtherHeader", "prefix": "x", "value": "y", @@ -87,8 +87,8 @@ func TestLuaRewriteHeaders(t *testing.T) { func newLuaResponseHandle(L *lua.LState, headers map[string]string, - metadata map[string]interface{}, - dynamicMetadata map[string]map[string]interface{}, + metadata map[string]any, + dynamicMetadata map[string]map[string]any, ) lua.LValue { return newLuaType(L, map[string]lua.LGFunction{ "headers": func(L *lua.LState) int { @@ -145,7 +145,7 @@ func newLuaHeaders(L *lua.LState, headers map[string]string) lua.LValue { return tbl } -func newLuaMetadata(L *lua.LState, metadata map[string]interface{}) lua.LValue { +func newLuaMetadata(L *lua.LState, metadata map[string]any) lua.LValue { return newLuaType(L, map[string]lua.LGFunction{ "get": func(L *lua.LState) int { _ = L.CheckTable(1) @@ -163,7 +163,7 @@ func newLuaMetadata(L *lua.LState, metadata map[string]interface{}) lua.LValue { }) } -func newLuaDynamicMetadata(L *lua.LState, metadata map[string]map[string]interface{}) lua.LValue { +func newLuaDynamicMetadata(L *lua.LState, metadata map[string]map[string]any) lua.LValue { return newLuaType(L, map[string]lua.LGFunction{ "get": func(L *lua.LState) int { _ = L.CheckTable(1) @@ -186,7 +186,7 @@ func newLuaDynamicMetadata(L *lua.LState, metadata map[string]map[string]interfa m, ok := metadata[filterName] if !ok { - m = make(map[string]interface{}) + m = make(map[string]any) metadata[filterName] = m } m[key] = fromLua(L, value) @@ -196,7 +196,7 @@ func newLuaDynamicMetadata(L *lua.LState, metadata map[string]map[string]interfa }) } -func newLuaStreamInfo(L *lua.LState, dynamicMetadata map[string]map[string]interface{}) lua.LValue { +func newLuaStreamInfo(L *lua.LState, dynamicMetadata map[string]map[string]any) lua.LValue { return newLuaType(L, map[string]lua.LGFunction{ "dynamicMetadata": func(L *lua.LState) int { L.Push(newLuaDynamicMetadata(L, dynamicMetadata)) @@ -215,7 +215,7 @@ func newLuaType(L *lua.LState, funcs map[string]lua.LGFunction) lua.LValue { return tbl } -func fromLua(L *lua.LState, v lua.LValue) interface{} { +func fromLua(L *lua.LState, v lua.LValue) any { switch v.Type() { case lua.LTNil: return nil @@ -226,8 +226,8 @@ func fromLua(L *lua.LState, v lua.LValue) interface{} { case lua.LTString: return string(v.(lua.LString)) case lua.LTTable: - a := []interface{}{} - m := map[string]interface{}{} + a := []any{} + m := map[string]any{} v.(*lua.LTable).ForEach(func(key, value lua.LValue) { if key.Type() == lua.LTNumber { a = append(a, fromLua(L, value)) @@ -244,9 +244,9 @@ func fromLua(L *lua.LState, v lua.LValue) interface{} { } } -func toLua(L *lua.LState, obj interface{}) lua.LValue { +func toLua(L *lua.LState, obj any) lua.LValue { // send the object through JSON to remove custom types - var normalized interface{} + var normalized any bs, err := json.Marshal(obj) if err != nil { panic(err) @@ -261,13 +261,13 @@ func toLua(L *lua.LState, obj interface{}) lua.LValue { } switch t := normalized.(type) { - case []interface{}: + case []any: tbl := L.NewTable() for _, v := range t { tbl.Append(toLua(L, v)) } return tbl - case map[string]interface{}: + case map[string]any: tbl := L.NewTable() for k, v := range t { L.SetField(tbl, k, toLua(L, v)) diff --git a/config/envoyconfig/routes.go b/config/envoyconfig/routes.go index bc42535d2..f19e61832 100644 --- a/config/envoyconfig/routes.go +++ b/config/envoyconfig/routes.go @@ -645,7 +645,7 @@ func getRewriteHeadersMetadata(headers []config.RewriteHeader) *structpb.Value { }, } } - var obj interface{} + var obj any bs, _ := json.Marshal(headers) _ = json.Unmarshal(bs, &obj) v, _ := structpb.NewValue(obj) diff --git a/config/http_test.go b/config/http_test.go index 58679cf90..a2beb8e32 100644 --- a/config/http_test.go +++ b/config/http_test.go @@ -18,7 +18,7 @@ func getLocalCertPEM(s *httptest.Server) []byte { } func TestHTTPTransport(t *testing.T) { - s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) defer s.Close() @@ -44,7 +44,7 @@ func TestPolicyHTTPTransport(t *testing.T) { src := NewStaticSource(&Config{Options: &Options{}}) http.DefaultTransport = NewHTTPTransport(src) - s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) defer s.Close() diff --git a/config/layered_test.go b/config/layered_test.go index 97aebbeca..7c4aa3b9f 100644 --- a/config/layered_test.go +++ b/config/layered_test.go @@ -21,7 +21,7 @@ func TestLayeredConfig(t *testing.T) { t.Run("error on initial build", func(t *testing.T) { underlying := config.NewStaticSource(&config.Config{}) - _, err := config.NewLayeredSource(ctx, underlying, func(c *config.Config) error { + _, err := config.NewLayeredSource(ctx, underlying, func(_ *config.Config) error { return errors.New("error") }) require.Error(t, err) @@ -39,7 +39,7 @@ func TestLayeredConfig(t *testing.T) { var dst atomic.Pointer[config.Config] dst.Store(layered.GetConfig()) - layered.OnConfigChange(ctx, func(ctx context.Context, c *config.Config) { + layered.OnConfigChange(ctx, func(_ context.Context, c *config.Config) { dst.Store(c) }) diff --git a/config/metrics_test.go b/config/metrics_test.go index f3efd91ae..eece08d10 100644 --- a/config/metrics_test.go +++ b/config/metrics_test.go @@ -22,7 +22,7 @@ func TestMetricsManager(t *testing.T) { mgr := NewMetricsManager(ctx, src) srv1 := httptest.NewServer(mgr) defer srv1.Close() - srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.Error(w, "ERROR", http.StatusInternalServerError) })) defer srv2.Close() diff --git a/config/options.go b/config/options.go index 2bc3e7ef9..2784cf23f 100644 --- a/config/options.go +++ b/config/options.go @@ -474,7 +474,7 @@ func (o *Options) parsePolicy() error { return nil } -func (o *Options) viperSet(key string, value interface{}) { +func (o *Options) viperSet(key string, value any) { o.viper.Set(key, value) } diff --git a/config/options_test.go b/config/options_test.go index dd1b3e389..61ca9191d 100644 --- a/config/options_test.go +++ b/config/options_test.go @@ -205,7 +205,7 @@ func Test_parseHeaders(t *testing.T) { name string want map[string]string envHeaders string - viperHeaders interface{} + viperHeaders any wantErr bool }{ { @@ -513,7 +513,7 @@ func Test_AutoCertOptionsFromEnvVar(t *testing.T) { } tests := map[string]func(t *testing.T) test{ - "ok/simple": func(t *testing.T) test { + "ok/simple": func(_ *testing.T) test { envs := map[string]string{ "AUTOCERT": "true", "AUTOCERT_DIR": "/test", diff --git a/config/policy_ppl_test.go b/config/policy_ppl_test.go index adaaac64d..37cd322fa 100644 --- a/config/policy_ppl_test.go +++ b/config/policy_ppl_test.go @@ -17,21 +17,21 @@ func TestPolicy_ToPPL(t *testing.T) { AllowAnyAuthenticatedUser: true, AllowedDomains: []string{"a.example.com", "b.example.com"}, AllowedUsers: []string{"user1", "user2"}, - AllowedIDPClaims: map[string][]interface{}{ + AllowedIDPClaims: map[string][]any{ "family_name": {"Smith", "Jones"}, }, SubPolicies: []SubPolicy{ { AllowedDomains: []string{"c.example.com", "d.example.com"}, AllowedUsers: []string{"user3", "user4"}, - AllowedIDPClaims: map[string][]interface{}{ + AllowedIDPClaims: map[string][]any{ "given_name": {"John"}, }, }, { AllowedDomains: []string{"e.example.com"}, AllowedUsers: []string{"user5"}, - AllowedIDPClaims: map[string][]interface{}{ + AllowedIDPClaims: map[string][]any{ "timezone": {"EST"}, }, }, diff --git a/config/trace_test.go b/config/trace_test.go index d20c0a420..af87ac955 100644 --- a/config/trace_test.go +++ b/config/trace_test.go @@ -102,7 +102,7 @@ func TestTraceManager(t *testing.T) { incoming := make(chan Request, 100) - h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { var objs []struct { Name string } diff --git a/databroker/databroker_test.go b/databroker/databroker_test.go index 64b841449..04b774cb4 100644 --- a/databroker/databroker_test.go +++ b/databroker/databroker_test.go @@ -67,7 +67,7 @@ func TestServerSync(t *testing.T) { serverVersion = res.GetServerVersion() } - t.Run("Sync ok", func(t *testing.T) { + t.Run("Sync ok", func(_ *testing.T) { client, _ := c.Sync(ctx, &databroker.SyncRequest{ ServerVersion: serverVersion, }) diff --git a/integration/authorization_test.go b/integration/authorization_test.go index 9379f6f79..8e49c472d 100644 --- a/integration/authorization_test.go +++ b/integration/authorization_test.go @@ -67,7 +67,7 @@ func TestAuthorization(t *testing.T) { } } -func assertDeniedAccess(t *testing.T, res *http.Response, msgAndArgs ...interface{}) bool { +func assertDeniedAccess(t *testing.T, res *http.Response, msgAndArgs ...any) bool { return assert.Condition(t, func() bool { return res.StatusCode == http.StatusForbidden || res.StatusCode == http.StatusUnauthorized }, msgAndArgs...) diff --git a/integration/cmd/pomerium-integration-tests/main.go b/integration/cmd/pomerium-integration-tests/main.go index 7a0376ad7..29ab66e7c 100644 --- a/integration/cmd/pomerium-integration-tests/main.go +++ b/integration/cmd/pomerium-integration-tests/main.go @@ -20,13 +20,13 @@ import ( func main() { generateCmd := &ffcli.Command{ Name: "generate-configuration", - Exec: func(ctx context.Context, args []string) error { + Exec: func(ctx context.Context, _ []string) error { return runGenerateConfiguration(ctx) }, } rootCmd := &ffcli.Command{ Subcommands: []*ffcli.Command{generateCmd}, - Exec: func(ctx context.Context, args []string) error { + Exec: func(_ context.Context, _ []string) error { return flag.ErrHelp }, } diff --git a/integration/main_test.go b/integration/main_test.go index 0ccd20284..d7b9f5c88 100644 --- a/integration/main_test.go +++ b/integration/main_test.go @@ -97,7 +97,7 @@ func getClient(t testing.TB) *http.Client { } return &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, Transport: getTransport(t), diff --git a/integration/policy_test.go b/integration/policy_test.go index ab74a47e0..c29a156d3 100644 --- a/integration/policy_test.go +++ b/integration/policy_test.go @@ -514,11 +514,11 @@ func TestPomeriumJWT(t *testing.T) { require.NoError(t, err) defer res.Body.Close() - var m map[string]interface{} + var m map[string]any err = json.NewDecoder(res.Body).Decode(&m) require.NoError(t, err) - headers, ok := m["headers"].(map[string]interface{}) + headers, ok := m["headers"].(map[string]any) require.True(t, ok) headerJWT, ok := headers["x-pomerium-jwt-assertion"].(string) require.True(t, ok) @@ -554,7 +554,7 @@ func TestPomeriumJWT(t *testing.T) { assert.Equal(t, p, p2) } -func rawJWTPayload(t *testing.T, jwt string) map[string]interface{} { +func rawJWTPayload(t *testing.T, jwt string) map[string]any { t.Helper() s := strings.Split(jwt, ".") require.Equal(t, 3, len(s), "unexpected JWT format") @@ -562,7 +562,7 @@ func rawJWTPayload(t *testing.T, jwt string) map[string]interface{} { require.NoError(t, err, "JWT payload could not be decoded") d := json.NewDecoder(bytes.NewReader(payload)) d.UseNumber() - var decoded map[string]interface{} + var decoded map[string]any err = d.Decode(&decoded) require.NoError(t, err, "JWT payload could not be deserialized") return decoded diff --git a/internal/authenticateflow/authenticateflow.go b/internal/authenticateflow/authenticateflow.go index 67b78e972..7c12c4ac5 100644 --- a/internal/authenticateflow/authenticateflow.go +++ b/internal/authenticateflow/authenticateflow.go @@ -15,7 +15,7 @@ import ( var outboundGRPCConnection = new(grpc.CachedOutboundGRPClientConn) -func populateUserFromClaims(u *user.User, claims map[string]interface{}) { +func populateUserFromClaims(u *user.User, claims map[string]any) { if v, ok := claims["name"]; ok { u.Name = fmt.Sprint(v) } diff --git a/internal/authenticateflow/stateful_test.go b/internal/authenticateflow/stateful_test.go index 5ab1ead7a..eeb340fc6 100644 --- a/internal/authenticateflow/stateful_test.go +++ b/internal/authenticateflow/stateful_test.go @@ -363,7 +363,7 @@ type protoEqualMatcher struct { expected proto.Message } -func (m protoEqualMatcher) Matches(x interface{}) bool { +func (m protoEqualMatcher) Matches(x any) bool { p, ok := x.(proto.Message) if !ok { return false diff --git a/internal/autocert/manager.go b/internal/autocert/manager.go index 4b3285542..60029d217 100644 --- a/internal/autocert/manager.go +++ b/internal/autocert/manager.go @@ -93,7 +93,7 @@ func newManager(ctx context.Context, return nil, err } mgr.certmagic = certmagic.New(certmagic.NewCache(certmagic.CacheOptions{ - GetConfigForCert: func(c certmagic.Certificate) (*certmagic.Config, error) { + GetConfigForCert: func(_ certmagic.Certificate) (*certmagic.Config, error) { return mgr.certmagic, nil }, Logger: logger, diff --git a/internal/autocert/manager_test.go b/internal/autocert/manager_test.go index 40374b103..b3b0cd47a 100644 --- a/internal/autocert/manager_test.go +++ b/internal/autocert/manager_test.go @@ -37,7 +37,7 @@ import ( "github.com/pomerium/pomerium/internal/log" ) -type M = map[string]interface{} +type M = map[string]any type testCA struct { key *ecdsa.PrivateKey @@ -94,7 +94,7 @@ func newMockACME(ca *testCA, srv *httptest.Server) http.Handler { r := chi.NewRouter() r.Use(middleware.Logger) - r.Get("/acme/directory", func(w http.ResponseWriter, r *http.Request) { + r.Get("/acme/directory", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(M{ "keyChange": srv.URL + "/acme/key-change", @@ -104,11 +104,11 @@ func newMockACME(ca *testCA, srv *httptest.Server) http.Handler { "revokeCert": srv.URL + "/acme/revoke-cert", }) }) - r.Head("/acme/new-nonce", func(w http.ResponseWriter, r *http.Request) { + r.Head("/acme/new-nonce", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Replay-Nonce", "NONCE") w.WriteHeader(http.StatusOK) }) - r.Post("/acme/new-acct", func(w http.ResponseWriter, r *http.Request) { + r.Post("/acme/new-acct", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Replay-Nonce", "NONCE") w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) @@ -188,13 +188,13 @@ func newMockACME(ca *testCA, srv *httptest.Server) http.Handler { "certificate": srv.URL + "/acme/certificate", }) }) - r.Post("/acme/certificate", func(w http.ResponseWriter, r *http.Request) { + r.Post("/acme/certificate", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Replay-Nonce", "NONCE") w.Header().Set("Content-Type", "application/pem-certificate-chain") w.WriteHeader(http.StatusOK) _, _ = w.Write(certBuffer.Bytes()) }) - r.Get("/certs/ca", func(w http.ResponseWriter, r *http.Request) { + r.Get("/certs/ca", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/pkix-cert") w.WriteHeader(http.StatusOK) _, _ = w.Write(ca.cert.Raw) @@ -326,7 +326,7 @@ func TestRedirect(t *testing.T) { } client := &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }, } @@ -358,7 +358,7 @@ func waitFor(addr string) error { return err } -func readJWSPayload(r io.Reader, dst interface{}) { +func readJWSPayload(r io.Reader, dst any) { var req struct { Protected string `json:"protected"` Payload string `json:"payload"` @@ -388,7 +388,7 @@ func Test_configureCertificateAuthority(t *testing.T) { wantErr bool } tests := map[string]func(t *testing.T) test{ - "ok/default": func(t *testing.T) test { + "ok/default": func(_ *testing.T) test { return test{ args: args{ acmeMgr: newACMEIssuer(), @@ -403,7 +403,7 @@ func Test_configureCertificateAuthority(t *testing.T) { wantErr: false, } }, - "ok/staging": func(t *testing.T) test { + "ok/staging": func(_ *testing.T) test { return test{ args: args{ acmeMgr: newACMEIssuer(), @@ -420,7 +420,7 @@ func Test_configureCertificateAuthority(t *testing.T) { wantErr: false, } }, - "ok/custom-ca-staging": func(t *testing.T) test { + "ok/custom-ca-staging": func(_ *testing.T) test { return test{ args: args{ acmeMgr: newACMEIssuer(), @@ -464,7 +464,7 @@ func Test_configureExternalAccountBinding(t *testing.T) { wantErr bool } tests := map[string]func(t *testing.T) test{ - "ok": func(t *testing.T) test { + "ok": func(_ *testing.T) test { return test{ args: args{ acmeMgr: newACMEIssuer(), @@ -484,7 +484,7 @@ func Test_configureExternalAccountBinding(t *testing.T) { wantErr: false, } }, - "fail/error-decoding-mac-key": func(t *testing.T) test { + "fail/error-decoding-mac-key": func(_ *testing.T) test { return test{ args: args{ acmeMgr: newACMEIssuer(), diff --git a/internal/autocert/storage.go b/internal/autocert/storage.go index 310c0783a..dccd83379 100644 --- a/internal/autocert/storage.go +++ b/internal/autocert/storage.go @@ -69,7 +69,7 @@ func GetCertMagicStorage(ctx context.Context, dst string) (certmagic.Storage, er prefix = strings.TrimPrefix(match[3][1:], "/") options = append(options, config.WithRegion("us-east-1"), - config.WithEndpointResolver(aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) { + config.WithEndpointResolver(aws.EndpointResolverFunc(func(_, _ string) (aws.Endpoint, error) { return aws.Endpoint{ PartitionID: "aws", URL: "http://" + host, diff --git a/internal/controlplane/events_test.go b/internal/controlplane/events_test.go index 9485adde4..811944ef9 100644 --- a/internal/controlplane/events_test.go +++ b/internal/controlplane/events_test.go @@ -51,11 +51,11 @@ func TestEvents(t *testing.T) { grpcSrv := grpc.NewServer() databrokerpb.RegisterDataBrokerServiceServer(grpcSrv, &mockDataBrokerServer{ - put: func(ctx context.Context, req *databrokerpb.PutRequest) (*databrokerpb.PutResponse, error) { + put: func(_ context.Context, req *databrokerpb.PutRequest) (*databrokerpb.PutResponse, error) { putRequest = req return new(databrokerpb.PutResponse), nil }, - setOptions: func(ctx context.Context, req *databrokerpb.SetOptionsRequest) (*databrokerpb.SetOptionsResponse, error) { + setOptions: func(_ context.Context, req *databrokerpb.SetOptionsRequest) (*databrokerpb.SetOptionsResponse, error) { setOptionsRequest = req return new(databrokerpb.SetOptionsResponse), nil }, diff --git a/internal/controlplane/xdsmgr/xdsmgr.go b/internal/controlplane/xdsmgr/xdsmgr.go index 11c132323..4e95f0a06 100644 --- a/internal/controlplane/xdsmgr/xdsmgr.go +++ b/internal/controlplane/xdsmgr/xdsmgr.go @@ -21,7 +21,7 @@ type streamState struct { unsubscribedResources map[string]struct{} } -var onHandleDeltaRequest = func(state *streamState) {} +var onHandleDeltaRequest = func(_ *streamState) {} // A Manager manages xDS resources. type Manager struct { @@ -51,7 +51,7 @@ func (mgr *Manager) DeltaAggregatedResources( stateByTypeURL := map[string]*streamState{} - getDeltaResponse := func(ctx context.Context, typeURL string) *envoy_service_discovery_v3.DeltaDiscoveryResponse { + getDeltaResponse := func(_ context.Context, typeURL string) *envoy_service_discovery_v3.DeltaDiscoveryResponse { mgr.mu.Lock() defer mgr.mu.Unlock() diff --git a/internal/controlplane/xdsmgr/xdsmgr_test.go b/internal/controlplane/xdsmgr/xdsmgr_test.go index cd0fa8fe8..3e2504771 100644 --- a/internal/controlplane/xdsmgr/xdsmgr_test.go +++ b/internal/controlplane/xdsmgr/xdsmgr_test.go @@ -27,7 +27,7 @@ func TestManager(t *testing.T) { stateChanged := signal.New() origOnHandleDeltaRequest := onHandleDeltaRequest defer func() { onHandleDeltaRequest = origOnHandleDeltaRequest }() - onHandleDeltaRequest = func(state *streamState) { + onHandleDeltaRequest = func(_ *streamState) { stateChanged.Broadcast(ctx) } @@ -44,7 +44,7 @@ func TestManager(t *testing.T) { cc, err := grpc.Dial("test", grpc.WithInsecure(), - grpc.WithContextDialer(func(ctx context.Context, target string) (net.Conn, error) { + grpc.WithContextDialer(func(_ context.Context, _ string) (net.Conn, error) { return li.Dial() })) if !assert.NoError(t, err) { diff --git a/internal/enabler/enabler_test.go b/internal/enabler/enabler_test.go index 34c74dc8c..91004097f 100644 --- a/internal/enabler/enabler_test.go +++ b/internal/enabler/enabler_test.go @@ -18,7 +18,7 @@ func TestEnabler(t *testing.T) { t.Run("enabled immediately", func(t *testing.T) { t.Parallel() - e := enabler.New("test", enabler.HandlerFunc(func(ctx context.Context) error { + e := enabler.New("test", enabler.HandlerFunc(func(_ context.Context) error { return errors.New("ERROR") }), true) err := e.Run(context.Background()) @@ -27,7 +27,7 @@ func TestEnabler(t *testing.T) { t.Run("enabled delayed", func(t *testing.T) { t.Parallel() - e := enabler.New("test", enabler.HandlerFunc(func(ctx context.Context) error { + e := enabler.New("test", enabler.HandlerFunc(func(_ context.Context) error { return errors.New("ERROR") }), false) time.AfterFunc(time.Millisecond*10, e.Enable) diff --git a/internal/encoding/base64.go b/internal/encoding/base64.go index 71a9c0711..8c84b548a 100644 --- a/internal/encoding/base64.go +++ b/internal/encoding/base64.go @@ -7,7 +7,7 @@ import ( ) // DecodeBase64OrJSON decodes a JSON string that can optionally be base64 encoded. -func DecodeBase64OrJSON(in string, out interface{}) error { +func DecodeBase64OrJSON(in string, out any) error { in = strings.TrimSpace(in) // the data can be base64 encoded diff --git a/internal/encoding/econding.go b/internal/encoding/econding.go index 23cb1dacf..fa0eed024 100644 --- a/internal/encoding/econding.go +++ b/internal/encoding/econding.go @@ -10,10 +10,10 @@ type MarshalUnmarshaler interface { // Marshaler encodes a struct into a set of bytes. type Marshaler interface { - Marshal(interface{}) ([]byte, error) + Marshal(any) ([]byte, error) } // Unmarshaler decodes a set of bytes and returns a struct. type Unmarshaler interface { - Unmarshal([]byte, interface{}) error + Unmarshal([]byte, any) error } diff --git a/internal/encoding/jws/jws.go b/internal/encoding/jws/jws.go index eaa0ad573..8f153f138 100644 --- a/internal/encoding/jws/jws.go +++ b/internal/encoding/jws/jws.go @@ -14,7 +14,7 @@ import ( type JSONWebSigner struct { Signer jose.Signer - key interface{} + key any } // NewHS256Signer creates a SHA256 JWT signer from a 32 byte key. @@ -28,13 +28,13 @@ func NewHS256Signer(key []byte) (encoding.MarshalUnmarshaler, error) { } // Marshal signs, and serializes a JWT. -func (c *JSONWebSigner) Marshal(x interface{}) ([]byte, error) { +func (c *JSONWebSigner) Marshal(x any) ([]byte, error) { s, err := jwt.Signed(c.Signer).Claims(x).CompactSerialize() return []byte(s), err } // Unmarshal parses and validates a signed JWT. -func (c *JSONWebSigner) Unmarshal(value []byte, s interface{}) error { +func (c *JSONWebSigner) Unmarshal(value []byte, s any) error { tok, err := jwt.ParseSigned(string(value)) if err != nil { return err diff --git a/internal/handlers/signedout.go b/internal/handlers/signedout.go index 818e6f049..4a6d6c798 100644 --- a/internal/handlers/signedout.go +++ b/internal/handlers/signedout.go @@ -13,8 +13,8 @@ type SignedOutData struct { } // ToJSON converts the data into a JSON map. -func (data SignedOutData) ToJSON() map[string]interface{} { - m := map[string]interface{}{} +func (data SignedOutData) ToJSON() map[string]any { + m := map[string]any{} httputil.AddBrandingOptionsToMap(m, data.BrandingOptions) return m } diff --git a/internal/handlers/signout.go b/internal/handlers/signout.go index 14cb109ef..c12ed23bb 100644 --- a/internal/handlers/signout.go +++ b/internal/handlers/signout.go @@ -14,8 +14,8 @@ type SignOutConfirmData struct { } // ToJSON converts the data into a JSON map. -func (data SignOutConfirmData) ToJSON() map[string]interface{} { - m := map[string]interface{}{ +func (data SignOutConfirmData) ToJSON() map[string]any { + m := map[string]any{ "url": data.URL, } httputil.AddBrandingOptionsToMap(m, data.BrandingOptions) diff --git a/internal/handlers/webauthn/webauthn.go b/internal/handlers/webauthn/webauthn.go index 468556c2f..455bedba3 100644 --- a/internal/handlers/webauthn/webauthn.go +++ b/internal/handlers/webauthn/webauthn.go @@ -396,7 +396,7 @@ func (h *Handler) handleView(w http.ResponseWriter, r *http.Request, state *Stat return err } - m := map[string]interface{}{ + m := map[string]any{ "creationOptions": creationOptions, "requestOptions": requestOptions, "selfUrl": r.URL.String(), diff --git a/internal/hashutil/hashutil.go b/internal/hashutil/hashutil.go index 15d0de0c5..d5f0a335d 100644 --- a/internal/hashutil/hashutil.go +++ b/internal/hashutil/hashutil.go @@ -11,7 +11,7 @@ import ( // MustHash returns the xxhash of an arbitrary value or struct. Returns 0 // on error. // NOT SUITABLE FOR CRYTOGRAPHIC HASHING. -func MustHash(v interface{}) uint64 { +func MustHash(v any) uint64 { hash, err := Hash(v) if err != nil { hash = 0 @@ -21,7 +21,7 @@ func MustHash(v interface{}) uint64 { // Hash returns the xxhash of an arbitrary value or struct. // NOT SUITABLE FOR CRYTOGRAPHIC HASHING. -func Hash(v interface{}) (uint64, error) { +func Hash(v any) (uint64, error) { opts := &hashstructure.HashOptions{ Hasher: xxhash.New(), } diff --git a/internal/hashutil/hashutil_test.go b/internal/hashutil/hashutil_test.go index 64aa3c00f..30d67d988 100644 --- a/internal/hashutil/hashutil_test.go +++ b/internal/hashutil/hashutil_test.go @@ -11,7 +11,7 @@ func TestHash(t *testing.T) { t.Parallel() tests := []struct { name string - v interface{} + v any want uint64 wantErr bool }{ diff --git a/internal/httputil/client.go b/internal/httputil/client.go index 73d3cd1c5..d489e7b33 100644 --- a/internal/httputil/client.go +++ b/internal/httputil/client.go @@ -91,7 +91,7 @@ func getDefaultClient() *httpClient { } // Do provides a simple helper interface to make HTTP requests -func Do(ctx context.Context, method, endpoint, userAgent string, headers map[string]string, params url.Values, response interface{}) error { +func Do(ctx context.Context, method, endpoint, userAgent string, headers map[string]string, params url.Values, response any) error { var body io.Reader switch method { case http.MethodPost: diff --git a/internal/httputil/cookie_test.go b/internal/httputil/cookie_test.go index 12b64634b..e4589a601 100644 --- a/internal/httputil/cookie_test.go +++ b/internal/httputil/cookie_test.go @@ -18,14 +18,14 @@ func TestCookieChunker(t *testing.T) { t.Parallel() cc := NewCookieChunker(WithCookieChunkerChunkSize(16)) - srv1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { assert.NoError(t, cc.SetCookie(w, &http.Cookie{ Name: "example", Value: strings.Repeat("x", 77), })) })) defer srv1.Close() - srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv2 := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { cookie, err := cc.LoadCookie(r, "example") if assert.NoError(t, err) { assert.Equal(t, &http.Cookie{ @@ -57,7 +57,7 @@ func TestCookieChunker(t *testing.T) { t.Parallel() cc := NewCookieChunker(WithCookieChunkerChunkSize(2), WithCookieChunkerMaxChunks(2)) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { assert.Error(t, cc.SetCookie(w, &http.Cookie{ Name: "example", Value: strings.Repeat("x", 1024), @@ -71,7 +71,7 @@ func TestCookieChunker(t *testing.T) { t.Parallel() cc1 := NewCookieChunker(WithCookieChunkerChunkSize(64)) - srv1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { assert.NoError(t, cc1.SetCookie(w, &http.Cookie{ Name: "example", Value: strings.Repeat("x", 1024), @@ -80,7 +80,7 @@ func TestCookieChunker(t *testing.T) { defer srv1.Close() cc2 := NewCookieChunker(WithCookieChunkerChunkSize(64), WithCookieChunkerMaxChunks(2)) - srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv2 := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { cookie, err := cc2.LoadCookie(r, "example") assert.Error(t, err) assert.Nil(t, cookie) diff --git a/internal/httputil/handlers.go b/internal/httputil/handlers.go index 03826de57..aa4d68ae3 100644 --- a/internal/httputil/handlers.go +++ b/internal/httputil/handlers.go @@ -19,7 +19,7 @@ func Redirect(w http.ResponseWriter, r *http.Request, url string, code int) { // It does not otherwise end the request; the caller should ensure no further // writes are done to w. // The error message should be application/json. -func RenderJSON(w http.ResponseWriter, code int, v interface{}) { +func RenderJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json") w.Header().Set("X-Content-Type-Options", "nosniff") b := new(bytes.Buffer) diff --git a/internal/httputil/handlers_test.go b/internal/httputil/handlers_test.go index 183085aa8..5a2cc72e6 100644 --- a/internal/httputil/handlers_test.go +++ b/internal/httputil/handlers_test.go @@ -46,8 +46,8 @@ func TestHandlerFunc_ServeHTTP(t *testing.T) { f HandlerFunc wantBody string }{ - {"good http error", func(w http.ResponseWriter, r *http.Request) error { return NewError(404, errors.New("404")) }, "{\"Status\":404}\n"}, - {"good std error", func(w http.ResponseWriter, r *http.Request) error { return errors.New("404") }, "{\"Status\":500}\n"}, + {"good http error", func(_ http.ResponseWriter, _ *http.Request) error { return NewError(404, errors.New("404")) }, "{\"Status\":404}\n"}, + {"good std error", func(_ http.ResponseWriter, _ *http.Request) error { return errors.New("404") }, "{\"Status\":500}\n"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -66,7 +66,7 @@ func TestRenderJSON(t *testing.T) { tests := []struct { name string code int - v interface{} + v any wantBody string wantCode int }{ @@ -88,7 +88,7 @@ func TestRenderJSON(t *testing.T) { { "map", http.StatusOK, - map[string]interface{}{ + map[string]any{ "C": 1, // notice order does not matter "A": "A", "B": "B", @@ -99,7 +99,7 @@ func TestRenderJSON(t *testing.T) { { "bad!", http.StatusOK, - map[string]interface{}{ + map[string]any{ "BAD BOI": math.Inf(1), }, `{"error":"json: unsupported value: +Inf"}`, http.StatusInternalServerError, diff --git a/internal/httputil/reproxy/reproxy_test.go b/internal/httputil/reproxy/reproxy_test.go index 28d92504b..56e1c74f0 100644 --- a/internal/httputil/reproxy/reproxy_test.go +++ b/internal/httputil/reproxy/reproxy_test.go @@ -16,7 +16,7 @@ import ( ) func TestMiddleware(t *testing.T) { - next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "NEXT") }) @@ -38,7 +38,7 @@ func TestMiddleware(t *testing.T) { t.Run("proxy", func(t *testing.T) { h := New() - srv1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "SERVER1") })) defer srv1.Close() diff --git a/internal/httputil/server_test.go b/internal/httputil/server_test.go index da4df3f3a..8784b7b09 100644 --- a/internal/httputil/server_test.go +++ b/internal/httputil/server_test.go @@ -35,7 +35,7 @@ func TestNewServer(t *testing.T) { Addr: ":0", Insecure: true, }, - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "Hello, http") }), false, @@ -45,7 +45,7 @@ func TestNewServer(t *testing.T) { &ServerOptions{ Addr: ":0", }, - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "Hello, http") }), true, @@ -55,7 +55,7 @@ func TestNewServer(t *testing.T) { &ServerOptions{ Insecure: true, }, - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "Hello, http") }), false, @@ -63,7 +63,7 @@ func TestNewServer(t *testing.T) { { "empty handler", nil, - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "Hello, http") }), true, @@ -73,7 +73,7 @@ func TestNewServer(t *testing.T) { &ServerOptions{ Addr: ":65536", Insecure: true, - }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + }, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "Hello, http") }), true, @@ -83,7 +83,7 @@ func TestNewServer(t *testing.T) { &ServerOptions{ TLSConfig: &tls.Config{}, }, - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "Hello, http") }), false, diff --git a/internal/identity/claims.go b/internal/identity/claims.go index 1d54de16c..df1e1f253 100644 --- a/internal/identity/claims.go +++ b/internal/identity/claims.go @@ -23,13 +23,13 @@ func (claims *SessionClaims) SetRawIDToken(rawIDToken string) { } // Claims are JWT claims. -type Claims map[string]interface{} +type Claims map[string]any // NewClaimsFromRaw creates a new Claims map from a map of raw messages. func NewClaimsFromRaw(raw map[string]json.RawMessage) Claims { claims := make(Claims) for k, rawv := range raw { - var v interface{} + var v any if err := json.Unmarshal(rawv, &v); err == nil { claims[k] = v } @@ -43,7 +43,7 @@ func (claims *Claims) UnmarshalJSON(data []byte) error { *claims = make(Claims) } - var m map[string]interface{} + var m map[string]any err := json.Unmarshal(data, &m) if err != nil { return err @@ -55,7 +55,7 @@ func (claims *Claims) UnmarshalJSON(data []byte) error { } // Claims takes the claims data and fills v. -func (claims Claims) Claims(v interface{}) error { +func (claims Claims) Claims(v any) error { bs, err := json.Marshal(claims) if err != nil { return err @@ -81,13 +81,13 @@ func (claims Claims) Flatten() FlattenedClaims { flattened[k+"."+sk] = sv } case reflect.Slice: - slc := make([]interface{}, rv.Len()) + slc := make([]any, rv.Len()) for i := 0; i < rv.Len(); i++ { slc[i] = rv.Index(i).Interface() } flattened[k] = slc default: - flattened[k] = []interface{}{v} + flattened[k] = []any{v} } } return flattened @@ -103,7 +103,7 @@ func (claims Claims) ToAnyMap() map[string]*anypb.Any { } // FlattenedClaims are a set claims flattened into a single-level map. -type FlattenedClaims map[string][]interface{} +type FlattenedClaims map[string][]any // NewFlattenedClaimsFromPB creates a new FlattenedClaims from the protobuf struct type. func NewFlattenedClaimsFromPB(m map[string]*structpb.ListValue) FlattenedClaims { diff --git a/internal/identity/manager/manager.go b/internal/identity/manager/manager.go index 365ce5d2e..f7bedca6c 100644 --- a/internal/identity/manager/manager.go +++ b/internal/identity/manager/manager.go @@ -32,7 +32,7 @@ import ( type Authenticator interface { Refresh(context.Context, *oauth2.Token, identity.State) (*oauth2.Token, error) Revoke(context.Context, *oauth2.Token) error - UpdateUserInfo(context.Context, *oauth2.Token, interface{}) error + UpdateUserInfo(context.Context, *oauth2.Token, any) error } // A Manager refreshes identity information using session and user data. diff --git a/internal/identity/manager/schedulers_test.go b/internal/identity/manager/schedulers_test.go index 7a6d02b62..c9970fd24 100644 --- a/internal/identity/manager/schedulers_test.go +++ b/internal/identity/manager/schedulers_test.go @@ -24,7 +24,7 @@ func TestRefreshSessionScheduler(t *testing.T) { time.Now, sessionRefreshGracePeriod, sessionRefreshCoolOffDuration, - func(ctx context.Context, sesionID string) { + func(_ context.Context, _ string) { calls.Append(time.Now()) }, "S1", @@ -51,7 +51,7 @@ func TestUpdateUserInfoScheduler(t *testing.T) { ctx := context.Background() userUpdateInfoInterval := 100 * time.Millisecond - uuis := newUpdateUserInfoScheduler(ctx, userUpdateInfoInterval, func(ctx context.Context, userID string) { + uuis := newUpdateUserInfoScheduler(ctx, userUpdateInfoInterval, func(_ context.Context, _ string) { calls.Append(time.Now()) }, "U1") t.Cleanup(uuis.Stop) diff --git a/internal/identity/mock_provider.go b/internal/identity/mock_provider.go index 49075c96f..04e744a91 100644 --- a/internal/identity/mock_provider.go +++ b/internal/identity/mock_provider.go @@ -37,7 +37,7 @@ func (mp MockProvider) Revoke(_ context.Context, _ *oauth2.Token) error { } // UpdateUserInfo is a mocked providers function. -func (mp MockProvider) UpdateUserInfo(_ context.Context, _ *oauth2.Token, _ interface{}) error { +func (mp MockProvider) UpdateUserInfo(_ context.Context, _ *oauth2.Token, _ any) error { return mp.UpdateUserInfoError } diff --git a/internal/identity/oauth/apple/apple.go b/internal/identity/oauth/apple/apple.go index 0ba5c0133..fe0d0b4ac 100644 --- a/internal/identity/oauth/apple/apple.go +++ b/internal/identity/oauth/apple/apple.go @@ -143,7 +143,7 @@ func (p *Provider) Revoke(ctx context.Context, t *oauth2.Token) error { } // UpdateUserInfo gets claims from the oauth token. -func (p *Provider) UpdateUserInfo(_ context.Context, t *oauth2.Token, v interface{}) error { +func (p *Provider) UpdateUserInfo(_ context.Context, t *oauth2.Token, v any) error { rawIDToken, ok := t.Extra("id_token").(string) if !ok { return nil diff --git a/internal/identity/oauth/github/github.go b/internal/identity/oauth/github/github.go index cfd9adf9d..64557a822 100644 --- a/internal/identity/oauth/github/github.go +++ b/internal/identity/oauth/github/github.go @@ -109,7 +109,7 @@ func (p *Provider) Authenticate(ctx context.Context, code string, v identity.Sta // UpdateUserInfo will get the user information from github and also retrieve the user's team(s) // // https://developer.github.com/v3/users/#get-the-authenticated-user -func (p *Provider) UpdateUserInfo(ctx context.Context, t *oauth2.Token, v interface{}) error { +func (p *Provider) UpdateUserInfo(ctx context.Context, t *oauth2.Token, v any) error { err := p.userInfo(ctx, t, v) if err != nil { return fmt.Errorf("github: could not retrieve user info %w", err) @@ -134,7 +134,7 @@ func (p *Provider) Refresh(_ context.Context, t *oauth2.Token, _ identity.State) // // https://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user // https://developer.github.com/v3/auth/ -func (p *Provider) userEmail(ctx context.Context, t *oauth2.Token, v interface{}) error { +func (p *Provider) userEmail(ctx context.Context, t *oauth2.Token, v any) error { // response represents the github user email // https://developer.github.com/v3/users/emails/#response var response []struct { @@ -167,7 +167,7 @@ func (p *Provider) userEmail(ctx context.Context, t *oauth2.Token, v interface{} return json.Unmarshal(b, v) } -func (p *Provider) userInfo(ctx context.Context, t *oauth2.Token, v interface{}) error { +func (p *Provider) userInfo(ctx context.Context, t *oauth2.Token, v any) error { var response struct { ID int `json:"id"` Login string `json:"login"` diff --git a/internal/identity/oidc/azure/microsoft.go b/internal/identity/oidc/azure/microsoft.go index 98496f546..ea9ab6c1c 100644 --- a/internal/identity/oidc/azure/microsoft.go +++ b/internal/identity/oidc/azure/microsoft.go @@ -115,7 +115,7 @@ func (transport *wellKnownConfiguration) RoundTrip(req *http.Request) (*http.Res return nil, err } - var wk map[string]interface{} + var wk map[string]any if err := json.Unmarshal(bs, &wk); err == nil { if issuerVar, ok := wk["issuer"]; ok { if fmt.Sprint(issuerVar) == nonSpecIssuerURL { diff --git a/internal/identity/oidc/oidc.go b/internal/identity/oidc/oidc.go index d8d89c4d2..df93ed1cd 100644 --- a/internal/identity/oidc/oidc.go +++ b/internal/identity/oidc/oidc.go @@ -158,7 +158,7 @@ func (p *Provider) Authenticate(ctx context.Context, code string, v identity.Sta // groups endpoint (non-spec) to populate the rest of the user's information. // // https://openid.net/specs/openid-connect-core-1_0.html#UserInfo -func (p *Provider) UpdateUserInfo(ctx context.Context, t *oauth2.Token, v interface{}) error { +func (p *Provider) UpdateUserInfo(ctx context.Context, t *oauth2.Token, v any) error { pp, err := p.GetProvider() if err != nil { return err @@ -255,7 +255,7 @@ func (p *Provider) Revoke(ctx context.Context, t *oauth2.Token) error { } // GetSubject gets the RFC 7519 Subject claim (`sub`) from a -func (p *Provider) GetSubject(v interface{}) (string, error) { +func (p *Provider) GetSubject(v any) (string, error) { b, err := json.Marshal(v) if err != nil { return "", err diff --git a/internal/identity/oidc/refresh_test.go b/internal/identity/oidc/refresh_test.go index 6ac7f067b..0a5314038 100644 --- a/internal/identity/oidc/refresh_test.go +++ b/internal/identity/oidc/refresh_test.go @@ -18,7 +18,7 @@ func TestRefresh(t *testing.T) { ctx, clearTimeout := context.WithTimeout(context.Background(), 10*time.Second) t.Cleanup(clearTimeout) - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{ "access_token": "NEW_TOKEN", @@ -52,7 +52,7 @@ func TestRefresh_errors(t *testing.T) { ctx, clearTimeout := context.WithTimeout(context.Background(), 10*time.Second) t.Cleanup(clearTimeout) - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("{}")) })) t.Cleanup(s.Close) diff --git a/internal/identity/oidc/userinfo.go b/internal/identity/oidc/userinfo.go index d5452a78c..ca61ad146 100644 --- a/internal/identity/oidc/userinfo.go +++ b/internal/identity/oidc/userinfo.go @@ -52,7 +52,7 @@ func (transport *userInfoRoundTripper) RoundTrip(req *http.Request) (*http.Respo return nil, err } - var userInfo map[string]interface{} + var userInfo map[string]any if err := json.Unmarshal(bs, &userInfo); err == nil { // AWS Cognito returns email_verified as a string, so we'll make it a bool if ev, ok := userInfo["email_verified"]; ok { diff --git a/internal/identity/providers.go b/internal/identity/providers.go index 4e8fd51f6..690b04514 100644 --- a/internal/identity/providers.go +++ b/internal/identity/providers.go @@ -30,7 +30,7 @@ type Authenticator interface { Refresh(context.Context, *oauth2.Token, identity.State) (*oauth2.Token, error) Revoke(context.Context, *oauth2.Token) error Name() string - UpdateUserInfo(ctx context.Context, t *oauth2.Token, v interface{}) error + UpdateUserInfo(ctx context.Context, t *oauth2.Token, v any) error SignIn(w http.ResponseWriter, r *http.Request, state string) error SignOut(w http.ResponseWriter, r *http.Request, idTokenHint, authenticateSignedOutURL, redirectToURL string) error diff --git a/internal/log/grpc.go b/internal/log/grpc.go index 726dba95b..b003049cb 100644 --- a/internal/log/grpc.go +++ b/internal/log/grpc.go @@ -13,69 +13,69 @@ func init() { type grpcLogger struct{} -func (c *grpcLogger) Info(args ...interface{}) { +func (c *grpcLogger) Info(args ...any) { if GetLevel() <= zerolog.DebugLevel { Logger().Info().Msg(fmt.Sprint(args...)) } } -func (c *grpcLogger) Infoln(args ...interface{}) { +func (c *grpcLogger) Infoln(args ...any) { if GetLevel() <= zerolog.DebugLevel { Logger().Info().Msg(fmt.Sprintln(args...)) } } -func (c *grpcLogger) Infof(format string, args ...interface{}) { +func (c *grpcLogger) Infof(format string, args ...any) { if GetLevel() <= zerolog.DebugLevel { Logger().Info().Msg(fmt.Sprintf(format, args...)) } } -func (c *grpcLogger) Warning(args ...interface{}) { +func (c *grpcLogger) Warning(args ...any) { if GetLevel() <= zerolog.DebugLevel { Logger().Warn().Msg(fmt.Sprint(args...)) } } -func (c *grpcLogger) Warningln(args ...interface{}) { +func (c *grpcLogger) Warningln(args ...any) { if GetLevel() <= zerolog.DebugLevel { Logger().Warn().Msg(fmt.Sprintln(args...)) } } -func (c *grpcLogger) Warningf(format string, args ...interface{}) { +func (c *grpcLogger) Warningf(format string, args ...any) { if GetLevel() <= zerolog.DebugLevel { Logger().Warn().Msg(fmt.Sprintf(format, args...)) } } -func (c *grpcLogger) Error(args ...interface{}) { +func (c *grpcLogger) Error(args ...any) { if GetLevel() <= zerolog.DebugLevel { Logger().Error().Msg(fmt.Sprint(args...)) } } -func (c *grpcLogger) Errorln(args ...interface{}) { +func (c *grpcLogger) Errorln(args ...any) { if GetLevel() <= zerolog.DebugLevel { Logger().Error().Msg(fmt.Sprintln(args...)) } } -func (c *grpcLogger) Errorf(format string, args ...interface{}) { +func (c *grpcLogger) Errorf(format string, args ...any) { if GetLevel() <= zerolog.DebugLevel { Logger().Error().Msg(fmt.Sprintf(format, args...)) } } -func (c *grpcLogger) Fatal(args ...interface{}) { +func (c *grpcLogger) Fatal(args ...any) { Logger().Fatal().Msg(fmt.Sprint(args...)) } -func (c *grpcLogger) Fatalln(args ...interface{}) { +func (c *grpcLogger) Fatalln(args ...any) { Logger().Fatal().Msg(fmt.Sprintln(args...)) } -func (c *grpcLogger) Fatalf(format string, args ...interface{}) { +func (c *grpcLogger) Fatalf(format string, args ...any) { Logger().Fatal().Msg(fmt.Sprintf(format, args...)) } diff --git a/internal/log/log.go b/internal/log/log.go index e537a0bc6..ba88a710f 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -162,13 +162,13 @@ func Log(_ context.Context) *zerolog.Event { // Print sends a log event using debug level and no extra field. // Arguments are handled in the manner of fmt.Print. -func Print(v ...interface{}) { +func Print(v ...any) { Logger().Print(v...) } // Printf sends a log event using debug level and no extra field. // Arguments are handled in the manner of fmt.Printf. -func Printf(format string, v ...interface{}) { +func Printf(format string, v ...any) { Logger().Printf(format, v...) } diff --git a/internal/log/middleware_test.go b/internal/log/middleware_test.go index 829c27cd7..0ec71646c 100644 --- a/internal/log/middleware_test.go +++ b/internal/log/middleware_test.go @@ -24,7 +24,7 @@ func TestNewHandler(t *testing.T) { Str("foo", "bar"). Logger() lh := NewHandler(func() *zerolog.Logger { return &log }) - h := lh(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := lh(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { l := FromRequest(r) if !reflect.DeepEqual(*l, log) { t.Fail() @@ -38,7 +38,7 @@ func TestRemoteAddrHandler(t *testing.T) { r := &http.Request{ RemoteAddr: "1.2.3.4:1234", } - h := RemoteAddrHandler("ip")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := RemoteAddrHandler("ip")(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { l := FromRequest(r) l.Log().Msg("") })) @@ -55,7 +55,7 @@ func TestRemoteAddrHandlerIPv6(t *testing.T) { r := &http.Request{ RemoteAddr: "[2001:db8:a0b:12f0::1]:1234", } - h := RemoteAddrHandler("ip")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := RemoteAddrHandler("ip")(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { l := FromRequest(r) l.Log().Msg("") })) @@ -74,7 +74,7 @@ func TestUserAgentHandler(t *testing.T) { "User-Agent": []string{"some user agent string"}, }, } - h := UserAgentHandler("ua")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := UserAgentHandler("ua")(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { l := FromRequest(r) l.Log().Msg("") })) @@ -93,7 +93,7 @@ func TestRefererHandler(t *testing.T) { "Referer": []string{"http://foo.com/bar"}, }, } - h := RefererHandler("referer")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := RefererHandler("referer")(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { l := FromRequest(r) l.Log().Msg("") })) @@ -112,7 +112,7 @@ func TestRequestIDHandler(t *testing.T) { "X-Request-Id": []string{"1234"}, }, } - h := RequestIDHandler("request-id")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := RequestIDHandler("request-id")(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { requestID := requestid.FromContext(r.Context()) l := FromRequest(r) l.Log().Msg("") @@ -131,7 +131,7 @@ func BenchmarkDataRace(b *testing.B) { Str("foo", "bar"). Logger() lh := NewHandler(func() *zerolog.Logger { return &log }) - h := lh(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := lh(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { l := FromRequest(r) l.UpdateContext(func(c zerolog.Context) zerolog.Context { return c.Str("bar", "baz") @@ -153,7 +153,7 @@ func TestLogHeadersHandler(t *testing.T) { r.Header.Set("X-Forwarded-For", "proxy1,proxy2,proxy3") - h := HeadersHandler([]string{"X-Forwarded-For"})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := HeadersHandler([]string{"X-Forwarded-For"})(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { l := FromRequest(r) l.Log().Msg("") })) @@ -170,7 +170,7 @@ func TestAccessHandler(t *testing.T) { r := httptest.NewRequest(http.MethodGet, "/", nil) - h := AccessHandler(func(r *http.Request, status, size int, duration time.Duration) { + h := AccessHandler(func(r *http.Request, status, size int, _ time.Duration) { l := FromRequest(r) l.Log().Int("status", status).Int("size", size).Msg("info") })(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/middleware/middleware_test.go b/internal/middleware/middleware_test.go index 86ef88f16..df7dbb13d 100644 --- a/internal/middleware/middleware_test.go +++ b/internal/middleware/middleware_test.go @@ -26,7 +26,7 @@ func TestSetHeaders(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + testHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { for k, want := range tt.securityHeaders { if got := w.Header().Get(k); want != got { t.Errorf("want %s got %q", want, got) @@ -42,7 +42,7 @@ func TestSetHeaders(t *testing.T) { func TestValidateSignature(t *testing.T) { t.Parallel() - fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fn := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, http.StatusText(http.StatusOK)) w.WriteHeader(http.StatusOK) }) @@ -81,7 +81,7 @@ func TestValidateSignature(t *testing.T) { func TestRequireBasicAuth(t *testing.T) { t.Parallel() - fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fn := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, http.StatusText(http.StatusOK)) w.WriteHeader(http.StatusOK) }) diff --git a/internal/sessions/cookie/cookie_store.go b/internal/sessions/cookie/cookie_store.go index d542d1d98..70318a6cb 100644 --- a/internal/sessions/cookie/cookie_store.go +++ b/internal/sessions/cookie/cookie_store.go @@ -136,7 +136,7 @@ func (cs *Store) LoadSession(r *http.Request) (string, error) { } // SaveSession saves a session state to a request's cookie store. -func (cs *Store) SaveSession(w http.ResponseWriter, _ *http.Request, x interface{}) error { +func (cs *Store) SaveSession(w http.ResponseWriter, _ *http.Request, x any) error { var value string switch v := x.(type) { case []byte: diff --git a/internal/sessions/cookie/cookie_store_test.go b/internal/sessions/cookie/cookie_store_test.go index e6289c486..90232608a 100644 --- a/internal/sessions/cookie/cookie_store_test.go +++ b/internal/sessions/cookie/cookie_store_test.go @@ -104,7 +104,7 @@ func TestStore_SaveSession(t *testing.T) { } tests := []struct { name string - State interface{} + State any encoder encoding.Marshaler decoder encoding.Unmarshaler wantErr bool diff --git a/internal/sessions/cookie/middleware_test.go b/internal/sessions/cookie/middleware_test.go index 3353d0965..934d4e988 100644 --- a/internal/sessions/cookie/middleware_test.go +++ b/internal/sessions/cookie/middleware_test.go @@ -27,7 +27,7 @@ func testAuthorizer(next http.Handler) http.Handler { } func TestVerifier(t *testing.T) { - fnh := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fnh := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprint(w, http.StatusText(http.StatusOK)) w.WriteHeader(http.StatusOK) diff --git a/internal/sessions/header/middleware_test.go b/internal/sessions/header/middleware_test.go index 13e0d2871..8c66b4246 100644 --- a/internal/sessions/header/middleware_test.go +++ b/internal/sessions/header/middleware_test.go @@ -27,7 +27,7 @@ func testAuthorizer(next http.Handler) http.Handler { } func TestVerifier(t *testing.T) { - fnh := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fnh := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprint(w, http.StatusText(http.StatusOK)) w.WriteHeader(http.StatusOK) diff --git a/internal/sessions/middleware.go b/internal/sessions/middleware.go index 45d5047e6..6d584e9b2 100644 --- a/internal/sessions/middleware.go +++ b/internal/sessions/middleware.go @@ -46,7 +46,7 @@ func FromContext(ctx context.Context) (string, error) { } // contextKey is a value for use with context.WithValue. It's used as -// a pointer so it fits in an interface{} without allocation. This technique +// a pointer so it fits in an any without allocation. This technique // for defining context keys was copied from Go 1.7's new use of context in net/http. type contextKey struct { name string diff --git a/internal/sessions/middleware_test.go b/internal/sessions/middleware_test.go index e658a12bf..be9674342 100644 --- a/internal/sessions/middleware_test.go +++ b/internal/sessions/middleware_test.go @@ -62,7 +62,7 @@ func testAuthorizer(next http.Handler) http.Handler { } func TestVerifier(t *testing.T) { - fnh := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fnh := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprint(w, http.StatusText(http.StatusOK)) w.WriteHeader(http.StatusOK) diff --git a/internal/sessions/mock/mock_store.go b/internal/sessions/mock/mock_store.go index 5263af40d..0b2f76a7d 100644 --- a/internal/sessions/mock/mock_store.go +++ b/internal/sessions/mock/mock_store.go @@ -38,6 +38,6 @@ func (ms Store) LoadSession(*http.Request) (string, error) { } // SaveSession returns a save error. -func (ms Store) SaveSession(http.ResponseWriter, *http.Request, interface{}) error { +func (ms Store) SaveSession(http.ResponseWriter, *http.Request, any) error { return ms.SaveError } diff --git a/internal/sessions/queryparam/middleware_test.go b/internal/sessions/queryparam/middleware_test.go index b18f68a21..9431ead6f 100644 --- a/internal/sessions/queryparam/middleware_test.go +++ b/internal/sessions/queryparam/middleware_test.go @@ -27,7 +27,7 @@ func testAuthorizer(next http.Handler) http.Handler { } func TestVerifier(t *testing.T) { - fnh := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fnh := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprint(w, http.StatusText(http.StatusOK)) w.WriteHeader(http.StatusOK) diff --git a/internal/sessions/queryparam/query_store.go b/internal/sessions/queryparam/query_store.go index 034f8f5c2..b86d18f3c 100644 --- a/internal/sessions/queryparam/query_store.go +++ b/internal/sessions/queryparam/query_store.go @@ -60,7 +60,7 @@ func (qp *Store) ClearSession(_ http.ResponseWriter, r *http.Request) { } // SaveSession sets a session to a request's query param key `pomerium_session` -func (qp *Store) SaveSession(_ http.ResponseWriter, r *http.Request, x interface{}) error { +func (qp *Store) SaveSession(_ http.ResponseWriter, r *http.Request, x any) error { data, err := qp.encoder.Marshal(x) if err != nil { return err diff --git a/internal/sessions/store.go b/internal/sessions/store.go index bc88207ac..32044fe98 100644 --- a/internal/sessions/store.go +++ b/internal/sessions/store.go @@ -11,7 +11,7 @@ import ( type SessionStore interface { SessionLoader ClearSession(http.ResponseWriter, *http.Request) - SaveSession(http.ResponseWriter, *http.Request, interface{}) error + SaveSession(http.ResponseWriter, *http.Request, any) error } // SessionLoader defines an interface for loading a session. diff --git a/internal/telemetry/metrics/grpc.go b/internal/telemetry/metrics/grpc.go index 7ad043133..08a4bb2ae 100644 --- a/internal/telemetry/metrics/grpc.go +++ b/internal/telemetry/metrics/grpc.go @@ -120,8 +120,8 @@ func GRPCClientInterceptor(service string) grpc.UnaryClientInterceptor { return func( ctx context.Context, method string, - req interface{}, - reply interface{}, + req any, + reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, diff --git a/internal/telemetry/metrics/helpers_test.go b/internal/telemetry/metrics/helpers_test.go index e930e8822..2c6d9b9c1 100644 --- a/internal/telemetry/metrics/helpers_test.go +++ b/internal/telemetry/metrics/helpers_test.go @@ -7,7 +7,7 @@ import ( "go.opencensus.io/metric/metricdata" ) -func testMetricRetrieval(metrics []*metricdata.Metric, t *testing.T, labels []metricdata.LabelValue, value interface{}, name string) { +func testMetricRetrieval(metrics []*metricdata.Metric, t *testing.T, labels []metricdata.LabelValue, value any, name string) { t.Helper() switch value.(type) { diff --git a/internal/telemetry/metrics/http_test.go b/internal/telemetry/metrics/http_test.go index 99755e2c8..d34371a66 100644 --- a/internal/telemetry/metrics/http_test.go +++ b/internal/telemetry/metrics/http_test.go @@ -44,7 +44,7 @@ func testDataRetrieval(v *view.View, t *testing.T, want string) { func newTestMux() http.Handler { mux := http.NewServeMux() - mux.HandleFunc("/good", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("/good", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintf(w, "Hello") }) @@ -123,7 +123,7 @@ func newTestTransport() http.RoundTripper { } func newFailingTestTransport() http.RoundTripper { - return tripper.RoundTripperFunc(func(r *http.Request) (*http.Response, error) { + return tripper.RoundTripperFunc(func(_ *http.Request) (*http.Response, error) { return nil, errors.New("failure") }) } diff --git a/internal/telemetry/metrics/providers_test.go b/internal/telemetry/metrics/providers_test.go index 9cc2e8afc..09fb63c6c 100644 --- a/internal/telemetry/metrics/providers_test.go +++ b/internal/telemetry/metrics/providers_test.go @@ -11,7 +11,7 @@ import ( ) func newEnvoyMetricsHandler() http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(` # TYPE envoy_server_initialization_time_ms histogram envoy_server_initialization_time_ms_bucket{le="0.5"} 0 diff --git a/internal/testutil/testutil.go b/internal/testutil/testutil.go index f9caca028..c926da0c5 100644 --- a/internal/testutil/testutil.go +++ b/internal/testutil/testutil.go @@ -21,7 +21,7 @@ import ( const maxWait = time.Minute * 20 // AssertProtoEqual asserts that two protobuf messages equal. Slices of messages are also supported. -func AssertProtoEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) bool { +func AssertProtoEqual(t *testing.T, expected, actual any, msgAndArgs ...any) bool { t.Helper() return assert.True(t, cmp.Equal(expected, actual, protocmp.Transform()), append(msgAndArgs, cmp.Diff(expected, actual, protocmp.Transform()))...) @@ -29,13 +29,13 @@ func AssertProtoEqual(t *testing.T, expected, actual interface{}, msgAndArgs ... // AssertProtoJSONEqual asserts that a protobuf message matches the given JSON. The protoMsg can also be a slice // of protobuf messages. -func AssertProtoJSONEqual(t *testing.T, expected string, protoMsg interface{}, msgAndArgs ...interface{}) bool { +func AssertProtoJSONEqual(t *testing.T, expected string, protoMsg any, msgAndArgs ...any) bool { t.Helper() formattedJSON := formattedProtoJSON(protoMsg) return assert.Equal(t, reformatJSON(json.RawMessage(expected)), formattedJSON, msgAndArgs...) } -func formattedProtoJSON(protoMsg interface{}) string { +func formattedProtoJSON(protoMsg any) string { protoMsgVal := reflect.ValueOf(protoMsg) if protoMsgVal.Kind() == reflect.Slice { var protoMsgs []json.RawMessage @@ -49,13 +49,13 @@ func formattedProtoJSON(protoMsg interface{}) string { } func reformatJSON(raw json.RawMessage) string { - var obj interface{} + var obj any _ = json.Unmarshal(raw, &obj) bs, _ := json.MarshalIndent(obj, "", " ") return string(bs) } -func toProtoJSON(protoMsg interface{}) json.RawMessage { +func toProtoJSON(protoMsg any) json.RawMessage { bs, _ := protojson.Marshal(protoMsg.(protoreflect.ProtoMessage)) return bs } @@ -69,7 +69,7 @@ var updateFlag = flag.Bool("update", false, // To update a reference JSON file, pass the test argument '-update'. This will // overwrite the reference output to match the current behavior. func AssertProtoJSONFileEqual( - t *testing.T, file string, protoMsg interface{}, msgAndArgs ...interface{}, + t *testing.T, file string, protoMsg any, msgAndArgs ...any, ) bool { t.Helper() diff --git a/internal/urlutil/signed.go b/internal/urlutil/signed.go index af07ed6a5..9f308e94b 100644 --- a/internal/urlutil/signed.go +++ b/internal/urlutil/signed.go @@ -92,7 +92,7 @@ func (su *SignedURL) Validate() error { // hmacURL takes a redirect url string and timestamp and returns the base64 // encoded HMAC result. -func hmacURL(key []byte, data ...interface{}) string { +func hmacURL(key []byte, data ...any) string { h := cryptutil.GenerateHMAC([]byte(fmt.Sprint(data...)), key) return base64.URLEncoding.EncodeToString(h) } diff --git a/internal/zero/connect-mux/config.go b/internal/zero/connect-mux/config.go index d7da0412c..40a4f756a 100644 --- a/internal/zero/connect-mux/config.go +++ b/internal/zero/connect-mux/config.go @@ -45,7 +45,7 @@ func newConfig(opts ...WatchOption) *config { for _, opt := range []WatchOption{ WithOnConnected(func(_ context.Context) {}), WithOnDisconnected(func(_ context.Context) {}), - WithOnBundleUpdated(func(_ context.Context, key string) {}), + WithOnBundleUpdated(func(_ context.Context, _ string) {}), WithOnBootstrapConfigUpdated(func(_ context.Context) {}), } { opt(cfg) diff --git a/internal/zero/controller/mux_log.go b/internal/zero/controller/mux_log.go index de83ad460..a8db02015 100644 --- a/internal/zero/controller/mux_log.go +++ b/internal/zero/controller/mux_log.go @@ -13,16 +13,16 @@ func (c *controller) RunConnectLog(ctx context.Context) error { logger := log.Ctx(ctx).With().Str("service", "connect-mux").Logger().Level(zerolog.InfoLevel) return c.api.Watch(ctx, - connect_mux.WithOnConnected(func(ctx context.Context) { + connect_mux.WithOnConnected(func(_ context.Context) { logger.Debug().Msg("connected") }), - connect_mux.WithOnDisconnected(func(ctx context.Context) { + connect_mux.WithOnDisconnected(func(_ context.Context) { logger.Debug().Msg("disconnected") }), - connect_mux.WithOnBootstrapConfigUpdated(func(ctx context.Context) { + connect_mux.WithOnBootstrapConfigUpdated(func(_ context.Context) { logger.Debug().Msg("bootstrap config updated") }), - connect_mux.WithOnBundleUpdated(func(ctx context.Context, key string) { + connect_mux.WithOnBundleUpdated(func(_ context.Context, key string) { logger.Debug().Str("key", key).Msg("bundle updated") }), ) diff --git a/internal/zero/reconciler/bundles_queue.go b/internal/zero/reconciler/bundles_queue.go index 8ed3f6b7b..6895352ec 100644 --- a/internal/zero/reconciler/bundles_queue.go +++ b/internal/zero/reconciler/bundles_queue.go @@ -25,12 +25,12 @@ func (h bundleHeap) Less(i, j int) bool { func (h bundleHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *bundleHeap) Push(x interface{}) { +func (h *bundleHeap) Push(x any) { item := x.(bundle) *h = append(*h, item) } -func (h *bundleHeap) Pop() interface{} { +func (h *bundleHeap) Pop() any { old := *h n := len(old) x := old[n-1] diff --git a/internal/zero/reconciler/service.go b/internal/zero/reconciler/service.go index 86f9cf80d..dd78a93f9 100644 --- a/internal/zero/reconciler/service.go +++ b/internal/zero/reconciler/service.go @@ -49,7 +49,7 @@ func Run(ctx context.Context, opts ...Option) error { func (c *service) watchUpdates(ctx context.Context) error { return c.config.api.Watch(ctx, - connect_mux.WithOnConnected(func(ctx context.Context) { + connect_mux.WithOnConnected(func(_ context.Context) { c.triggerFullUpdate(true) }), connect_mux.WithOnDisconnected(func(_ context.Context) { diff --git a/internal/zero/reconciler/sync.go b/internal/zero/reconciler/sync.go index d005a8b00..e2ea1b4dd 100644 --- a/internal/zero/reconciler/sync.go +++ b/internal/zero/reconciler/sync.go @@ -217,10 +217,10 @@ func (c *service) syncBundleToDatabroker(ctx context.Context, key string, src io err = databroker.NewReconciler( fmt.Sprintf("bundle-%s", key), c.config.databrokerClient, - func(ctx context.Context) (databroker.RecordSetBundle, error) { + func(_ context.Context) (databroker.RecordSetBundle, error) { return databrokerRecords, nil }, - func(ctx context.Context) (databroker.RecordSetBundle, error) { + func(_ context.Context) (databroker.RecordSetBundle, error) { return bundleRecords, nil }, func(_ []*databroker.Record) {}, diff --git a/internal/zero/token/cache_test.go b/internal/zero/token/cache_test.go index 05d532e73..f8de4b363 100644 --- a/internal/zero/token/cache_test.go +++ b/internal/zero/token/cache_test.go @@ -19,7 +19,7 @@ func TestCache(t *testing.T) { var testToken *token.Token var testError error - fetcher := func(ctx context.Context, refreshToken string) (*token.Token, error) { + fetcher := func(_ context.Context, _ string) (*token.Token, error) { if testToken != nil { token := *testToken return &token, nil @@ -54,7 +54,7 @@ func TestCache(t *testing.T) { t.Run("token cannot fit minTTL", func(t *testing.T) { t.Parallel() - fetcher := func(ctx context.Context, refreshToken string) (*token.Token, error) { + fetcher := func(_ context.Context, _ string) (*token.Token, error) { return &token.Token{"ok-bearer", time.Now().Add(time.Minute)}, nil } diff --git a/pkg/cmd/pomerium/pomerium.go b/pkg/cmd/pomerium/pomerium.go index ea9d8dd79..efbcb9d1f 100644 --- a/pkg/cmd/pomerium/pomerium.go +++ b/pkg/cmd/pomerium/pomerium.go @@ -32,7 +32,7 @@ import ( // Run runs the main pomerium application. func Run(ctx context.Context, src config.Source) error { - _, _ = maxprocs.Set(maxprocs.Logger(func(s string, i ...interface{}) { log.Debug(context.Background()).Msgf(s, i...) })) + _, _ = maxprocs.Set(maxprocs.Logger(func(s string, i ...any) { log.Debug(context.Background()).Msgf(s, i...) })) log.Info(ctx). Str("envoy_version", files.FullVersion()). diff --git a/pkg/contextutil/contextutil.go b/pkg/contextutil/contextutil.go index cd12f17e6..d59066534 100644 --- a/pkg/contextutil/contextutil.go +++ b/pkg/contextutil/contextutil.go @@ -55,7 +55,7 @@ func (mc *mergedCtx) Err() error { return mc.doneCtx.Err() } -func (mc *mergedCtx) Value(key interface{}) interface{} { +func (mc *mergedCtx) Value(key any) any { if value := mc.ctx1.Value(key); value != nil { return value } diff --git a/pkg/cryptutil/hash_test.go b/pkg/cryptutil/hash_test.go index e32786275..4e4767ee7 100644 --- a/pkg/cryptutil/hash_test.go +++ b/pkg/cryptutil/hash_test.go @@ -88,7 +88,7 @@ func TestHashProto(t *testing.T) { // deterministic. var cur []byte for i := 0; i < 1000; i++ { - s, err := structpb.NewStruct(map[string]interface{}{ + s, err := structpb.NewStruct(map[string]any{ "1": "a", "2": "b", "3": "c", "4": "d", "5": "e", "6": "f", "7": "g", "8": "h", }) diff --git a/pkg/cryptutil/jose.go b/pkg/cryptutil/jose.go index 3334050d7..2b7dbb03c 100644 --- a/pkg/cryptutil/jose.go +++ b/pkg/cryptutil/jose.go @@ -75,7 +75,7 @@ func loadKeys(data []byte, unmarshal func([]byte) (any, error)) ([]*jose.JSONWeb return jwks, nil } -func loadPrivateKey(b []byte) (interface{}, error) { +func loadPrivateKey(b []byte) (any, error) { var wrappedErr error var err error var key any @@ -99,7 +99,7 @@ func loadPrivateKey(b []byte) (interface{}, error) { } // https://github.com/square/go-jose/tree/v2.5.1#supported-key-types -func loadPublicKey(b []byte) (interface{}, error) { +func loadPublicKey(b []byte) (any, error) { var wrappedErr error var err error var key any @@ -130,7 +130,7 @@ func loadPublicKey(b []byte) (interface{}, error) { } // SignatureAlgorithmForKey returns the signature algorithm for the given key. -func SignatureAlgorithmForKey(key interface{}) (jose.SignatureAlgorithm, error) { +func SignatureAlgorithmForKey(key any) (jose.SignatureAlgorithm, error) { switch key.(type) { case *ecdsa.PrivateKey, *ecdsa.PublicKey: return jose.ES256, nil diff --git a/pkg/cryptutil/x509.go b/pkg/cryptutil/x509.go index 5381f54ef..3e40ab9c3 100644 --- a/pkg/cryptutil/x509.go +++ b/pkg/cryptutil/x509.go @@ -30,7 +30,7 @@ type ( ) // MarshalPKCS8PrivateKey wraps x509.MarshalPKCS8PrivateKey with added support for KeyEncryptionKeys. -func MarshalPKCS8PrivateKey(key interface{}) ([]byte, error) { +func MarshalPKCS8PrivateKey(key any) ([]byte, error) { // also support a pointer to a private key encryption key if kek, ok := key.(*PrivateKeyEncryptionKey); ok { key = *kek @@ -53,7 +53,7 @@ func MarshalPKCS8PrivateKey(key interface{}) ([]byte, error) { } // MarshalPKIXPublicKey wraps x509.MarshalPKIXPublicKey with added support for KeyEncryptionKeys. -func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { +func MarshalPKIXPublicKey(pub any) ([]byte, error) { if kek, ok := pub.(*PublicKeyEncryptionKey); ok { pub = *kek } @@ -76,7 +76,7 @@ func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { } // ParsePKCS8PrivateKey wraps x509.ParsePKCS8PrivateKey with added support for KeyEncryptionKeys. -func ParsePKCS8PrivateKey(der []byte) (interface{}, error) { +func ParsePKCS8PrivateKey(der []byte) (any, error) { var privKey pkcs8 _, err := asn1.Unmarshal(der, &privKey) if err != nil { @@ -96,7 +96,7 @@ func ParsePKCS8PrivateKey(der []byte) (interface{}, error) { } // ParsePKIXPublicKey wraps x509.ParsePKIXPublicKey with added support for KeyEncryptionKeys. -func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) { +func ParsePKIXPublicKey(derBytes []byte) (pub any, err error) { var pki publicKeyInfo rest, err := asn1.Unmarshal(derBytes, &pki) if err != nil || len(rest) > 0 { diff --git a/pkg/fanout/fanout_test.go b/pkg/fanout/fanout_test.go index 8d2a53662..29b9b9f84 100644 --- a/pkg/fanout/fanout_test.go +++ b/pkg/fanout/fanout_test.go @@ -25,7 +25,7 @@ func TestFanOutStopped(t *testing.T) { return errors.Is(f.Publish(context.Background(), 1), fanout.ErrStopped) }, 5*time.Second, 10*time.Millisecond) - err := f.Receive(context.Background(), func(ctx context.Context, msg int) error { + err := f.Receive(context.Background(), func(_ context.Context, _ int) error { return nil }) assert.ErrorIs(t, err, fanout.ErrStopped) @@ -47,7 +47,7 @@ func TestFanOutEvictSlowSubscriber(t *testing.T) { eg, ctx := errgroup.WithContext(ctx) eg.Go(func() error { - err := f.Receive(ctx, func(ctx context.Context, msg int) error { + err := f.Receive(ctx, func(ctx context.Context, _ int) error { select { case <-ctx.Done(): // context was canceled as expected @@ -91,7 +91,7 @@ func TestFanOutReceiverCancelOnError(t *testing.T) { ready := make(chan struct{}) go func() { - errch <- f.Receive(ctx, func(ctx context.Context, msg int) error { + errch <- f.Receive(ctx, func(_ context.Context, _ int) error { return receiverErr }, fanout.WithOnSubscriberAdded[int](func() { close(ready) })) }() @@ -111,7 +111,7 @@ func TestFanOutFilter(t *testing.T) { ready := make(chan struct{}) results := make(chan int) go func() { - _ = f.Receive(ctx, func(ctx context.Context, msg int) error { + _ = f.Receive(ctx, func(_ context.Context, msg int) error { results <- msg return nil }, @@ -146,7 +146,7 @@ func BenchmarkFanout(b *testing.B) { want := i eg.Go(func() error { seen := 0 - err := f.Receive(ctx, func(ctx context.Context, _ int) error { + err := f.Receive(ctx, func(_ context.Context, _ int) error { if seen++; seen == cycles { return errStopReceiver } diff --git a/pkg/grpc/client.go b/pkg/grpc/client.go index f92513408..f9f115b24 100644 --- a/pkg/grpc/client.go +++ b/pkg/grpc/client.go @@ -61,7 +61,7 @@ func NewGRPCClientConn(ctx context.Context, opts *Options, other ...grpc.DialOpt // grpcTimeoutInterceptor enforces per-RPC request timeouts func grpcTimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor { - return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if timeout <= 0 { return invoker(ctx, method, req, reply, cc, opts...) } diff --git a/pkg/grpc/client_test.go b/pkg/grpc/client_test.go index 52260852e..1dffa4e46 100644 --- a/pkg/grpc/client_test.go +++ b/pkg/grpc/client_test.go @@ -10,7 +10,7 @@ import ( func Test_grpcTimeoutInterceptor(t *testing.T) { mockInvoker := func(sleepTime time.Duration, wantFail bool) grpc.UnaryInvoker { - return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error { + return func(ctx context.Context, _ string, _, _ any, _ *grpc.ClientConn, _ ...grpc.CallOption) error { time.Sleep(sleepTime) deadline, ok := ctx.Deadline() if !ok { diff --git a/pkg/grpc/databroker/databroker_test.go b/pkg/grpc/databroker/databroker_test.go index 0b5003a3d..0c3c17b88 100644 --- a/pkg/grpc/databroker/databroker_test.go +++ b/pkg/grpc/databroker/databroker_test.go @@ -69,7 +69,7 @@ func TestInitialSync(t *testing.T) { r2 := new(Record) m := &mockServer{ - syncLatest: func(req *SyncLatestRequest, stream DataBrokerService_SyncLatestServer) error { + syncLatest: func(_ *SyncLatestRequest, stream DataBrokerService_SyncLatestServer) error { stream.Send(&SyncLatestResponse{ Response: &SyncLatestResponse_Record{ Record: r1, diff --git a/pkg/grpc/databroker/leaser_test.go b/pkg/grpc/databroker/leaser_test.go index 7f2ef75ff..f1680b0b4 100644 --- a/pkg/grpc/databroker/leaser_test.go +++ b/pkg/grpc/databroker/leaser_test.go @@ -126,7 +126,7 @@ func TestLeaser(t *testing.T) { AnyTimes() handler.EXPECT(). RunLeased(gomock.Any()). - DoAndReturn(func(ctx context.Context) error { + DoAndReturn(func(_ context.Context) error { time.Sleep(time.Millisecond * 20) return exitErr }). @@ -162,7 +162,7 @@ func TestLeasers(t *testing.T) { Times(1) var counter int64 - fn1 := func(ctx context.Context) error { + fn1 := func(_ context.Context) error { atomic.AddInt64(&counter, 1) return exitErr } diff --git a/pkg/grpc/databroker/syncer_test.go b/pkg/grpc/databroker/syncer_test.go index 22d7f40a9..ee1bc6e23 100644 --- a/pkg/grpc/databroker/syncer_test.go +++ b/pkg/grpc/databroker/syncer_test.go @@ -87,7 +87,7 @@ func TestSyncer(t *testing.T) { } return nil }, - syncLatest: func(req *SyncLatestRequest, server DataBrokerService_SyncLatestServer) error { + syncLatest: func(_ *SyncLatestRequest, server DataBrokerService_SyncLatestServer) error { syncLatestCount++ switch syncLatestCount { case 1: @@ -161,10 +161,10 @@ func TestSyncer(t *testing.T) { getDataBrokerServiceClient: func() DataBrokerServiceClient { return NewDataBrokerServiceClient(gc) }, - clearRecords: func(ctx context.Context) { + clearRecords: func(_ context.Context) { clearCh <- struct{}{} }, - updateRecords: func(ctx context.Context, serverVersion uint64, records []*Record) { + updateRecords: func(_ context.Context, _ uint64, records []*Record) { updateCh <- records }, }) diff --git a/pkg/grpc/user/user.go b/pkg/grpc/user/user.go index 6c9e41dce..bd2fd5b53 100644 --- a/pkg/grpc/user/user.go +++ b/pkg/grpc/user/user.go @@ -61,8 +61,8 @@ func (x *User) AddClaims(claims identity.FlattenedClaims) { // GetClaim returns a claim. // // This method is used by the dashboard template HTML to display claim data. -func (x *User) GetClaim(claim string) []interface{} { - var vs []interface{} +func (x *User) GetClaim(claim string) []any { + var vs []any for _, sv := range x.GetClaims()[claim].GetValues() { vs = append(vs, sv.AsInterface()) } diff --git a/pkg/grpcutil/client.go b/pkg/grpcutil/client.go index e6ef727e8..947c3b02a 100644 --- a/pkg/grpcutil/client.go +++ b/pkg/grpcutil/client.go @@ -107,7 +107,7 @@ func NewGRPCClientConn(ctx context.Context, opts *Options, other ...grpc.DialOpt // grpcTimeoutInterceptor enforces per-RPC request timeouts func grpcTimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor { - return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if timeout <= 0 { return invoker(ctx, method, req, reply, cc, opts...) } diff --git a/pkg/grpcutil/options.go b/pkg/grpcutil/options.go index c72b90c6e..d3329251e 100644 --- a/pkg/grpcutil/options.go +++ b/pkg/grpcutil/options.go @@ -32,7 +32,7 @@ func WithStreamSignedJWT(getKey func() []byte) grpc.StreamClientInterceptor { // WithUnarySignedJWT returns a UnaryClientInterceptor that adds a JWT to requests. func WithUnarySignedJWT(getKey func() []byte) grpc.UnaryClientInterceptor { - return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { ctx, err := withSignedJWT(ctx, getKey()) if err != nil { return err @@ -65,7 +65,7 @@ func withSignedJWT(ctx context.Context, key []byte) (context.Context, error) { // UnaryRequireSignedJWT requires a JWT in the gRPC metadata and that it be signed by the base64-encoded key. func UnaryRequireSignedJWT(key string) grpc.UnaryServerInterceptor { keyBS, _ := base64.StdEncoding.DecodeString(key) - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { if err := RequireSignedJWT(ctx, keyBS); err != nil { return nil, err } @@ -76,7 +76,7 @@ func UnaryRequireSignedJWT(key string) grpc.UnaryServerInterceptor { // StreamRequireSignedJWT requires a JWT in the gRPC metadata and that it be signed by the base64-encoded key. func StreamRequireSignedJWT(key string) grpc.StreamServerInterceptor { keyBS, _ := base64.StdEncoding.DecodeString(key) - return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if err := RequireSignedJWT(ss.Context(), keyBS); err != nil { return err } diff --git a/pkg/grpcutil/version.go b/pkg/grpcutil/version.go index 9da403a04..415971af2 100644 --- a/pkg/grpcutil/version.go +++ b/pkg/grpcutil/version.go @@ -15,12 +15,12 @@ const MetadataKeyPomeriumVersion = "x-pomerium-version" // AttachMetadataInterceptors returns unary and server stream interceptors that attach metadata to the response. func AttachMetadataInterceptors(md metadata.MD) (grpc.UnaryServerInterceptor, grpc.StreamServerInterceptor) { - unary := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + unary := func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { _ = grpc.SetHeader(ctx, md) return handler(ctx, req) } - stream := func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + stream := func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { _ = ss.SetHeader(md) return handler(srv, ss) } diff --git a/pkg/httputil/serve.go b/pkg/httputil/serve.go index 1fc9b950f..c5a049f33 100644 --- a/pkg/httputil/serve.go +++ b/pkg/httputil/serve.go @@ -19,7 +19,7 @@ func ServeWithGracefulStop(ctx context.Context, handler http.Handler, li net.Lis srv := http.Server{ Handler: handler, - BaseContext: func(l net.Listener) context.Context { + BaseContext: func(_ net.Listener) context.Context { return baseCtx }, } diff --git a/pkg/httputil/serve_test.go b/pkg/httputil/serve_test.go index 553f29e71..0821243d7 100644 --- a/pkg/httputil/serve_test.go +++ b/pkg/httputil/serve_test.go @@ -27,7 +27,7 @@ func TestServeWithGracefulStop(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { }) now := time.Now() diff --git a/pkg/policy/criteria/criteria.go b/pkg/policy/criteria/criteria.go index 763b38bdb..535fa202d 100644 --- a/pkg/policy/criteria/criteria.go +++ b/pkg/policy/criteria/criteria.go @@ -88,7 +88,7 @@ func NewCriterionDeviceRule( ) *ast.Rule { r1 := g.NewRule(name) - additionalData := map[string]interface{}{ + additionalData := map[string]any{ "device_type": deviceType, } @@ -185,7 +185,7 @@ func NewCriterionTerm(value bool, reasons ...Reason) *ast.Term { // NewCriterionTermWithAdditionalData creates a new rego term for a criterion with additional data: // // [true, {"reason"}, {"key": "value"}] -func NewCriterionTermWithAdditionalData(value bool, reason Reason, additionalData map[string]interface{}) *ast.Term { +func NewCriterionTermWithAdditionalData(value bool, reason Reason, additionalData map[string]any) *ast.Term { var kvs [][2]*ast.Term for k, v := range additionalData { kvs = append(kvs, [2]*ast.Term{ diff --git a/pkg/policy/criteria/criteria_test.go b/pkg/policy/criteria/criteria_test.go index b516448ad..47db51dd2 100644 --- a/pkg/policy/criteria/criteria_test.go +++ b/pkg/policy/criteria/criteria_test.go @@ -23,8 +23,8 @@ import ( ) type ( - A = []interface{} - M = map[string]interface{} + A = []any + M = map[string]any ) var testingNow = time.Date(2021, 5, 11, 13, 43, 0, 0, time.Local) @@ -87,7 +87,7 @@ func makeRecord(object interface { } } -func makeStructRecord(recordType, recordID string, object interface{}) *databroker.Record { +func makeStructRecord(recordType, recordID string, object any) *databroker.Record { s := protoutil.ToStruct(object).GetStructValue() return &databroker.Record{ Type: recordType, @@ -115,7 +115,7 @@ func evaluate(t *testing.T, Decl: types.NewFunction([]types.Type{ types.S, types.S, }, types.A), - }, func(bctx rego.BuiltinContext, op1, op2 *ast.Term) (*ast.Term, error) { + }, func(_ rego.BuiltinContext, op1, op2 *ast.Term) (*ast.Term, error) { recordType, ok := op1.Value.(ast.String) if !ok { return nil, fmt.Errorf("invalid type for record_type: %T", op1) @@ -159,7 +159,7 @@ func evaluate(t *testing.T, if len(resultSet) == 0 { return make(rego.Vars), nil } - vars, ok := resultSet[0].Bindings["result"].(map[string]interface{}) + vars, ok := resultSet[0].Bindings["result"].(map[string]any) if !ok { return make(rego.Vars), nil } diff --git a/pkg/policy/criteria/matchers_test.go b/pkg/policy/criteria/matchers_test.go index 308915da2..ec9735da4 100644 --- a/pkg/policy/criteria/matchers_test.go +++ b/pkg/policy/criteria/matchers_test.go @@ -13,7 +13,7 @@ import ( ) func TestStringMatcher(t *testing.T) { - str := func(x interface{}) string { + str := func(x any) string { bs := format.MustAst(x) return strings.TrimSpace(string(bs)) } @@ -53,7 +53,7 @@ func TestStringMatcher(t *testing.T) { } func TestStringListMatcher(t *testing.T) { - str := func(x interface{}) string { + str := func(x any) string { bs := format.MustAst(x) return strings.TrimSpace(string(bs)) } diff --git a/pkg/policy/generator/generator_test.go b/pkg/policy/generator/generator_test.go index 0635d7a72..7ce6e27c0 100644 --- a/pkg/policy/generator/generator_test.go +++ b/pkg/policy/generator/generator_test.go @@ -13,7 +13,7 @@ import ( func Test(t *testing.T) { g := New(WithCriterion(func(g *Generator) Criterion { - return NewCriterionFunc(CriterionDataTypeUnused, "accept", func(subPath string, data parser.Value) (rule *ast.Rule, additionalRules []*ast.Rule, err error) { + return NewCriterionFunc(CriterionDataTypeUnused, "accept", func(_ string, _ parser.Value) (rule *ast.Rule, additionalRules []*ast.Rule, err error) { rule = g.NewRule("accept") rule.Body = append(rule.Body, ast.MustParseExpr("1 == 1")) return rule, nil, nil diff --git a/pkg/policy/parser/parser.go b/pkg/policy/parser/parser.go index 72e45ae2e..64e0f43e7 100644 --- a/pkg/policy/parser/parser.go +++ b/pkg/policy/parser/parser.go @@ -101,7 +101,7 @@ func (p *Parser) ParseJSON(r io.Reader) (*Policy, error) { // ParseYAML parses a raw YAML document into a policy. func (p *Parser) ParseYAML(r io.Reader) (*Policy, error) { - var obj interface{} + var obj any err := yaml.NewDecoder(r).Decode(&obj) if err != nil { return nil, err diff --git a/pkg/protoutil/any.go b/pkg/protoutil/any.go index 2e0cd8e5c..08b36da7d 100644 --- a/pkg/protoutil/any.go +++ b/pkg/protoutil/any.go @@ -8,7 +8,7 @@ import ( ) // ToAny converts any type into an any value. -func ToAny(value interface{}) *anypb.Any { +func ToAny(value any) *anypb.Any { switch v := value.(type) { case bool: return NewAnyBool(v) diff --git a/pkg/protoutil/any_test.go b/pkg/protoutil/any_test.go index 0cceea953..79b92b338 100644 --- a/pkg/protoutil/any_test.go +++ b/pkg/protoutil/any_test.go @@ -9,7 +9,7 @@ import ( func TestToAny(t *testing.T) { testCases := []struct { name string - value interface{} + value any expect string }{ {"bool", true, `{ @@ -68,11 +68,11 @@ func TestToAny(t *testing.T) { "@type": "type.googleapis.com/google.protobuf.UInt64Value", "value": "1" }`}, - {"[]interface{}", []interface{}{1, 2, 3, 4}, `{ + {"[]any", []any{1, 2, 3, 4}, `{ "@type": "type.googleapis.com/google.protobuf.Value", "value": [1,2,3,4] }`}, - {"map[string]interface{}", map[string]interface{}{"k1": "v1", "k2": "v2"}, `{ + {"map[string]any", map[string]any{"k1": "v1", "k2": "v2"}, `{ "@type": "type.googleapis.com/google.protobuf.Value", "value": {"k1": "v1", "k2": "v2"} }`}, diff --git a/pkg/protoutil/crypt_test.go b/pkg/protoutil/crypt_test.go index 3c9e3591d..dc9fda180 100644 --- a/pkg/protoutil/crypt_test.go +++ b/pkg/protoutil/crypt_test.go @@ -77,9 +77,9 @@ func assertProtoEqual(t *testing.T, x, y proto.Message) { } func BenchmarkEncrypt(b *testing.B) { - m := map[string]interface{}{} + m := map[string]any{} for i := 0; i < 10; i++ { - mm := map[string]interface{}{} + mm := map[string]any{} for j := 0; j < 10; j++ { mm[fmt.Sprintf("key%d", j)] = fmt.Sprintf("value%d", j) } diff --git a/pkg/protoutil/struct.go b/pkg/protoutil/struct.go index cb76dd41b..f520ed587 100644 --- a/pkg/protoutil/struct.go +++ b/pkg/protoutil/struct.go @@ -11,7 +11,7 @@ import ( ) // ToStruct converts any value into a structpb Value. -func ToStruct(value interface{}) *structpb.Value { +func ToStruct(value any) *structpb.Value { if value == nil { return NewStructNull() } diff --git a/pkg/protoutil/struct_test.go b/pkg/protoutil/struct_test.go index f25227b90..4924d4b57 100644 --- a/pkg/protoutil/struct_test.go +++ b/pkg/protoutil/struct_test.go @@ -11,7 +11,7 @@ import ( func TestToValue(t *testing.T) { testCases := []struct { name string - value interface{} + value any expect string }{ {"bool", true, "true"}, @@ -28,8 +28,8 @@ func TestToValue(t *testing.T) { {"uint16", uint16(1), "1"}, {"uint32", uint32(1), "1"}, {"uint64", uint64(1), "1"}, - {"[]interface{}", []interface{}{1, 2, 3, 4}, `[1,2,3,4]`}, - {"map[string]interface{}", map[string]interface{}{"k1": "v1", "k2": "v2"}, `{"k1":"v1","k2":"v2"}`}, + {"[]any", []any{1, 2, 3, 4}, `[1,2,3,4]`}, + {"map[string]any", map[string]any{"k1": "v1", "k2": "v2"}, `{"k1":"v1","k2":"v2"}`}, {"Message", &apipb.Method{Name: "example"}, `{"name": "example"}`}, } for _, tc := range testCases { diff --git a/pkg/protoutil/transform_test.go b/pkg/protoutil/transform_test.go index e8270e2ab..0766a871e 100644 --- a/pkg/protoutil/transform_test.go +++ b/pkg/protoutil/transform_test.go @@ -75,7 +75,7 @@ func TestTransform(t *testing.T) { }, }, } - transformed, err := Transform(original, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) (protoreflect.Value, error) { + transformed, err := Transform(original, func(_ protoreflect.FieldDescriptor, v protoreflect.Value) (protoreflect.Value, error) { switch vv := v.Interface().(type) { case []byte: return protoreflect.ValueOfBytes(append([]byte("TRANSFORM_"), vv...)), nil diff --git a/pkg/storage/cache.go b/pkg/storage/cache.go index b780e1e81..ee75cb631 100644 --- a/pkg/storage/cache.go +++ b/pkg/storage/cache.go @@ -47,7 +47,7 @@ func (cache *localCache) GetOrUpdate( return cached, nil } - v, err, _ := cache.singleflight.Do(strkey, func() (interface{}, error) { + v, err, _ := cache.singleflight.Do(strkey, func() (any, error) { cache.mu.RLock() cached, ok := cache.m[strkey] cache.mu.RUnlock() @@ -105,7 +105,7 @@ func (cache *globalCache) GetOrUpdate( return data, nil } - v, err, _ := cache.singleflight.Do(string(key), func() (interface{}, error) { + v, err, _ := cache.singleflight.Do(string(key), func() (any, error) { data, expiry, ok := cache.get(key) if ok && now.Before(expiry) { return data, nil diff --git a/pkg/storage/cache_test.go b/pkg/storage/cache_test.go index 1f73db6e8..132dc201a 100644 --- a/pkg/storage/cache_test.go +++ b/pkg/storage/cache_test.go @@ -14,7 +14,7 @@ func TestLocalCache(t *testing.T) { defer clearTimeout() callCount := 0 - update := func(ctx context.Context) ([]byte, error) { + update := func(_ context.Context) ([]byte, error) { callCount++ return []byte("v1"), nil } @@ -42,7 +42,7 @@ func TestGlobalCache(t *testing.T) { defer clearTimeout() callCount := 0 - update := func(ctx context.Context) ([]byte, error) { + update := func(_ context.Context) ([]byte, error) { callCount++ return []byte("v1"), nil } @@ -65,7 +65,7 @@ func TestGlobalCache(t *testing.T) { assert.Equal(t, 2, callCount) assert.Eventually(t, func() bool { - _, err := c.GetOrUpdate(ctx, []byte("k1"), func(ctx context.Context) ([]byte, error) { + _, err := c.GetOrUpdate(ctx, []byte("k1"), func(_ context.Context) ([]byte, error) { return nil, fmt.Errorf("ERROR") }) return err != nil diff --git a/pkg/storage/filter_test.go b/pkg/storage/filter_test.go index 701d675d8..c0e16d876 100644 --- a/pkg/storage/filter_test.go +++ b/pkg/storage/filter_test.go @@ -9,8 +9,8 @@ import ( ) func TestFilterExpressionFromStruct(t *testing.T) { - type M = map[string]interface{} - type A = []interface{} + type M = map[string]any + type A = []any s, err := structpb.NewStruct(M{ "$and": A{ diff --git a/pkg/storage/index_test.go b/pkg/storage/index_test.go index 60c99dae2..810a5102e 100644 --- a/pkg/storage/index_test.go +++ b/pkg/storage/index_test.go @@ -11,7 +11,7 @@ import ( ) func TestGetRecordIndex(t *testing.T) { - type M = map[string]interface{} + type M = map[string]any t.Run("missing", func(t *testing.T) { v, err := structpb.NewStruct(M{ "notindex": "value", diff --git a/pkg/storage/inmemory/stream.go b/pkg/storage/inmemory/stream.go index 7e8469778..98af671c8 100644 --- a/pkg/storage/inmemory/stream.go +++ b/pkg/storage/inmemory/stream.go @@ -24,7 +24,7 @@ func newSyncLatestRecordStream( } var ready []*databroker.Record - generator := func(ctx context.Context, block bool) (*databroker.Record, error) { + generator := func(_ context.Context, _ bool) (*databroker.Record, error) { backend.mu.RLock() for _, co := range backend.lookup { for _, record := range co.List() { @@ -39,7 +39,7 @@ func newSyncLatestRecordStream( return storage.NewRecordStream(ctx, backend.closed, []storage.RecordStreamGenerator{ generator, - func(ctx context.Context, block bool) (*databroker.Record, error) { + func(_ context.Context, _ bool) (*databroker.Record, error) { if len(ready) == 0 { return nil, storage.ErrStreamDone } diff --git a/pkg/storage/postgres/filter.go b/pkg/storage/postgres/filter.go index 61dc1fe8f..a408005a7 100644 --- a/pkg/storage/postgres/filter.go +++ b/pkg/storage/postgres/filter.go @@ -8,7 +8,7 @@ import ( "github.com/pomerium/pomerium/pkg/storage" ) -func addFilterExpressionToQuery(query *string, args *[]interface{}, expr storage.FilterExpression) error { +func addFilterExpressionToQuery(query *string, args *[]any, expr storage.FilterExpression) error { compoundExpression := func(subexprs []storage.FilterExpression, op string) error { *query += "( " for i, subexpr := range subexprs { diff --git a/pkg/storage/postgres/postgres.go b/pkg/storage/postgres/postgres.go index 570c555b3..5bcf41d42 100644 --- a/pkg/storage/postgres/postgres.go +++ b/pkg/storage/postgres/postgres.go @@ -39,9 +39,9 @@ var ( ) type querier interface { - Exec(ctx context.Context, sql string, arguments ...interface{}) (commandTag pgconn.CommandTag, err error) - Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) - QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row + Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) + Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) + QueryRow(ctx context.Context, sql string, args ...any) pgx.Row } func deleteChangesBefore(ctx context.Context, q querier, cutoff time.Time) error { @@ -207,7 +207,7 @@ func getRecord( } func listRecords(ctx context.Context, q querier, expr storage.FilterExpression, offset, limit int) ([]*databroker.Record, error) { - args := []interface{}{offset, limit} + args := []any{offset, limit} query := ` SELECT type, id, version, data, modified_at FROM ` + schemaName + `.` + recordsTableName + ` diff --git a/pkg/storage/storage.go b/pkg/storage/storage.go index dfdbff6ea..c00ec1693 100644 --- a/pkg/storage/storage.go +++ b/pkg/storage/storage.go @@ -112,7 +112,7 @@ func matchProtoListValue(fd protoreflect.FieldDescriptor, l protoreflect.List, q func matchProtoMapValue(fd protoreflect.FieldDescriptor, m protoreflect.Map, query string) bool { matches := false - m.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { + m.Range(func(_ protoreflect.MapKey, v protoreflect.Value) bool { matches = matches || matchProtoSingularValue(fd, v, query) return !matches }) diff --git a/pkg/storage/stream.go b/pkg/storage/stream.go index a9531c3e3..176b7955f 100644 --- a/pkg/storage/stream.go +++ b/pkg/storage/stream.go @@ -107,7 +107,7 @@ func RecordStreamToList(recordStream RecordStream) ([]*databroker.Record, error) // RecordListToStream converts a record list to a stream. func RecordListToStream(ctx context.Context, records []*databroker.Record) RecordStream { return NewRecordStream(ctx, nil, []RecordStreamGenerator{ - func(ctx context.Context, block bool) (*databroker.Record, error) { + func(_ context.Context, _ bool) (*databroker.Record, error) { if len(records) == 0 { return nil, ErrStreamDone } diff --git a/pkg/storage/stream_filter.go b/pkg/storage/stream_filter.go index 05daccbfb..69e16fb01 100644 --- a/pkg/storage/stream_filter.go +++ b/pkg/storage/stream_filter.go @@ -47,13 +47,13 @@ func RecordStreamFilterFromFilterExpression( expr FilterExpression, ) (filter RecordStreamFilter, err error) { if expr == nil { - return func(record *databroker.Record) (keep bool) { return true }, nil + return func(_ *databroker.Record) (keep bool) { return true }, nil } switch expr := expr.(type) { case AndFilterExpression: if len(expr) == 0 { - return func(record *databroker.Record) (keep bool) { return true }, nil + return func(_ *databroker.Record) (keep bool) { return true }, nil } fs := make([]RecordStreamFilter, len(expr)) @@ -73,7 +73,7 @@ func RecordStreamFilterFromFilterExpression( }, nil case OrFilterExpression: if len(expr) == 0 { - return func(record *databroker.Record) (keep bool) { return true }, nil + return func(_ *databroker.Record) (keep bool) { return true }, nil } fs := make([]RecordStreamFilter, len(expr)) diff --git a/pkg/storage/stream_filter_test.go b/pkg/storage/stream_filter_test.go index a364068c1..9dad3b576 100644 --- a/pkg/storage/stream_filter_test.go +++ b/pkg/storage/stream_filter_test.go @@ -12,7 +12,7 @@ import ( ) func TestRecordStreamFilterFromFilterExpression(t *testing.T) { - type M = map[string]interface{} + type M = map[string]any s, err := structpb.NewStruct(M{ "$index": M{ diff --git a/pkg/telemetry/requestid/grpc_client.go b/pkg/telemetry/requestid/grpc_client.go index b773f1a06..5b85ed7ee 100644 --- a/pkg/telemetry/requestid/grpc_client.go +++ b/pkg/telemetry/requestid/grpc_client.go @@ -23,7 +23,7 @@ func StreamClientInterceptor() grpc.StreamClientInterceptor { // metadata. func UnaryClientInterceptor() grpc.UnaryClientInterceptor { return func(ctx context.Context, - method string, req, reply interface{}, + method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, ) error { ctx = toMetadata(ctx) diff --git a/pkg/telemetry/requestid/grpc_server.go b/pkg/telemetry/requestid/grpc_server.go index 50f89aebf..43f0fb1d0 100644 --- a/pkg/telemetry/requestid/grpc_server.go +++ b/pkg/telemetry/requestid/grpc_server.go @@ -19,7 +19,7 @@ func (ss grpcStream) Context() context.Context { // StreamServerInterceptor returns a new gRPC StreamServerInterceptor which populates the request id // from the incoming metadata. func StreamServerInterceptor() grpc.StreamServerInterceptor { - return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { ctx := ss.Context() requestID := fromMetadata(ctx) ctx = WithValue(ctx, requestID) @@ -34,7 +34,7 @@ func StreamServerInterceptor() grpc.StreamServerInterceptor { // UnaryServerInterceptor returns a new gRPC UnaryServerInterceptor which populates the request id // from the incoming metadata. func UnaryServerInterceptor() grpc.UnaryServerInterceptor { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { requestID := fromMetadata(ctx) ctx = WithValue(ctx, requestID) return handler(ctx, req) diff --git a/pkg/webauthnutil/credential_storage_test.go b/pkg/webauthnutil/credential_storage_test.go index 426b68036..20154318c 100644 --- a/pkg/webauthnutil/credential_storage_test.go +++ b/pkg/webauthnutil/credential_storage_test.go @@ -31,7 +31,7 @@ func (m mockDataBrokerServiceClient) Put(ctx context.Context, in *databroker.Put func TestCredentialStorage(t *testing.T) { m := map[string]*databroker.Record{} client := &mockDataBrokerServiceClient{ - get: func(ctx context.Context, in *databroker.GetRequest, opts ...grpc.CallOption) (*databroker.GetResponse, error) { + get: func(_ context.Context, in *databroker.GetRequest, _ ...grpc.CallOption) (*databroker.GetResponse, error) { record, ok := m[in.GetType()+"/"+in.GetId()] if !ok { return nil, status.Error(codes.NotFound, "record not found") @@ -40,7 +40,7 @@ func TestCredentialStorage(t *testing.T) { Record: record, }, nil }, - put: func(ctx context.Context, in *databroker.PutRequest, opts ...grpc.CallOption) (*databroker.PutResponse, error) { + put: func(_ context.Context, in *databroker.PutRequest, _ ...grpc.CallOption) (*databroker.PutResponse, error) { for _, record := range in.GetRecords() { m[record.GetType()+"/"+record.GetId()] = record } diff --git a/pkg/webauthnutil/device_type_test.go b/pkg/webauthnutil/device_type_test.go index 5ba0a1662..5e0a677a6 100644 --- a/pkg/webauthnutil/device_type_test.go +++ b/pkg/webauthnutil/device_type_test.go @@ -19,7 +19,7 @@ func TestGetDeviceType(t *testing.T) { t.Run("from databroker", func(t *testing.T) { client := &mockDataBrokerServiceClient{ - get: func(ctx context.Context, in *databroker.GetRequest, opts ...grpc.CallOption) (*databroker.GetResponse, error) { + get: func(_ context.Context, in *databroker.GetRequest, _ ...grpc.CallOption) (*databroker.GetResponse, error) { assert.Equal(t, "type.googleapis.com/pomerium.device.Type", in.GetType()) assert.Equal(t, "any", in.GetId()) data, _ := anypb.New(&device.Type{ @@ -40,7 +40,7 @@ func TestGetDeviceType(t *testing.T) { }) t.Run("default", func(t *testing.T) { client := &mockDataBrokerServiceClient{ - get: func(ctx context.Context, in *databroker.GetRequest, opts ...grpc.CallOption) (*databroker.GetResponse, error) { + get: func(_ context.Context, _ *databroker.GetRequest, _ ...grpc.CallOption) (*databroker.GetResponse, error) { return nil, status.Error(codes.NotFound, "not found") }, } diff --git a/proxy/proxy.go b/proxy/proxy.go index ad3e86bf3..8d3c78c18 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -107,7 +107,7 @@ func (p *Proxy) setHandlers(opts *config.Options) error { log.Warn(context.TODO()).Msg("proxy: configuration has no policies") } r := httputil.NewRouter() - r.NotFoundHandler = httputil.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { + r.NotFoundHandler = httputil.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) error { return httputil.NewError(http.StatusNotFound, fmt.Errorf("%s route unknown", r.Host)) }) r.SkipClean(true)