core/lint: upgrade golangci-lint, replace interface{} with any (#5099)

* core/lint: upgrade golangci-lint, replace interface{} with any

* regen proto
This commit is contained in:
Caleb Doxsey 2024-05-02 14:33:52 -06:00 committed by GitHub
parent 614048ae9c
commit 1a5b8b606f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
135 changed files with 341 additions and 340 deletions

View file

@ -22,5 +22,5 @@ jobs:
- uses: golangci/golangci-lint-action@9d1e0624a798bb64f6c3cea93db47765312263dc - uses: golangci/golangci-lint-action@9d1e0624a798bb64f6c3cea93db47765312263dc
with: with:
version: v1.55 version: v1.57
args: --timeout=10m args: --timeout=10m

View file

@ -1 +1,2 @@
golang 1.22.0 golang 1.22.0
golangci-lint 1.57.2

View file

@ -87,7 +87,7 @@ build-ui: yarn
.PHONY: lint .PHONY: lint
lint: ## Verifies `golint` passes. lint: ## Verifies `golint` passes.
@echo "==> $@" @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 .PHONY: test
test: get-envoy ## Runs the go tests. test: get-envoy ## Runs the go tests.

View file

@ -225,7 +225,7 @@ func TestAuthenticate_SignOut(t *testing.T) {
ctrl := gomock.NewController(t) ctrl := gomock.NewController(t)
defer ctrl.Finish() defer ctrl.Finish()
a := &Authenticate{ 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 return tt.provider, nil
})), })),
state: atomicutil.NewValue(&authenticateState{ state: atomicutil.NewValue(&authenticateState{
@ -280,7 +280,7 @@ func TestAuthenticate_SignOutDoesNotRequireSession(t *testing.T) {
sessionStore := &mstore.Store{LoadError: errors.New("no session")} sessionStore := &mstore.Store{LoadError: errors.New("no session")}
a := &Authenticate{ 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 return identity.MockProvider{}, nil
})), })),
state: atomicutil.NewValue(&authenticateState{ state: atomicutil.NewValue(&authenticateState{
@ -355,7 +355,7 @@ func TestAuthenticate_OAuthCallback(t *testing.T) {
} }
authURL, _ := url.Parse(tt.authenticateURL) authURL, _ := url.Parse(tt.authenticateURL)
a := &Authenticate{ 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 return tt.provider, nil
})), })),
state: atomicutil.NewValue(&authenticateState{ state: atomicutil.NewValue(&authenticateState{
@ -401,7 +401,7 @@ func TestAuthenticate_OAuthCallback(t *testing.T) {
func TestAuthenticate_SessionValidatorMiddleware(t *testing.T) { func TestAuthenticate_SessionValidatorMiddleware(t *testing.T) {
t.Parallel() 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") w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "RVSI FILIVS CAISAR") fmt.Fprintln(w, "RVSI FILIVS CAISAR")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -467,7 +467,7 @@ func TestAuthenticate_SessionValidatorMiddleware(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
a := &Authenticate{ 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 return tt.provider, nil
})), })),
state: atomicutil.NewValue(&authenticateState{ state: atomicutil.NewValue(&authenticateState{

View file

@ -55,7 +55,7 @@ func TestAccessTracker(t *testing.T) {
} }
tracker := NewAccessTracker(&testAccessTrackerProvider{ tracker := NewAccessTracker(&testAccessTrackerProvider{
dataBrokerServiceClient: &mockDataBrokerServiceClient{ 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() mu.Lock()
defer mu.Unlock() defer mu.Unlock()
@ -88,7 +88,7 @@ func TestAccessTracker(t *testing.T) {
return nil, status.Errorf(codes.InvalidArgument, "unknown type: %s", in.GetType()) 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() mu.Lock()
defer mu.Unlock() defer mu.Unlock()

View file

@ -34,7 +34,7 @@ var (
types.Args(types.S, types.S), types.Args(types.S, types.S),
types.NewObject(nil, types.NewDynamicProperty(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) serviceAccount, ok := op1.Value.(ast.String)
if !ok { if !ok {
return nil, fmt.Errorf("invalid service account type: %T", op1) return nil, fmt.Errorf("invalid service account type: %T", op1)
@ -65,7 +65,7 @@ type gcpIdentityTokenSource struct {
} }
func (src *gcpIdentityTokenSource) Token() (*oauth2.Token, error) { 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{ req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, GCPIdentityDocURL+"?"+url.Values{
"format": {"full"}, "format": {"full"},
"audience": {src.audience}, "audience": {src.audience},

View file

@ -62,7 +62,7 @@ var variableSubstitutionFunctionRegoOption = rego.Function2(&rego.Function{
), ),
types.Named("output", types.S), 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) inputString, ok := op1.Value.(ast.String)
if !ok { if !ok {
return nil, fmt.Errorf("invalid input_string type: %T", op1.Value) 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 { func (e *HeadersEvaluator) getHeader(vars rego.Vars) http.Header {
h := make(http.Header) h := make(http.Header)
m, ok := vars["result"].(map[string]interface{}) m, ok := vars["result"].(map[string]any)
if !ok { if !ok {
return h return h
} }
m, ok = m["identity_headers"].(map[string]interface{}) m, ok = m["identity_headers"].(map[string]any)
if !ok { if !ok {
return h return h
} }
for k := range m { for k := range m {
vs, ok := m[k].([]interface{}) vs, ok := m[k].([]any)
if !ok { if !ok {
continue continue
} }

View file

@ -62,8 +62,8 @@ func TestNewHeadersRequestFromPolicy_nil(t *testing.T) {
func TestHeadersEvaluator(t *testing.T) { func TestHeadersEvaluator(t *testing.T) {
t.Parallel() t.Parallel()
type A = []interface{} type A = []any
type M = map[string]interface{} type M = map[string]any
signingKey, err := cryptutil.NewSigningKey() signingKey, err := cryptutil.NewSigningKey()
require.NoError(t, err) require.NoError(t, err)
@ -114,7 +114,7 @@ func TestHeadersEvaluator(t *testing.T) {
// between numeric formats. // between numeric formats.
d := json.NewDecoder(bytes.NewReader(decodeJWSPayload(t, jwtHeader))) d := json.NewDecoder(bytes.NewReader(decodeJWSPayload(t, jwtHeader)))
d.UseNumber() d.UseNumber()
var jwtPayloadDecoded map[string]interface{} var jwtPayloadDecoded map[string]any
err = d.Decode(&jwtPayloadDecoded) err = d.Decode(&jwtPayloadDecoded)
require.NoError(t, err) require.NoError(t, err)

View file

@ -43,7 +43,7 @@ func NewPolicyResponse() *PolicyResponse {
type RuleResult struct { type RuleResult struct {
Value bool Value bool
Reasons criteria.Reasons Reasons criteria.Reasons
AdditionalData map[string]interface{} AdditionalData map[string]any
} }
// NewRuleResult creates a new RuleResult. // NewRuleResult creates a new RuleResult.
@ -51,7 +51,7 @@ func NewRuleResult(value bool, reasons ...criteria.Reason) RuleResult {
return RuleResult{ return RuleResult{
Value: value, Value: value,
Reasons: criteria.NewReasons(reasons...), 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) { func (e *PolicyEvaluator) getRuleResult(name string, vars rego.Vars) (result RuleResult) {
result = NewRuleResult(false) result = NewRuleResult(false)
m, ok := vars["result"].(map[string]interface{}) m, ok := vars["result"].(map[string]any)
if !ok { if !ok {
return result return result
} }
@ -244,10 +244,10 @@ func (e *PolicyEvaluator) getRuleResult(name string, vars rego.Vars) (result Rul
switch t := m[name].(type) { switch t := m[name].(type) {
case bool: case bool:
result.Value = t result.Value = t
case []interface{}: case []any:
switch len(t) { switch len(t) {
case 3: case 3:
v, ok := t[2].(map[string]interface{}) v, ok := t[2].(map[string]any)
if ok { if ok {
for k, vv := range v { for k, vv := range v {
result.AdditionalData[k] = vv result.AdditionalData[k] = vv
@ -256,7 +256,7 @@ func (e *PolicyEvaluator) getRuleResult(name string, vars rego.Vars) (result Rul
fallthrough fallthrough
case 2: case 2:
// fill in the reasons // fill in the reasons
v, ok := t[1].([]interface{}) v, ok := t[1].([]any)
if ok { if ok {
for _, vv := range v { for _, vv := range v {
result.Reasons.Add(criteria.Reason(fmt.Sprint(vv))) result.Reasons.Add(criteria.Reason(fmt.Sprint(vv)))

View file

@ -58,7 +58,7 @@ func (s *Store) UpdateSigningKey(signingKey *jose.JSONWebKey) {
s.write("/signing_key", signingKey) s.write("/signing_key", signingKey)
} }
func (s *Store) write(rawPath string, value interface{}) { func (s *Store) write(rawPath string, value any) {
ctx := context.TODO() ctx := context.TODO()
err := opastorage.Txn(ctx, s.Store, opastorage.WriteParams, func(txn opastorage.Transaction) error { err := opastorage.Txn(ctx, s.Store, opastorage.WriteParams, func(txn opastorage.Transaction) error {
return s.writeTxn(txn, rawPath, value) 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) p, ok := opastorage.ParsePath(rawPath)
if !ok { if !ok {
return fmt.Errorf("invalid path") 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) bs, _ := json.Marshal(msg)
var obj map[string]interface{} var obj map[string]any
_ = json.Unmarshal(bs, &obj) _ = json.Unmarshal(bs, &obj)
return obj return obj
} }

View file

@ -64,7 +64,7 @@ func TestAutocertOptions_Validate(t *testing.T) {
cleanup func() cleanup func()
} }
tests := map[string]func(t *testing.T) test{ 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{ return test{
fields: fields{ fields: fields{
CA: "test-ca.example.com/directory", CA: "test-ca.example.com/directory",
@ -72,7 +72,7 @@ func TestAutocertOptions_Validate(t *testing.T) {
wantErr: false, wantErr: false,
} }
}, },
"ok/eab": func(t *testing.T) test { "ok/eab": func(_ *testing.T) test {
return test{ return test{
fields: fields{ fields: fields{
EABKeyID: "keyID", EABKeyID: "keyID",
@ -81,7 +81,7 @@ func TestAutocertOptions_Validate(t *testing.T) {
wantErr: false, wantErr: false,
} }
}, },
"ok/trusted-ca": func(t *testing.T) test { "ok/trusted-ca": func(_ *testing.T) test {
return test{ return test{
fields: fields{ fields: fields{
TrustedCA: base64.StdEncoding.EncodeToString(certPEM), TrustedCA: base64.StdEncoding.EncodeToString(certPEM),
@ -103,7 +103,7 @@ func TestAutocertOptions_Validate(t *testing.T) {
cleanup: func() { os.Remove(f.Name()) }, 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{ return test{
fields: fields{ fields: fields{
EABKeyID: "keyID", EABKeyID: "keyID",
@ -111,7 +111,7 @@ func TestAutocertOptions_Validate(t *testing.T) {
wantErr: true, wantErr: true,
} }
}, },
"fail/missing-eab-key-id": func(t *testing.T) test { "fail/missing-eab-key-id": func(_ *testing.T) test {
return test{ return test{
fields: fields{ fields: fields{
EABMACKey: "29D7t6-mOuEV5vvBRX0UYF5T7x6fomidhM1kMJco-yw", EABMACKey: "29D7t6-mOuEV5vvBRX0UYF5T7x6fomidhM1kMJco-yw",
@ -119,7 +119,7 @@ func TestAutocertOptions_Validate(t *testing.T) {
wantErr: true, wantErr: true,
} }
}, },
"fail/invalid-mac-key": func(t *testing.T) test { "fail/invalid-mac-key": func(_ *testing.T) test {
return test{ return test{
fields: fields{ fields: fields{
EABMACKey: ">invalid-base64-url-encoded-mac-key<", EABMACKey: ">invalid-base64-url-encoded-mac-key<",
@ -142,7 +142,7 @@ func TestAutocertOptions_Validate(t *testing.T) {
cleanup: func() { os.Remove(f.Name()) }, 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{ return test{
fields: fields{ fields: fields{
TrustedCA: ">invalid-base-64-data<", TrustedCA: ">invalid-base-64-data<",
@ -150,7 +150,7 @@ func TestAutocertOptions_Validate(t *testing.T) {
wantErr: true, wantErr: true,
} }
}, },
"fail/trusted-ca-missing-file": func(t *testing.T) test { "fail/trusted-ca-missing-file": func(_ *testing.T) test {
return test{ return test{
fields: fields{ fields: fields{
TrustedCAFile: "some-non-existing-file", TrustedCAFile: "some-non-existing-file",

View file

@ -57,7 +57,7 @@ func (codecType CodecType) ToEnvoy() envoy_http_connection_manager.HttpConnectio
} }
func decodeCodecTypeHookFunc() mapstructure.DecodeHookFunc { 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("")) { if t != reflect.TypeOf(CodecType("")) {
return data, nil return data, nil
} }

View file

@ -38,7 +38,7 @@ func TestFileWatcherSource(t *testing.T) {
src := NewFileWatcherSource(ctx, ssrc) src := NewFileWatcherSource(ctx, ssrc)
var closeOnce sync.Once var closeOnce sync.Once
ch := make(chan struct{}) 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() { closeOnce.Do(func() {
close(ch) close(ch)
}) })

View file

@ -24,7 +24,7 @@ import (
) )
func decodeNullBoolHookFunc() mapstructure.DecodeHookFunc { 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{}) { if t != reflect.TypeOf(null.Bool{}) {
return data, nil return data, nil
} }
@ -57,7 +57,7 @@ func NewJWTClaimHeaders(claims ...string) JWTClaimHeaders {
// UnmarshalJSON unmarshals JSON data into the JWTClaimHeaders. // UnmarshalJSON unmarshals JSON data into the JWTClaimHeaders.
func (hdrs *JWTClaimHeaders) UnmarshalJSON(data []byte) error { func (hdrs *JWTClaimHeaders) UnmarshalJSON(data []byte) error {
var m map[string]interface{} var m map[string]any
if json.Unmarshal(data, &m) == nil { if json.Unmarshal(data, &m) == nil {
*hdrs = make(map[string]string) *hdrs = make(map[string]string)
for k, v := range m { for k, v := range m {
@ -67,7 +67,7 @@ func (hdrs *JWTClaimHeaders) UnmarshalJSON(data []byte) error {
return nil return nil
} }
var a []interface{} var a []any
if json.Unmarshal(data, &a) == nil { if json.Unmarshal(data, &a) == nil {
var vs []string var vs []string
for _, v := range a { 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. // UnmarshalYAML uses UnmarshalJSON to unmarshal YAML data into the JWTClaimHeaders.
func (hdrs *JWTClaimHeaders) UnmarshalYAML(unmarshal func(interface{}) error) error { func (hdrs *JWTClaimHeaders) UnmarshalYAML(unmarshal func(any) error) error {
var i interface{} var i any
err := unmarshal(&i) err := unmarshal(&i)
if err != nil { if err != nil {
return err return err
@ -110,7 +110,7 @@ func (hdrs *JWTClaimHeaders) UnmarshalYAML(unmarshal func(interface{}) error) er
} }
func decodeJWTClaimHeadersHookFunc() mapstructure.DecodeHookFunc { 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{}) { if t != reflect.TypeOf(JWTClaimHeaders{}) {
return data, nil 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 // UnmarshalYAML unmarshals a YAML document into the string slice. UnmarshalJSON is
// reused as the actual implementation. // reused as the actual implementation.
func (slc *StringSlice) UnmarshalYAML(unmarshal func(interface{}) error) error { func (slc *StringSlice) UnmarshalYAML(unmarshal func(any) error) error {
var i interface{} var i any
err := unmarshal(&i) err := unmarshal(&i)
if err != nil { if err != nil {
return err return err
@ -350,8 +350,8 @@ func (ppl *PPLPolicy) UnmarshalJSON(data []byte) error {
} }
// UnmarshalYAML parses YAML into a PPL policy. // UnmarshalYAML parses YAML into a PPL policy.
func (ppl *PPLPolicy) UnmarshalYAML(unmarshal func(interface{}) error) error { func (ppl *PPLPolicy) UnmarshalYAML(unmarshal func(any) error) error {
var i interface{} var i any
err := unmarshal(&i) err := unmarshal(&i)
if err != nil { if err != nil {
return err return err
@ -364,7 +364,7 @@ func (ppl *PPLPolicy) UnmarshalYAML(unmarshal func(interface{}) error) error {
} }
func decodePPLPolicyHookFunc() mapstructure.DecodeHookFunc { 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{}) { if t != reflect.TypeOf(&PPLPolicy{}) {
return data, nil return data, nil
} }
@ -383,7 +383,7 @@ func decodePPLPolicyHookFunc() mapstructure.DecodeHookFunc {
// DecodePolicyBase64Hook returns a mapstructure decode hook for base64 data. // DecodePolicyBase64Hook returns a mapstructure decode hook for base64 data.
func DecodePolicyBase64Hook() mapstructure.DecodeHookFunc { 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{}) { if t != reflect.TypeOf([]Policy{}) {
return data, nil return data, nil
} }
@ -402,7 +402,7 @@ func DecodePolicyBase64Hook() mapstructure.DecodeHookFunc {
return nil, fmt.Errorf("base64 decoding policy data: %w", err) 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 { if err = yaml.Unmarshal(bytes, &out); err != nil {
return nil, fmt.Errorf("parsing base64-encoded policy data as yaml: %w", err) 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. // DecodePolicyHookFunc returns a Decode Hook for mapstructure.
func DecodePolicyHookFunc() mapstructure.DecodeHookFunc { 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{}) { if t != reflect.TypeOf(Policy{}) {
return data, nil return data, nil
} }
@ -424,7 +424,7 @@ func DecodePolicyHookFunc() mapstructure.DecodeHookFunc {
if err != nil { if err != nil {
return nil, err return nil, err
} }
ms, ok := mp.(map[string]interface{}) ms, ok := mp.(map[string]any)
if !ok { if !ok {
return nil, errKeysMustBeStrings return nil, errKeysMustBeStrings
} }
@ -433,8 +433,8 @@ func DecodePolicyHookFunc() mapstructure.DecodeHookFunc {
} }
} }
func parsePolicy(src map[string]interface{}) (out map[string]interface{}, err error) { func parsePolicy(src map[string]any) (out map[string]any, err error) {
out = make(map[string]interface{}, len(src)) out = make(map[string]any, len(src))
for k, v := range src { for k, v := range src {
if k == toKey { if k == toKey {
if v, err = parseTo(v); err != nil { 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 return out, nil
} }
func parseTo(raw interface{}) ([]WeightedURL, error) { func parseTo(raw any) ([]WeightedURL, error) {
rawBS, err := json.Marshal(raw) rawBS, err := json.Marshal(raw)
if err != nil { if err != nil {
return nil, err 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 // 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 // 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) c := new(envoy_config_cluster_v3.Cluster)
if err := parseJSONPB(src, c, protoPartial); err != nil { if err := parseJSONPB(src, c, protoPartial); err != nil {
return nil, err 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 // parseJSONPB takes an intermediate representation and parses it using protobuf parser
// that correctly handles oneof and other data types // 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) data, err := json.Marshal(src)
if err != nil { if err != nil {
return err 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. // decodeSANMatcherHookFunc returns a decode hook for the SANMatcher type.
func decodeSANMatcherHookFunc() mapstructure.DecodeHookFunc { 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{}) { if t != reflect.TypeOf(SANMatcher{}) {
return data, nil 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 // serializable converts mapstructure nested map into map[string]any that is serializable to JSON
func serializable(in interface{}) (interface{}, error) { func serializable(in any) (any, error) {
switch typed := in.(type) { switch typed := in.(type) {
case map[interface{}]interface{}: case map[any]any:
m := make(map[string]interface{}) m := make(map[string]any)
for k, v := range typed { for k, v := range typed {
kstr, ok := k.(string) kstr, ok := k.(string)
if !ok { if !ok {
@ -560,8 +560,8 @@ func serializable(in interface{}) (interface{}, error) {
m[kstr] = val m[kstr] = val
} }
return m, nil return m, nil
case []interface{}: case []any:
out := make([]interface{}, 0, len(typed)) out := make([]any, 0, len(typed))
for _, elem := range typed { for _, elem := range typed {
val, err := serializable(elem) val, err := serializable(elem)
if err != nil { if err != nil {

View file

@ -136,7 +136,7 @@ func TestSerializable(t *testing.T) {
data, err := base64.StdEncoding.DecodeString("aGVhbHRoX2NoZWNrOgogIHRpbWVvdXQ6IDVzCiAgaW50ZXJ2YWw6IDYwcwogIGhlYWx0aHlUaHJlc2hvbGQ6IDEKICB1bmhlYWx0aHlUaHJlc2hvbGQ6IDIKICBodHRwX2hlYWx0aF9jaGVjazogCiAgICBob3N0OiAiaHR0cDovL2xvY2FsaG9zdDo4MDgwIgogICAgcGF0aDogIi8iCg==") data, err := base64.StdEncoding.DecodeString("aGVhbHRoX2NoZWNrOgogIHRpbWVvdXQ6IDVzCiAgaW50ZXJ2YWw6IDYwcwogIGhlYWx0aHlUaHJlc2hvbGQ6IDEKICB1bmhlYWx0aHlUaHJlc2hvbGQ6IDIKICBodHRwX2hlYWx0aF9jaGVjazogCiAgICBob3N0OiAiaHR0cDovL2xvY2FsaG9zdDo4MDgwIgogICAgcGF0aDogIi8iCg==")
require.NoError(t, err, "decode") require.NoError(t, err, "decode")
var mi map[interface{}]interface{} var mi map[any]any
err = yaml.Unmarshal(data, &mi) err = yaml.Unmarshal(data, &mi)
require.NoError(t, err, "unmarshal") require.NoError(t, err, "unmarshal")
@ -158,11 +158,11 @@ func TestDecodePPLPolicyHookFunc(t *testing.T) {
}) })
require.NoError(t, err) require.NoError(t, err)
err = decoder.Decode(map[string]interface{}{ err = decoder.Decode(map[string]any{
"policy": map[string]interface{}{ "policy": map[string]any{
"allow": map[string]interface{}{ "allow": map[string]any{
"or": []map[string]interface{}{ "or": []map[string]any{
{"email": map[string]interface{}{ {"email": map[string]any{
"is": "user1@example.com", "is": "user1@example.com",
}}, }},
}, },

View file

@ -149,7 +149,7 @@ func (b *Builder) BuildBootstrapDynamicResources(
// BuildBootstrapLayeredRuntime builds the layered runtime for the envoy bootstrap. // BuildBootstrapLayeredRuntime builds the layered runtime for the envoy bootstrap.
func (b *Builder) BuildBootstrapLayeredRuntime() (*envoy_config_bootstrap_v3.LayeredRuntime, error) { 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{ "re2": map[string]any{
"max_program_size": map[string]any{ "max_program_size": map[string]any{
"error_level": 1024 * 1024, "error_level": 1024 * 1024,

View file

@ -32,7 +32,7 @@ var (
testDataTemplate = template.Must(template.ParseFS(testDataFS, "testdata/*.json")) 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() t.Helper()
var buf bytes.Buffer var buf bytes.Buffer
err := testDataTemplate.ExecuteTemplate(&buf, name, data) err := testDataTemplate.ExecuteTemplate(&buf, name, data)

View file

@ -26,11 +26,11 @@ func TestLuaCleanUpstream(t *testing.T) {
"x-pomerium-authorization": "JWT", "x-pomerium-authorization": "JWT",
"cookie": "cookieA=aaa_pomerium=123; cookieb=bbb; _pomerium=ey;_pomerium_test1=stillhere ; _pomerium_test2=stillhere", "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_authorization": true,
"remove_pomerium_cookie": "_pomerium", "remove_pomerium_cookie": "_pomerium",
} }
dynamicMetadata := map[string]map[string]interface{}{} dynamicMetadata := map[string]map[string]any{}
handle := newLuaResponseHandle(L, headers, metadata, dynamicMetadata) handle := newLuaResponseHandle(L, headers, metadata, dynamicMetadata)
err = L.CallByParam(lua.P{ err = L.CallByParam(lua.P{
@ -59,14 +59,14 @@ func TestLuaRewriteHeaders(t *testing.T) {
headers := map[string]string{ headers := map[string]string{
"Location": "https://domain-with-dashes:8080/two/some/uri/", "Location": "https://domain-with-dashes:8080/two/some/uri/",
} }
metadata := map[string]interface{}{ metadata := map[string]any{
"rewrite_response_headers": []interface{}{ "rewrite_response_headers": []any{
map[string]interface{}{ map[string]any{
"header": "Location", "header": "Location",
"prefix": "https://domain-with-dashes:8080/two/", "prefix": "https://domain-with-dashes:8080/two/",
"value": "https://frontend/one/", "value": "https://frontend/one/",
}, },
map[string]interface{}{ map[string]any{
"header": "SomeOtherHeader", "header": "SomeOtherHeader",
"prefix": "x", "prefix": "x",
"value": "y", "value": "y",
@ -87,8 +87,8 @@ func TestLuaRewriteHeaders(t *testing.T) {
func newLuaResponseHandle(L *lua.LState, func newLuaResponseHandle(L *lua.LState,
headers map[string]string, headers map[string]string,
metadata map[string]interface{}, metadata map[string]any,
dynamicMetadata map[string]map[string]interface{}, dynamicMetadata map[string]map[string]any,
) lua.LValue { ) lua.LValue {
return newLuaType(L, map[string]lua.LGFunction{ return newLuaType(L, map[string]lua.LGFunction{
"headers": func(L *lua.LState) int { "headers": func(L *lua.LState) int {
@ -145,7 +145,7 @@ func newLuaHeaders(L *lua.LState, headers map[string]string) lua.LValue {
return tbl 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{ return newLuaType(L, map[string]lua.LGFunction{
"get": func(L *lua.LState) int { "get": func(L *lua.LState) int {
_ = L.CheckTable(1) _ = 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{ return newLuaType(L, map[string]lua.LGFunction{
"get": func(L *lua.LState) int { "get": func(L *lua.LState) int {
_ = L.CheckTable(1) _ = L.CheckTable(1)
@ -186,7 +186,7 @@ func newLuaDynamicMetadata(L *lua.LState, metadata map[string]map[string]interfa
m, ok := metadata[filterName] m, ok := metadata[filterName]
if !ok { if !ok {
m = make(map[string]interface{}) m = make(map[string]any)
metadata[filterName] = m metadata[filterName] = m
} }
m[key] = fromLua(L, value) 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{ return newLuaType(L, map[string]lua.LGFunction{
"dynamicMetadata": func(L *lua.LState) int { "dynamicMetadata": func(L *lua.LState) int {
L.Push(newLuaDynamicMetadata(L, dynamicMetadata)) L.Push(newLuaDynamicMetadata(L, dynamicMetadata))
@ -215,7 +215,7 @@ func newLuaType(L *lua.LState, funcs map[string]lua.LGFunction) lua.LValue {
return tbl return tbl
} }
func fromLua(L *lua.LState, v lua.LValue) interface{} { func fromLua(L *lua.LState, v lua.LValue) any {
switch v.Type() { switch v.Type() {
case lua.LTNil: case lua.LTNil:
return nil return nil
@ -226,8 +226,8 @@ func fromLua(L *lua.LState, v lua.LValue) interface{} {
case lua.LTString: case lua.LTString:
return string(v.(lua.LString)) return string(v.(lua.LString))
case lua.LTTable: case lua.LTTable:
a := []interface{}{} a := []any{}
m := map[string]interface{}{} m := map[string]any{}
v.(*lua.LTable).ForEach(func(key, value lua.LValue) { v.(*lua.LTable).ForEach(func(key, value lua.LValue) {
if key.Type() == lua.LTNumber { if key.Type() == lua.LTNumber {
a = append(a, fromLua(L, value)) 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 // send the object through JSON to remove custom types
var normalized interface{} var normalized any
bs, err := json.Marshal(obj) bs, err := json.Marshal(obj)
if err != nil { if err != nil {
panic(err) panic(err)
@ -261,13 +261,13 @@ func toLua(L *lua.LState, obj interface{}) lua.LValue {
} }
switch t := normalized.(type) { switch t := normalized.(type) {
case []interface{}: case []any:
tbl := L.NewTable() tbl := L.NewTable()
for _, v := range t { for _, v := range t {
tbl.Append(toLua(L, v)) tbl.Append(toLua(L, v))
} }
return tbl return tbl
case map[string]interface{}: case map[string]any:
tbl := L.NewTable() tbl := L.NewTable()
for k, v := range t { for k, v := range t {
L.SetField(tbl, k, toLua(L, v)) L.SetField(tbl, k, toLua(L, v))

View file

@ -645,7 +645,7 @@ func getRewriteHeadersMetadata(headers []config.RewriteHeader) *structpb.Value {
}, },
} }
} }
var obj interface{} var obj any
bs, _ := json.Marshal(headers) bs, _ := json.Marshal(headers)
_ = json.Unmarshal(bs, &obj) _ = json.Unmarshal(bs, &obj)
v, _ := structpb.NewValue(obj) v, _ := structpb.NewValue(obj)

View file

@ -18,7 +18,7 @@ func getLocalCertPEM(s *httptest.Server) []byte {
} }
func TestHTTPTransport(t *testing.T) { 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) w.WriteHeader(http.StatusOK)
})) }))
defer s.Close() defer s.Close()
@ -44,7 +44,7 @@ func TestPolicyHTTPTransport(t *testing.T) {
src := NewStaticSource(&Config{Options: &Options{}}) src := NewStaticSource(&Config{Options: &Options{}})
http.DefaultTransport = NewHTTPTransport(src) 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) w.WriteHeader(http.StatusOK)
})) }))
defer s.Close() defer s.Close()

View file

@ -21,7 +21,7 @@ func TestLayeredConfig(t *testing.T) {
t.Run("error on initial build", func(t *testing.T) { t.Run("error on initial build", func(t *testing.T) {
underlying := config.NewStaticSource(&config.Config{}) 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") return errors.New("error")
}) })
require.Error(t, err) require.Error(t, err)
@ -39,7 +39,7 @@ func TestLayeredConfig(t *testing.T) {
var dst atomic.Pointer[config.Config] var dst atomic.Pointer[config.Config]
dst.Store(layered.GetConfig()) 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) dst.Store(c)
}) })

View file

@ -22,7 +22,7 @@ func TestMetricsManager(t *testing.T) {
mgr := NewMetricsManager(ctx, src) mgr := NewMetricsManager(ctx, src)
srv1 := httptest.NewServer(mgr) srv1 := httptest.NewServer(mgr)
defer srv1.Close() 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) http.Error(w, "ERROR", http.StatusInternalServerError)
})) }))
defer srv2.Close() defer srv2.Close()

View file

@ -474,7 +474,7 @@ func (o *Options) parsePolicy() error {
return nil return nil
} }
func (o *Options) viperSet(key string, value interface{}) { func (o *Options) viperSet(key string, value any) {
o.viper.Set(key, value) o.viper.Set(key, value)
} }

View file

@ -205,7 +205,7 @@ func Test_parseHeaders(t *testing.T) {
name string name string
want map[string]string want map[string]string
envHeaders string envHeaders string
viperHeaders interface{} viperHeaders any
wantErr bool wantErr bool
}{ }{
{ {
@ -513,7 +513,7 @@ func Test_AutoCertOptionsFromEnvVar(t *testing.T) {
} }
tests := map[string]func(t *testing.T) test{ 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{ envs := map[string]string{
"AUTOCERT": "true", "AUTOCERT": "true",
"AUTOCERT_DIR": "/test", "AUTOCERT_DIR": "/test",

View file

@ -17,21 +17,21 @@ func TestPolicy_ToPPL(t *testing.T) {
AllowAnyAuthenticatedUser: true, AllowAnyAuthenticatedUser: true,
AllowedDomains: []string{"a.example.com", "b.example.com"}, AllowedDomains: []string{"a.example.com", "b.example.com"},
AllowedUsers: []string{"user1", "user2"}, AllowedUsers: []string{"user1", "user2"},
AllowedIDPClaims: map[string][]interface{}{ AllowedIDPClaims: map[string][]any{
"family_name": {"Smith", "Jones"}, "family_name": {"Smith", "Jones"},
}, },
SubPolicies: []SubPolicy{ SubPolicies: []SubPolicy{
{ {
AllowedDomains: []string{"c.example.com", "d.example.com"}, AllowedDomains: []string{"c.example.com", "d.example.com"},
AllowedUsers: []string{"user3", "user4"}, AllowedUsers: []string{"user3", "user4"},
AllowedIDPClaims: map[string][]interface{}{ AllowedIDPClaims: map[string][]any{
"given_name": {"John"}, "given_name": {"John"},
}, },
}, },
{ {
AllowedDomains: []string{"e.example.com"}, AllowedDomains: []string{"e.example.com"},
AllowedUsers: []string{"user5"}, AllowedUsers: []string{"user5"},
AllowedIDPClaims: map[string][]interface{}{ AllowedIDPClaims: map[string][]any{
"timezone": {"EST"}, "timezone": {"EST"},
}, },
}, },

View file

@ -102,7 +102,7 @@ func TestTraceManager(t *testing.T) {
incoming := make(chan Request, 100) 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 { var objs []struct {
Name string Name string
} }

View file

@ -67,7 +67,7 @@ func TestServerSync(t *testing.T) {
serverVersion = res.GetServerVersion() serverVersion = res.GetServerVersion()
} }
t.Run("Sync ok", func(t *testing.T) { t.Run("Sync ok", func(_ *testing.T) {
client, _ := c.Sync(ctx, &databroker.SyncRequest{ client, _ := c.Sync(ctx, &databroker.SyncRequest{
ServerVersion: serverVersion, ServerVersion: serverVersion,
}) })

View file

@ -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 assert.Condition(t, func() bool {
return res.StatusCode == http.StatusForbidden || res.StatusCode == http.StatusUnauthorized return res.StatusCode == http.StatusForbidden || res.StatusCode == http.StatusUnauthorized
}, msgAndArgs...) }, msgAndArgs...)

View file

@ -20,13 +20,13 @@ import (
func main() { func main() {
generateCmd := &ffcli.Command{ generateCmd := &ffcli.Command{
Name: "generate-configuration", Name: "generate-configuration",
Exec: func(ctx context.Context, args []string) error { Exec: func(ctx context.Context, _ []string) error {
return runGenerateConfiguration(ctx) return runGenerateConfiguration(ctx)
}, },
} }
rootCmd := &ffcli.Command{ rootCmd := &ffcli.Command{
Subcommands: []*ffcli.Command{generateCmd}, Subcommands: []*ffcli.Command{generateCmd},
Exec: func(ctx context.Context, args []string) error { Exec: func(_ context.Context, _ []string) error {
return flag.ErrHelp return flag.ErrHelp
}, },
} }

View file

@ -97,7 +97,7 @@ func getClient(t testing.TB) *http.Client {
} }
return &http.Client{ return &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error { CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse return http.ErrUseLastResponse
}, },
Transport: getTransport(t), Transport: getTransport(t),

View file

@ -514,11 +514,11 @@ func TestPomeriumJWT(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
defer res.Body.Close() defer res.Body.Close()
var m map[string]interface{} var m map[string]any
err = json.NewDecoder(res.Body).Decode(&m) err = json.NewDecoder(res.Body).Decode(&m)
require.NoError(t, err) require.NoError(t, err)
headers, ok := m["headers"].(map[string]interface{}) headers, ok := m["headers"].(map[string]any)
require.True(t, ok) require.True(t, ok)
headerJWT, ok := headers["x-pomerium-jwt-assertion"].(string) headerJWT, ok := headers["x-pomerium-jwt-assertion"].(string)
require.True(t, ok) require.True(t, ok)
@ -554,7 +554,7 @@ func TestPomeriumJWT(t *testing.T) {
assert.Equal(t, p, p2) 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() t.Helper()
s := strings.Split(jwt, ".") s := strings.Split(jwt, ".")
require.Equal(t, 3, len(s), "unexpected JWT format") 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") require.NoError(t, err, "JWT payload could not be decoded")
d := json.NewDecoder(bytes.NewReader(payload)) d := json.NewDecoder(bytes.NewReader(payload))
d.UseNumber() d.UseNumber()
var decoded map[string]interface{} var decoded map[string]any
err = d.Decode(&decoded) err = d.Decode(&decoded)
require.NoError(t, err, "JWT payload could not be deserialized") require.NoError(t, err, "JWT payload could not be deserialized")
return decoded return decoded

View file

@ -15,7 +15,7 @@ import (
var outboundGRPCConnection = new(grpc.CachedOutboundGRPClientConn) 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 { if v, ok := claims["name"]; ok {
u.Name = fmt.Sprint(v) u.Name = fmt.Sprint(v)
} }

View file

@ -363,7 +363,7 @@ type protoEqualMatcher struct {
expected proto.Message expected proto.Message
} }
func (m protoEqualMatcher) Matches(x interface{}) bool { func (m protoEqualMatcher) Matches(x any) bool {
p, ok := x.(proto.Message) p, ok := x.(proto.Message)
if !ok { if !ok {
return false return false

View file

@ -93,7 +93,7 @@ func newManager(ctx context.Context,
return nil, err return nil, err
} }
mgr.certmagic = certmagic.New(certmagic.NewCache(certmagic.CacheOptions{ 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 return mgr.certmagic, nil
}, },
Logger: logger, Logger: logger,

View file

@ -37,7 +37,7 @@ import (
"github.com/pomerium/pomerium/internal/log" "github.com/pomerium/pomerium/internal/log"
) )
type M = map[string]interface{} type M = map[string]any
type testCA struct { type testCA struct {
key *ecdsa.PrivateKey key *ecdsa.PrivateKey
@ -94,7 +94,7 @@ func newMockACME(ca *testCA, srv *httptest.Server) http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
r.Use(middleware.Logger) 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") w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(M{ _ = json.NewEncoder(w).Encode(M{
"keyChange": srv.URL + "/acme/key-change", "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", "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.Header().Set("Replay-Nonce", "NONCE")
w.WriteHeader(http.StatusOK) 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("Replay-Nonce", "NONCE")
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
@ -188,13 +188,13 @@ func newMockACME(ca *testCA, srv *httptest.Server) http.Handler {
"certificate": srv.URL + "/acme/certificate", "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("Replay-Nonce", "NONCE")
w.Header().Set("Content-Type", "application/pem-certificate-chain") w.Header().Set("Content-Type", "application/pem-certificate-chain")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, _ = w.Write(certBuffer.Bytes()) _, _ = 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.Header().Set("Content-Type", "application/pkix-cert")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, _ = w.Write(ca.cert.Raw) _, _ = w.Write(ca.cert.Raw)
@ -326,7 +326,7 @@ func TestRedirect(t *testing.T) {
} }
client := &http.Client{ client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error { CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse return http.ErrUseLastResponse
}, },
} }
@ -358,7 +358,7 @@ func waitFor(addr string) error {
return err return err
} }
func readJWSPayload(r io.Reader, dst interface{}) { func readJWSPayload(r io.Reader, dst any) {
var req struct { var req struct {
Protected string `json:"protected"` Protected string `json:"protected"`
Payload string `json:"payload"` Payload string `json:"payload"`
@ -388,7 +388,7 @@ func Test_configureCertificateAuthority(t *testing.T) {
wantErr bool wantErr bool
} }
tests := map[string]func(t *testing.T) test{ tests := map[string]func(t *testing.T) test{
"ok/default": func(t *testing.T) test { "ok/default": func(_ *testing.T) test {
return test{ return test{
args: args{ args: args{
acmeMgr: newACMEIssuer(), acmeMgr: newACMEIssuer(),
@ -403,7 +403,7 @@ func Test_configureCertificateAuthority(t *testing.T) {
wantErr: false, wantErr: false,
} }
}, },
"ok/staging": func(t *testing.T) test { "ok/staging": func(_ *testing.T) test {
return test{ return test{
args: args{ args: args{
acmeMgr: newACMEIssuer(), acmeMgr: newACMEIssuer(),
@ -420,7 +420,7 @@ func Test_configureCertificateAuthority(t *testing.T) {
wantErr: false, wantErr: false,
} }
}, },
"ok/custom-ca-staging": func(t *testing.T) test { "ok/custom-ca-staging": func(_ *testing.T) test {
return test{ return test{
args: args{ args: args{
acmeMgr: newACMEIssuer(), acmeMgr: newACMEIssuer(),
@ -464,7 +464,7 @@ func Test_configureExternalAccountBinding(t *testing.T) {
wantErr bool wantErr bool
} }
tests := map[string]func(t *testing.T) test{ tests := map[string]func(t *testing.T) test{
"ok": func(t *testing.T) test { "ok": func(_ *testing.T) test {
return test{ return test{
args: args{ args: args{
acmeMgr: newACMEIssuer(), acmeMgr: newACMEIssuer(),
@ -484,7 +484,7 @@ func Test_configureExternalAccountBinding(t *testing.T) {
wantErr: false, wantErr: false,
} }
}, },
"fail/error-decoding-mac-key": func(t *testing.T) test { "fail/error-decoding-mac-key": func(_ *testing.T) test {
return test{ return test{
args: args{ args: args{
acmeMgr: newACMEIssuer(), acmeMgr: newACMEIssuer(),

View file

@ -69,7 +69,7 @@ func GetCertMagicStorage(ctx context.Context, dst string) (certmagic.Storage, er
prefix = strings.TrimPrefix(match[3][1:], "/") prefix = strings.TrimPrefix(match[3][1:], "/")
options = append(options, options = append(options,
config.WithRegion("us-east-1"), 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{ return aws.Endpoint{
PartitionID: "aws", PartitionID: "aws",
URL: "http://" + host, URL: "http://" + host,

View file

@ -51,11 +51,11 @@ func TestEvents(t *testing.T) {
grpcSrv := grpc.NewServer() grpcSrv := grpc.NewServer()
databrokerpb.RegisterDataBrokerServiceServer(grpcSrv, &mockDataBrokerServer{ 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 putRequest = req
return new(databrokerpb.PutResponse), nil 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 setOptionsRequest = req
return new(databrokerpb.SetOptionsResponse), nil return new(databrokerpb.SetOptionsResponse), nil
}, },

View file

@ -21,7 +21,7 @@ type streamState struct {
unsubscribedResources map[string]struct{} unsubscribedResources map[string]struct{}
} }
var onHandleDeltaRequest = func(state *streamState) {} var onHandleDeltaRequest = func(_ *streamState) {}
// A Manager manages xDS resources. // A Manager manages xDS resources.
type Manager struct { type Manager struct {
@ -51,7 +51,7 @@ func (mgr *Manager) DeltaAggregatedResources(
stateByTypeURL := map[string]*streamState{} 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() mgr.mu.Lock()
defer mgr.mu.Unlock() defer mgr.mu.Unlock()

View file

@ -27,7 +27,7 @@ func TestManager(t *testing.T) {
stateChanged := signal.New() stateChanged := signal.New()
origOnHandleDeltaRequest := onHandleDeltaRequest origOnHandleDeltaRequest := onHandleDeltaRequest
defer func() { onHandleDeltaRequest = origOnHandleDeltaRequest }() defer func() { onHandleDeltaRequest = origOnHandleDeltaRequest }()
onHandleDeltaRequest = func(state *streamState) { onHandleDeltaRequest = func(_ *streamState) {
stateChanged.Broadcast(ctx) stateChanged.Broadcast(ctx)
} }
@ -44,7 +44,7 @@ func TestManager(t *testing.T) {
cc, err := grpc.Dial("test", cc, err := grpc.Dial("test",
grpc.WithInsecure(), 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() return li.Dial()
})) }))
if !assert.NoError(t, err) { if !assert.NoError(t, err) {

View file

@ -18,7 +18,7 @@ func TestEnabler(t *testing.T) {
t.Run("enabled immediately", func(t *testing.T) { t.Run("enabled immediately", func(t *testing.T) {
t.Parallel() 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") return errors.New("ERROR")
}), true) }), true)
err := e.Run(context.Background()) err := e.Run(context.Background())
@ -27,7 +27,7 @@ func TestEnabler(t *testing.T) {
t.Run("enabled delayed", func(t *testing.T) { t.Run("enabled delayed", func(t *testing.T) {
t.Parallel() 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") return errors.New("ERROR")
}), false) }), false)
time.AfterFunc(time.Millisecond*10, e.Enable) time.AfterFunc(time.Millisecond*10, e.Enable)

View file

@ -7,7 +7,7 @@ import (
) )
// DecodeBase64OrJSON decodes a JSON string that can optionally be base64 encoded. // 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) in = strings.TrimSpace(in)
// the data can be base64 encoded // the data can be base64 encoded

View file

@ -10,10 +10,10 @@ type MarshalUnmarshaler interface {
// Marshaler encodes a struct into a set of bytes. // Marshaler encodes a struct into a set of bytes.
type Marshaler interface { type Marshaler interface {
Marshal(interface{}) ([]byte, error) Marshal(any) ([]byte, error)
} }
// Unmarshaler decodes a set of bytes and returns a struct. // Unmarshaler decodes a set of bytes and returns a struct.
type Unmarshaler interface { type Unmarshaler interface {
Unmarshal([]byte, interface{}) error Unmarshal([]byte, any) error
} }

View file

@ -14,7 +14,7 @@ import (
type JSONWebSigner struct { type JSONWebSigner struct {
Signer jose.Signer Signer jose.Signer
key interface{} key any
} }
// NewHS256Signer creates a SHA256 JWT signer from a 32 byte key. // 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. // 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() s, err := jwt.Signed(c.Signer).Claims(x).CompactSerialize()
return []byte(s), err return []byte(s), err
} }
// Unmarshal parses and validates a signed JWT. // 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)) tok, err := jwt.ParseSigned(string(value))
if err != nil { if err != nil {
return err return err

View file

@ -13,8 +13,8 @@ type SignedOutData struct {
} }
// ToJSON converts the data into a JSON map. // ToJSON converts the data into a JSON map.
func (data SignedOutData) ToJSON() map[string]interface{} { func (data SignedOutData) ToJSON() map[string]any {
m := map[string]interface{}{} m := map[string]any{}
httputil.AddBrandingOptionsToMap(m, data.BrandingOptions) httputil.AddBrandingOptionsToMap(m, data.BrandingOptions)
return m return m
} }

View file

@ -14,8 +14,8 @@ type SignOutConfirmData struct {
} }
// ToJSON converts the data into a JSON map. // ToJSON converts the data into a JSON map.
func (data SignOutConfirmData) ToJSON() map[string]interface{} { func (data SignOutConfirmData) ToJSON() map[string]any {
m := map[string]interface{}{ m := map[string]any{
"url": data.URL, "url": data.URL,
} }
httputil.AddBrandingOptionsToMap(m, data.BrandingOptions) httputil.AddBrandingOptionsToMap(m, data.BrandingOptions)

View file

@ -396,7 +396,7 @@ func (h *Handler) handleView(w http.ResponseWriter, r *http.Request, state *Stat
return err return err
} }
m := map[string]interface{}{ m := map[string]any{
"creationOptions": creationOptions, "creationOptions": creationOptions,
"requestOptions": requestOptions, "requestOptions": requestOptions,
"selfUrl": r.URL.String(), "selfUrl": r.URL.String(),

View file

@ -11,7 +11,7 @@ import (
// MustHash returns the xxhash of an arbitrary value or struct. Returns 0 // MustHash returns the xxhash of an arbitrary value or struct. Returns 0
// on error. // on error.
// NOT SUITABLE FOR CRYTOGRAPHIC HASHING. // NOT SUITABLE FOR CRYTOGRAPHIC HASHING.
func MustHash(v interface{}) uint64 { func MustHash(v any) uint64 {
hash, err := Hash(v) hash, err := Hash(v)
if err != nil { if err != nil {
hash = 0 hash = 0
@ -21,7 +21,7 @@ func MustHash(v interface{}) uint64 {
// Hash returns the xxhash of an arbitrary value or struct. // Hash returns the xxhash of an arbitrary value or struct.
// NOT SUITABLE FOR CRYTOGRAPHIC HASHING. // NOT SUITABLE FOR CRYTOGRAPHIC HASHING.
func Hash(v interface{}) (uint64, error) { func Hash(v any) (uint64, error) {
opts := &hashstructure.HashOptions{ opts := &hashstructure.HashOptions{
Hasher: xxhash.New(), Hasher: xxhash.New(),
} }

View file

@ -11,7 +11,7 @@ func TestHash(t *testing.T) {
t.Parallel() t.Parallel()
tests := []struct { tests := []struct {
name string name string
v interface{} v any
want uint64 want uint64
wantErr bool wantErr bool
}{ }{

View file

@ -91,7 +91,7 @@ func getDefaultClient() *httpClient {
} }
// Do provides a simple helper interface to make HTTP requests // 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 var body io.Reader
switch method { switch method {
case http.MethodPost: case http.MethodPost:

View file

@ -18,14 +18,14 @@ func TestCookieChunker(t *testing.T) {
t.Parallel() t.Parallel()
cc := NewCookieChunker(WithCookieChunkerChunkSize(16)) 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{ assert.NoError(t, cc.SetCookie(w, &http.Cookie{
Name: "example", Name: "example",
Value: strings.Repeat("x", 77), Value: strings.Repeat("x", 77),
})) }))
})) }))
defer srv1.Close() 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") cookie, err := cc.LoadCookie(r, "example")
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, &http.Cookie{ assert.Equal(t, &http.Cookie{
@ -57,7 +57,7 @@ func TestCookieChunker(t *testing.T) {
t.Parallel() t.Parallel()
cc := NewCookieChunker(WithCookieChunkerChunkSize(2), WithCookieChunkerMaxChunks(2)) 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{ assert.Error(t, cc.SetCookie(w, &http.Cookie{
Name: "example", Name: "example",
Value: strings.Repeat("x", 1024), Value: strings.Repeat("x", 1024),
@ -71,7 +71,7 @@ func TestCookieChunker(t *testing.T) {
t.Parallel() t.Parallel()
cc1 := NewCookieChunker(WithCookieChunkerChunkSize(64)) 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{ assert.NoError(t, cc1.SetCookie(w, &http.Cookie{
Name: "example", Name: "example",
Value: strings.Repeat("x", 1024), Value: strings.Repeat("x", 1024),
@ -80,7 +80,7 @@ func TestCookieChunker(t *testing.T) {
defer srv1.Close() defer srv1.Close()
cc2 := NewCookieChunker(WithCookieChunkerChunkSize(64), WithCookieChunkerMaxChunks(2)) 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") cookie, err := cc2.LoadCookie(r, "example")
assert.Error(t, err) assert.Error(t, err)
assert.Nil(t, cookie) assert.Nil(t, cookie)

View file

@ -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 // It does not otherwise end the request; the caller should ensure no further
// writes are done to w. // writes are done to w.
// The error message should be application/json. // 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("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Content-Type-Options", "nosniff")
b := new(bytes.Buffer) b := new(bytes.Buffer)

View file

@ -46,8 +46,8 @@ func TestHandlerFunc_ServeHTTP(t *testing.T) {
f HandlerFunc f HandlerFunc
wantBody string wantBody string
}{ }{
{"good http error", func(w http.ResponseWriter, r *http.Request) error { return NewError(404, errors.New("404")) }, "{\"Status\":404}\n"}, {"good http error", func(_ http.ResponseWriter, _ *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 std error", func(_ http.ResponseWriter, _ *http.Request) error { return errors.New("404") }, "{\"Status\":500}\n"},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
@ -66,7 +66,7 @@ func TestRenderJSON(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
code int code int
v interface{} v any
wantBody string wantBody string
wantCode int wantCode int
}{ }{
@ -88,7 +88,7 @@ func TestRenderJSON(t *testing.T) {
{ {
"map", "map",
http.StatusOK, http.StatusOK,
map[string]interface{}{ map[string]any{
"C": 1, // notice order does not matter "C": 1, // notice order does not matter
"A": "A", "A": "A",
"B": "B", "B": "B",
@ -99,7 +99,7 @@ func TestRenderJSON(t *testing.T) {
{ {
"bad!", "bad!",
http.StatusOK, http.StatusOK,
map[string]interface{}{ map[string]any{
"BAD BOI": math.Inf(1), "BAD BOI": math.Inf(1),
}, },
`{"error":"json: unsupported value: +Inf"}`, http.StatusInternalServerError, `{"error":"json: unsupported value: +Inf"}`, http.StatusInternalServerError,

View file

@ -16,7 +16,7 @@ import (
) )
func TestMiddleware(t *testing.T) { 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") io.WriteString(w, "NEXT")
}) })
@ -38,7 +38,7 @@ func TestMiddleware(t *testing.T) {
t.Run("proxy", func(t *testing.T) { t.Run("proxy", func(t *testing.T) {
h := New() 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") io.WriteString(w, "SERVER1")
})) }))
defer srv1.Close() defer srv1.Close()

View file

@ -35,7 +35,7 @@ func TestNewServer(t *testing.T) {
Addr: ":0", Addr: ":0",
Insecure: true, Insecure: true,
}, },
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "Hello, http") fmt.Fprintln(w, "Hello, http")
}), }),
false, false,
@ -45,7 +45,7 @@ func TestNewServer(t *testing.T) {
&ServerOptions{ &ServerOptions{
Addr: ":0", Addr: ":0",
}, },
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "Hello, http") fmt.Fprintln(w, "Hello, http")
}), }),
true, true,
@ -55,7 +55,7 @@ func TestNewServer(t *testing.T) {
&ServerOptions{ &ServerOptions{
Insecure: true, Insecure: true,
}, },
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "Hello, http") fmt.Fprintln(w, "Hello, http")
}), }),
false, false,
@ -63,7 +63,7 @@ func TestNewServer(t *testing.T) {
{ {
"empty handler", "empty handler",
nil, nil,
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "Hello, http") fmt.Fprintln(w, "Hello, http")
}), }),
true, true,
@ -73,7 +73,7 @@ func TestNewServer(t *testing.T) {
&ServerOptions{ &ServerOptions{
Addr: ":65536", Addr: ":65536",
Insecure: true, Insecure: true,
}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { }, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "Hello, http") fmt.Fprintln(w, "Hello, http")
}), }),
true, true,
@ -83,7 +83,7 @@ func TestNewServer(t *testing.T) {
&ServerOptions{ &ServerOptions{
TLSConfig: &tls.Config{}, 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") fmt.Fprintln(w, "Hello, http")
}), }),
false, false,

View file

@ -23,13 +23,13 @@ func (claims *SessionClaims) SetRawIDToken(rawIDToken string) {
} }
// Claims are JWT claims. // 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. // NewClaimsFromRaw creates a new Claims map from a map of raw messages.
func NewClaimsFromRaw(raw map[string]json.RawMessage) Claims { func NewClaimsFromRaw(raw map[string]json.RawMessage) Claims {
claims := make(Claims) claims := make(Claims)
for k, rawv := range raw { for k, rawv := range raw {
var v interface{} var v any
if err := json.Unmarshal(rawv, &v); err == nil { if err := json.Unmarshal(rawv, &v); err == nil {
claims[k] = v claims[k] = v
} }
@ -43,7 +43,7 @@ func (claims *Claims) UnmarshalJSON(data []byte) error {
*claims = make(Claims) *claims = make(Claims)
} }
var m map[string]interface{} var m map[string]any
err := json.Unmarshal(data, &m) err := json.Unmarshal(data, &m)
if err != nil { if err != nil {
return err return err
@ -55,7 +55,7 @@ func (claims *Claims) UnmarshalJSON(data []byte) error {
} }
// Claims takes the claims data and fills v. // 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) bs, err := json.Marshal(claims)
if err != nil { if err != nil {
return err return err
@ -81,13 +81,13 @@ func (claims Claims) Flatten() FlattenedClaims {
flattened[k+"."+sk] = sv flattened[k+"."+sk] = sv
} }
case reflect.Slice: case reflect.Slice:
slc := make([]interface{}, rv.Len()) slc := make([]any, rv.Len())
for i := 0; i < rv.Len(); i++ { for i := 0; i < rv.Len(); i++ {
slc[i] = rv.Index(i).Interface() slc[i] = rv.Index(i).Interface()
} }
flattened[k] = slc flattened[k] = slc
default: default:
flattened[k] = []interface{}{v} flattened[k] = []any{v}
} }
} }
return flattened 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. // 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. // NewFlattenedClaimsFromPB creates a new FlattenedClaims from the protobuf struct type.
func NewFlattenedClaimsFromPB(m map[string]*structpb.ListValue) FlattenedClaims { func NewFlattenedClaimsFromPB(m map[string]*structpb.ListValue) FlattenedClaims {

View file

@ -32,7 +32,7 @@ import (
type Authenticator interface { type Authenticator interface {
Refresh(context.Context, *oauth2.Token, identity.State) (*oauth2.Token, error) Refresh(context.Context, *oauth2.Token, identity.State) (*oauth2.Token, error)
Revoke(context.Context, *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. // A Manager refreshes identity information using session and user data.

View file

@ -24,7 +24,7 @@ func TestRefreshSessionScheduler(t *testing.T) {
time.Now, time.Now,
sessionRefreshGracePeriod, sessionRefreshGracePeriod,
sessionRefreshCoolOffDuration, sessionRefreshCoolOffDuration,
func(ctx context.Context, sesionID string) { func(_ context.Context, _ string) {
calls.Append(time.Now()) calls.Append(time.Now())
}, },
"S1", "S1",
@ -51,7 +51,7 @@ func TestUpdateUserInfoScheduler(t *testing.T) {
ctx := context.Background() ctx := context.Background()
userUpdateInfoInterval := 100 * time.Millisecond 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()) calls.Append(time.Now())
}, "U1") }, "U1")
t.Cleanup(uuis.Stop) t.Cleanup(uuis.Stop)

View file

@ -37,7 +37,7 @@ func (mp MockProvider) Revoke(_ context.Context, _ *oauth2.Token) error {
} }
// UpdateUserInfo is a mocked providers function. // 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 return mp.UpdateUserInfoError
} }

View file

@ -143,7 +143,7 @@ func (p *Provider) Revoke(ctx context.Context, t *oauth2.Token) error {
} }
// UpdateUserInfo gets claims from the oauth token. // 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) rawIDToken, ok := t.Extra("id_token").(string)
if !ok { if !ok {
return nil return nil

View file

@ -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) // 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 // 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) err := p.userInfo(ctx, t, v)
if err != nil { if err != nil {
return fmt.Errorf("github: could not retrieve user info %w", err) 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/users/emails/#list-email-addresses-for-a-user
// https://developer.github.com/v3/auth/ // 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 // response represents the github user email
// https://developer.github.com/v3/users/emails/#response // https://developer.github.com/v3/users/emails/#response
var response []struct { var response []struct {
@ -167,7 +167,7 @@ func (p *Provider) userEmail(ctx context.Context, t *oauth2.Token, v interface{}
return json.Unmarshal(b, v) 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 { var response struct {
ID int `json:"id"` ID int `json:"id"`
Login string `json:"login"` Login string `json:"login"`

View file

@ -115,7 +115,7 @@ func (transport *wellKnownConfiguration) RoundTrip(req *http.Request) (*http.Res
return nil, err return nil, err
} }
var wk map[string]interface{} var wk map[string]any
if err := json.Unmarshal(bs, &wk); err == nil { if err := json.Unmarshal(bs, &wk); err == nil {
if issuerVar, ok := wk["issuer"]; ok { if issuerVar, ok := wk["issuer"]; ok {
if fmt.Sprint(issuerVar) == nonSpecIssuerURL { if fmt.Sprint(issuerVar) == nonSpecIssuerURL {

View file

@ -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. // groups endpoint (non-spec) to populate the rest of the user's information.
// //
// https://openid.net/specs/openid-connect-core-1_0.html#UserInfo // 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() pp, err := p.GetProvider()
if err != nil { if err != nil {
return err 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 // 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) b, err := json.Marshal(v)
if err != nil { if err != nil {
return "", err return "", err

View file

@ -18,7 +18,7 @@ func TestRefresh(t *testing.T) {
ctx, clearTimeout := context.WithTimeout(context.Background(), 10*time.Second) ctx, clearTimeout := context.WithTimeout(context.Background(), 10*time.Second)
t.Cleanup(clearTimeout) 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.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{ w.Write([]byte(`{
"access_token": "NEW_TOKEN", "access_token": "NEW_TOKEN",
@ -52,7 +52,7 @@ func TestRefresh_errors(t *testing.T) {
ctx, clearTimeout := context.WithTimeout(context.Background(), 10*time.Second) ctx, clearTimeout := context.WithTimeout(context.Background(), 10*time.Second)
t.Cleanup(clearTimeout) 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("{}")) w.Write([]byte("{}"))
})) }))
t.Cleanup(s.Close) t.Cleanup(s.Close)

View file

@ -52,7 +52,7 @@ func (transport *userInfoRoundTripper) RoundTrip(req *http.Request) (*http.Respo
return nil, err return nil, err
} }
var userInfo map[string]interface{} var userInfo map[string]any
if err := json.Unmarshal(bs, &userInfo); err == nil { if err := json.Unmarshal(bs, &userInfo); err == nil {
// AWS Cognito returns email_verified as a string, so we'll make it a bool // AWS Cognito returns email_verified as a string, so we'll make it a bool
if ev, ok := userInfo["email_verified"]; ok { if ev, ok := userInfo["email_verified"]; ok {

View file

@ -30,7 +30,7 @@ type Authenticator interface {
Refresh(context.Context, *oauth2.Token, identity.State) (*oauth2.Token, error) Refresh(context.Context, *oauth2.Token, identity.State) (*oauth2.Token, error)
Revoke(context.Context, *oauth2.Token) error Revoke(context.Context, *oauth2.Token) error
Name() string 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 SignIn(w http.ResponseWriter, r *http.Request, state string) error
SignOut(w http.ResponseWriter, r *http.Request, idTokenHint, authenticateSignedOutURL, redirectToURL string) error SignOut(w http.ResponseWriter, r *http.Request, idTokenHint, authenticateSignedOutURL, redirectToURL string) error

View file

@ -13,69 +13,69 @@ func init() {
type grpcLogger struct{} type grpcLogger struct{}
func (c *grpcLogger) Info(args ...interface{}) { func (c *grpcLogger) Info(args ...any) {
if GetLevel() <= zerolog.DebugLevel { if GetLevel() <= zerolog.DebugLevel {
Logger().Info().Msg(fmt.Sprint(args...)) Logger().Info().Msg(fmt.Sprint(args...))
} }
} }
func (c *grpcLogger) Infoln(args ...interface{}) { func (c *grpcLogger) Infoln(args ...any) {
if GetLevel() <= zerolog.DebugLevel { if GetLevel() <= zerolog.DebugLevel {
Logger().Info().Msg(fmt.Sprintln(args...)) 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 { if GetLevel() <= zerolog.DebugLevel {
Logger().Info().Msg(fmt.Sprintf(format, args...)) Logger().Info().Msg(fmt.Sprintf(format, args...))
} }
} }
func (c *grpcLogger) Warning(args ...interface{}) { func (c *grpcLogger) Warning(args ...any) {
if GetLevel() <= zerolog.DebugLevel { if GetLevel() <= zerolog.DebugLevel {
Logger().Warn().Msg(fmt.Sprint(args...)) Logger().Warn().Msg(fmt.Sprint(args...))
} }
} }
func (c *grpcLogger) Warningln(args ...interface{}) { func (c *grpcLogger) Warningln(args ...any) {
if GetLevel() <= zerolog.DebugLevel { if GetLevel() <= zerolog.DebugLevel {
Logger().Warn().Msg(fmt.Sprintln(args...)) 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 { if GetLevel() <= zerolog.DebugLevel {
Logger().Warn().Msg(fmt.Sprintf(format, args...)) Logger().Warn().Msg(fmt.Sprintf(format, args...))
} }
} }
func (c *grpcLogger) Error(args ...interface{}) { func (c *grpcLogger) Error(args ...any) {
if GetLevel() <= zerolog.DebugLevel { if GetLevel() <= zerolog.DebugLevel {
Logger().Error().Msg(fmt.Sprint(args...)) Logger().Error().Msg(fmt.Sprint(args...))
} }
} }
func (c *grpcLogger) Errorln(args ...interface{}) { func (c *grpcLogger) Errorln(args ...any) {
if GetLevel() <= zerolog.DebugLevel { if GetLevel() <= zerolog.DebugLevel {
Logger().Error().Msg(fmt.Sprintln(args...)) 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 { if GetLevel() <= zerolog.DebugLevel {
Logger().Error().Msg(fmt.Sprintf(format, args...)) 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...)) Logger().Fatal().Msg(fmt.Sprint(args...))
} }
func (c *grpcLogger) Fatalln(args ...interface{}) { func (c *grpcLogger) Fatalln(args ...any) {
Logger().Fatal().Msg(fmt.Sprintln(args...)) 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...)) Logger().Fatal().Msg(fmt.Sprintf(format, args...))
} }

View file

@ -162,13 +162,13 @@ func Log(_ context.Context) *zerolog.Event {
// Print sends a log event using debug level and no extra field. // Print sends a log event using debug level and no extra field.
// Arguments are handled in the manner of fmt.Print. // Arguments are handled in the manner of fmt.Print.
func Print(v ...interface{}) { func Print(v ...any) {
Logger().Print(v...) Logger().Print(v...)
} }
// Printf sends a log event using debug level and no extra field. // Printf sends a log event using debug level and no extra field.
// Arguments are handled in the manner of fmt.Printf. // 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...) Logger().Printf(format, v...)
} }

View file

@ -24,7 +24,7 @@ func TestNewHandler(t *testing.T) {
Str("foo", "bar"). Str("foo", "bar").
Logger() Logger()
lh := NewHandler(func() *zerolog.Logger { return &log }) 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 := FromRequest(r)
if !reflect.DeepEqual(*l, log) { if !reflect.DeepEqual(*l, log) {
t.Fail() t.Fail()
@ -38,7 +38,7 @@ func TestRemoteAddrHandler(t *testing.T) {
r := &http.Request{ r := &http.Request{
RemoteAddr: "1.2.3.4:1234", 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 := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
@ -55,7 +55,7 @@ func TestRemoteAddrHandlerIPv6(t *testing.T) {
r := &http.Request{ r := &http.Request{
RemoteAddr: "[2001:db8:a0b:12f0::1]:1234", 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 := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
@ -74,7 +74,7 @@ func TestUserAgentHandler(t *testing.T) {
"User-Agent": []string{"some user agent string"}, "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 := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
@ -93,7 +93,7 @@ func TestRefererHandler(t *testing.T) {
"Referer": []string{"http://foo.com/bar"}, "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 := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
@ -112,7 +112,7 @@ func TestRequestIDHandler(t *testing.T) {
"X-Request-Id": []string{"1234"}, "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()) requestID := requestid.FromContext(r.Context())
l := FromRequest(r) l := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
@ -131,7 +131,7 @@ func BenchmarkDataRace(b *testing.B) {
Str("foo", "bar"). Str("foo", "bar").
Logger() Logger()
lh := NewHandler(func() *zerolog.Logger { return &log }) 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 := FromRequest(r)
l.UpdateContext(func(c zerolog.Context) zerolog.Context { l.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str("bar", "baz") return c.Str("bar", "baz")
@ -153,7 +153,7 @@ func TestLogHeadersHandler(t *testing.T) {
r.Header.Set("X-Forwarded-For", "proxy1,proxy2,proxy3") 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 := FromRequest(r)
l.Log().Msg("") l.Log().Msg("")
})) }))
@ -170,7 +170,7 @@ func TestAccessHandler(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil) 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 := FromRequest(r)
l.Log().Int("status", status).Int("size", size).Msg("info") l.Log().Int("status", status).Int("size", size).Msg("info")
})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { })(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

View file

@ -26,7 +26,7 @@ func TestSetHeaders(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { 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 { for k, want := range tt.securityHeaders {
if got := w.Header().Get(k); want != got { if got := w.Header().Get(k); want != got {
t.Errorf("want %s got %q", want, got) t.Errorf("want %s got %q", want, got)
@ -42,7 +42,7 @@ func TestSetHeaders(t *testing.T) {
func TestValidateSignature(t *testing.T) { func TestValidateSignature(t *testing.T) {
t.Parallel() 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)) fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
}) })
@ -81,7 +81,7 @@ func TestValidateSignature(t *testing.T) {
func TestRequireBasicAuth(t *testing.T) { func TestRequireBasicAuth(t *testing.T) {
t.Parallel() 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)) fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
}) })

View file

@ -136,7 +136,7 @@ func (cs *Store) LoadSession(r *http.Request) (string, error) {
} }
// SaveSession saves a session state to a request's cookie store. // 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 var value string
switch v := x.(type) { switch v := x.(type) {
case []byte: case []byte:

View file

@ -104,7 +104,7 @@ func TestStore_SaveSession(t *testing.T) {
} }
tests := []struct { tests := []struct {
name string name string
State interface{} State any
encoder encoding.Marshaler encoder encoding.Marshaler
decoder encoding.Unmarshaler decoder encoding.Unmarshaler
wantErr bool wantErr bool

View file

@ -27,7 +27,7 @@ func testAuthorizer(next http.Handler) http.Handler {
} }
func TestVerifier(t *testing.T) { 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") w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, http.StatusText(http.StatusOK)) fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)

View file

@ -27,7 +27,7 @@ func testAuthorizer(next http.Handler) http.Handler {
} }
func TestVerifier(t *testing.T) { 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") w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, http.StatusText(http.StatusOK)) fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)

View file

@ -46,7 +46,7 @@ func FromContext(ctx context.Context) (string, error) {
} }
// contextKey is a value for use with context.WithValue. It's used as // 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. // for defining context keys was copied from Go 1.7's new use of context in net/http.
type contextKey struct { type contextKey struct {
name string name string

View file

@ -62,7 +62,7 @@ func testAuthorizer(next http.Handler) http.Handler {
} }
func TestVerifier(t *testing.T) { 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") w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, http.StatusText(http.StatusOK)) fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)

View file

@ -38,6 +38,6 @@ func (ms Store) LoadSession(*http.Request) (string, error) {
} }
// SaveSession returns a save 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 return ms.SaveError
} }

View file

@ -27,7 +27,7 @@ func testAuthorizer(next http.Handler) http.Handler {
} }
func TestVerifier(t *testing.T) { 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") w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, http.StatusText(http.StatusOK)) fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)

View file

@ -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` // 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) data, err := qp.encoder.Marshal(x)
if err != nil { if err != nil {
return err return err

View file

@ -11,7 +11,7 @@ import (
type SessionStore interface { type SessionStore interface {
SessionLoader SessionLoader
ClearSession(http.ResponseWriter, *http.Request) 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. // SessionLoader defines an interface for loading a session.

View file

@ -120,8 +120,8 @@ func GRPCClientInterceptor(service string) grpc.UnaryClientInterceptor {
return func( return func(
ctx context.Context, ctx context.Context,
method string, method string,
req interface{}, req any,
reply interface{}, reply any,
cc *grpc.ClientConn, cc *grpc.ClientConn,
invoker grpc.UnaryInvoker, invoker grpc.UnaryInvoker,
opts ...grpc.CallOption, opts ...grpc.CallOption,

View file

@ -7,7 +7,7 @@ import (
"go.opencensus.io/metric/metricdata" "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() t.Helper()
switch value.(type) { switch value.(type) {

View file

@ -44,7 +44,7 @@ func testDataRetrieval(v *view.View, t *testing.T, want string) {
func newTestMux() http.Handler { func newTestMux() http.Handler {
mux := http.NewServeMux() 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") fmt.Fprintf(w, "Hello")
}) })
@ -123,7 +123,7 @@ func newTestTransport() http.RoundTripper {
} }
func newFailingTestTransport() 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") return nil, errors.New("failure")
}) })
} }

View file

@ -11,7 +11,7 @@ import (
) )
func newEnvoyMetricsHandler() http.HandlerFunc { func newEnvoyMetricsHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte(` w.Write([]byte(`
# TYPE envoy_server_initialization_time_ms histogram # TYPE envoy_server_initialization_time_ms histogram
envoy_server_initialization_time_ms_bucket{le="0.5"} 0 envoy_server_initialization_time_ms_bucket{le="0.5"} 0

View file

@ -21,7 +21,7 @@ import (
const maxWait = time.Minute * 20 const maxWait = time.Minute * 20
// AssertProtoEqual asserts that two protobuf messages equal. Slices of messages are also supported. // 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() t.Helper()
return assert.True(t, cmp.Equal(expected, actual, protocmp.Transform()), return assert.True(t, cmp.Equal(expected, actual, protocmp.Transform()),
append(msgAndArgs, cmp.Diff(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 // AssertProtoJSONEqual asserts that a protobuf message matches the given JSON. The protoMsg can also be a slice
// of protobuf messages. // 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() t.Helper()
formattedJSON := formattedProtoJSON(protoMsg) formattedJSON := formattedProtoJSON(protoMsg)
return assert.Equal(t, reformatJSON(json.RawMessage(expected)), formattedJSON, msgAndArgs...) return assert.Equal(t, reformatJSON(json.RawMessage(expected)), formattedJSON, msgAndArgs...)
} }
func formattedProtoJSON(protoMsg interface{}) string { func formattedProtoJSON(protoMsg any) string {
protoMsgVal := reflect.ValueOf(protoMsg) protoMsgVal := reflect.ValueOf(protoMsg)
if protoMsgVal.Kind() == reflect.Slice { if protoMsgVal.Kind() == reflect.Slice {
var protoMsgs []json.RawMessage var protoMsgs []json.RawMessage
@ -49,13 +49,13 @@ func formattedProtoJSON(protoMsg interface{}) string {
} }
func reformatJSON(raw json.RawMessage) string { func reformatJSON(raw json.RawMessage) string {
var obj interface{} var obj any
_ = json.Unmarshal(raw, &obj) _ = json.Unmarshal(raw, &obj)
bs, _ := json.MarshalIndent(obj, "", " ") bs, _ := json.MarshalIndent(obj, "", " ")
return string(bs) return string(bs)
} }
func toProtoJSON(protoMsg interface{}) json.RawMessage { func toProtoJSON(protoMsg any) json.RawMessage {
bs, _ := protojson.Marshal(protoMsg.(protoreflect.ProtoMessage)) bs, _ := protojson.Marshal(protoMsg.(protoreflect.ProtoMessage))
return bs 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 // To update a reference JSON file, pass the test argument '-update'. This will
// overwrite the reference output to match the current behavior. // overwrite the reference output to match the current behavior.
func AssertProtoJSONFileEqual( func AssertProtoJSONFileEqual(
t *testing.T, file string, protoMsg interface{}, msgAndArgs ...interface{}, t *testing.T, file string, protoMsg any, msgAndArgs ...any,
) bool { ) bool {
t.Helper() t.Helper()

View file

@ -92,7 +92,7 @@ func (su *SignedURL) Validate() error {
// hmacURL takes a redirect url string and timestamp and returns the base64 // hmacURL takes a redirect url string and timestamp and returns the base64
// encoded HMAC result. // 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) h := cryptutil.GenerateHMAC([]byte(fmt.Sprint(data...)), key)
return base64.URLEncoding.EncodeToString(h) return base64.URLEncoding.EncodeToString(h)
} }

View file

@ -45,7 +45,7 @@ func newConfig(opts ...WatchOption) *config {
for _, opt := range []WatchOption{ for _, opt := range []WatchOption{
WithOnConnected(func(_ context.Context) {}), WithOnConnected(func(_ context.Context) {}),
WithOnDisconnected(func(_ context.Context) {}), WithOnDisconnected(func(_ context.Context) {}),
WithOnBundleUpdated(func(_ context.Context, key string) {}), WithOnBundleUpdated(func(_ context.Context, _ string) {}),
WithOnBootstrapConfigUpdated(func(_ context.Context) {}), WithOnBootstrapConfigUpdated(func(_ context.Context) {}),
} { } {
opt(cfg) opt(cfg)

View file

@ -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) logger := log.Ctx(ctx).With().Str("service", "connect-mux").Logger().Level(zerolog.InfoLevel)
return c.api.Watch(ctx, return c.api.Watch(ctx,
connect_mux.WithOnConnected(func(ctx context.Context) { connect_mux.WithOnConnected(func(_ context.Context) {
logger.Debug().Msg("connected") logger.Debug().Msg("connected")
}), }),
connect_mux.WithOnDisconnected(func(ctx context.Context) { connect_mux.WithOnDisconnected(func(_ context.Context) {
logger.Debug().Msg("disconnected") logger.Debug().Msg("disconnected")
}), }),
connect_mux.WithOnBootstrapConfigUpdated(func(ctx context.Context) { connect_mux.WithOnBootstrapConfigUpdated(func(_ context.Context) {
logger.Debug().Msg("bootstrap config updated") 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") logger.Debug().Str("key", key).Msg("bundle updated")
}), }),
) )

View file

@ -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) 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) item := x.(bundle)
*h = append(*h, item) *h = append(*h, item)
} }
func (h *bundleHeap) Pop() interface{} { func (h *bundleHeap) Pop() any {
old := *h old := *h
n := len(old) n := len(old)
x := old[n-1] x := old[n-1]

View file

@ -49,7 +49,7 @@ func Run(ctx context.Context, opts ...Option) error {
func (c *service) watchUpdates(ctx context.Context) error { func (c *service) watchUpdates(ctx context.Context) error {
return c.config.api.Watch(ctx, return c.config.api.Watch(ctx,
connect_mux.WithOnConnected(func(ctx context.Context) { connect_mux.WithOnConnected(func(_ context.Context) {
c.triggerFullUpdate(true) c.triggerFullUpdate(true)
}), }),
connect_mux.WithOnDisconnected(func(_ context.Context) { connect_mux.WithOnDisconnected(func(_ context.Context) {

View file

@ -217,10 +217,10 @@ func (c *service) syncBundleToDatabroker(ctx context.Context, key string, src io
err = databroker.NewReconciler( err = databroker.NewReconciler(
fmt.Sprintf("bundle-%s", key), fmt.Sprintf("bundle-%s", key),
c.config.databrokerClient, c.config.databrokerClient,
func(ctx context.Context) (databroker.RecordSetBundle, error) { func(_ context.Context) (databroker.RecordSetBundle, error) {
return databrokerRecords, nil return databrokerRecords, nil
}, },
func(ctx context.Context) (databroker.RecordSetBundle, error) { func(_ context.Context) (databroker.RecordSetBundle, error) {
return bundleRecords, nil return bundleRecords, nil
}, },
func(_ []*databroker.Record) {}, func(_ []*databroker.Record) {},

View file

@ -19,7 +19,7 @@ func TestCache(t *testing.T) {
var testToken *token.Token var testToken *token.Token
var testError error var testError error
fetcher := func(ctx context.Context, refreshToken string) (*token.Token, error) { fetcher := func(_ context.Context, _ string) (*token.Token, error) {
if testToken != nil { if testToken != nil {
token := *testToken token := *testToken
return &token, nil return &token, nil
@ -54,7 +54,7 @@ func TestCache(t *testing.T) {
t.Run("token cannot fit minTTL", func(t *testing.T) { t.Run("token cannot fit minTTL", func(t *testing.T) {
t.Parallel() 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 return &token.Token{"ok-bearer", time.Now().Add(time.Minute)}, nil
} }

View file

@ -32,7 +32,7 @@ import (
// Run runs the main pomerium application. // Run runs the main pomerium application.
func Run(ctx context.Context, src config.Source) error { 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). log.Info(ctx).
Str("envoy_version", files.FullVersion()). Str("envoy_version", files.FullVersion()).

View file

@ -55,7 +55,7 @@ func (mc *mergedCtx) Err() error {
return mc.doneCtx.Err() 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 { if value := mc.ctx1.Value(key); value != nil {
return value return value
} }

View file

@ -88,7 +88,7 @@ func TestHashProto(t *testing.T) {
// deterministic. // deterministic.
var cur []byte var cur []byte
for i := 0; i < 1000; i++ { 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", "1": "a", "2": "b", "3": "c", "4": "d",
"5": "e", "6": "f", "7": "g", "8": "h", "5": "e", "6": "f", "7": "g", "8": "h",
}) })

View file

@ -75,7 +75,7 @@ func loadKeys(data []byte, unmarshal func([]byte) (any, error)) ([]*jose.JSONWeb
return jwks, nil return jwks, nil
} }
func loadPrivateKey(b []byte) (interface{}, error) { func loadPrivateKey(b []byte) (any, error) {
var wrappedErr error var wrappedErr error
var err error var err error
var key any 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 // 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 wrappedErr error
var err error var err error
var key any var key any
@ -130,7 +130,7 @@ func loadPublicKey(b []byte) (interface{}, error) {
} }
// SignatureAlgorithmForKey returns the signature algorithm for the given key. // 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) { switch key.(type) {
case *ecdsa.PrivateKey, *ecdsa.PublicKey: case *ecdsa.PrivateKey, *ecdsa.PublicKey:
return jose.ES256, nil return jose.ES256, nil

View file

@ -30,7 +30,7 @@ type (
) )
// MarshalPKCS8PrivateKey wraps x509.MarshalPKCS8PrivateKey with added support for KeyEncryptionKeys. // 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 // also support a pointer to a private key encryption key
if kek, ok := key.(*PrivateKeyEncryptionKey); ok { if kek, ok := key.(*PrivateKeyEncryptionKey); ok {
key = *kek key = *kek
@ -53,7 +53,7 @@ func MarshalPKCS8PrivateKey(key interface{}) ([]byte, error) {
} }
// MarshalPKIXPublicKey wraps x509.MarshalPKIXPublicKey with added support for KeyEncryptionKeys. // 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 { if kek, ok := pub.(*PublicKeyEncryptionKey); ok {
pub = *kek pub = *kek
} }
@ -76,7 +76,7 @@ func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
} }
// ParsePKCS8PrivateKey wraps x509.ParsePKCS8PrivateKey with added support for KeyEncryptionKeys. // ParsePKCS8PrivateKey wraps x509.ParsePKCS8PrivateKey with added support for KeyEncryptionKeys.
func ParsePKCS8PrivateKey(der []byte) (interface{}, error) { func ParsePKCS8PrivateKey(der []byte) (any, error) {
var privKey pkcs8 var privKey pkcs8
_, err := asn1.Unmarshal(der, &privKey) _, err := asn1.Unmarshal(der, &privKey)
if err != nil { if err != nil {
@ -96,7 +96,7 @@ func ParsePKCS8PrivateKey(der []byte) (interface{}, error) {
} }
// ParsePKIXPublicKey wraps x509.ParsePKIXPublicKey with added support for KeyEncryptionKeys. // 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 var pki publicKeyInfo
rest, err := asn1.Unmarshal(derBytes, &pki) rest, err := asn1.Unmarshal(derBytes, &pki)
if err != nil || len(rest) > 0 { if err != nil || len(rest) > 0 {

View file

@ -25,7 +25,7 @@ func TestFanOutStopped(t *testing.T) {
return errors.Is(f.Publish(context.Background(), 1), fanout.ErrStopped) return errors.Is(f.Publish(context.Background(), 1), fanout.ErrStopped)
}, 5*time.Second, 10*time.Millisecond) }, 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 return nil
}) })
assert.ErrorIs(t, err, fanout.ErrStopped) assert.ErrorIs(t, err, fanout.ErrStopped)
@ -47,7 +47,7 @@ func TestFanOutEvictSlowSubscriber(t *testing.T) {
eg, ctx := errgroup.WithContext(ctx) eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error { 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 { select {
case <-ctx.Done(): case <-ctx.Done():
// context was canceled as expected // context was canceled as expected
@ -91,7 +91,7 @@ func TestFanOutReceiverCancelOnError(t *testing.T) {
ready := make(chan struct{}) ready := make(chan struct{})
go func() { go func() {
errch <- f.Receive(ctx, func(ctx context.Context, msg int) error { errch <- f.Receive(ctx, func(_ context.Context, _ int) error {
return receiverErr return receiverErr
}, fanout.WithOnSubscriberAdded[int](func() { close(ready) })) }, fanout.WithOnSubscriberAdded[int](func() { close(ready) }))
}() }()
@ -111,7 +111,7 @@ func TestFanOutFilter(t *testing.T) {
ready := make(chan struct{}) ready := make(chan struct{})
results := make(chan int) results := make(chan int)
go func() { go func() {
_ = f.Receive(ctx, func(ctx context.Context, msg int) error { _ = f.Receive(ctx, func(_ context.Context, msg int) error {
results <- msg results <- msg
return nil return nil
}, },
@ -146,7 +146,7 @@ func BenchmarkFanout(b *testing.B) {
want := i want := i
eg.Go(func() error { eg.Go(func() error {
seen := 0 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 { if seen++; seen == cycles {
return errStopReceiver return errStopReceiver
} }

View file

@ -61,7 +61,7 @@ func NewGRPCClientConn(ctx context.Context, opts *Options, other ...grpc.DialOpt
// grpcTimeoutInterceptor enforces per-RPC request timeouts // grpcTimeoutInterceptor enforces per-RPC request timeouts
func grpcTimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor { 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 { if timeout <= 0 {
return invoker(ctx, method, req, reply, cc, opts...) return invoker(ctx, method, req, reply, cc, opts...)
} }

View file

@ -10,7 +10,7 @@ import (
func Test_grpcTimeoutInterceptor(t *testing.T) { func Test_grpcTimeoutInterceptor(t *testing.T) {
mockInvoker := func(sleepTime time.Duration, wantFail bool) grpc.UnaryInvoker { 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) time.Sleep(sleepTime)
deadline, ok := ctx.Deadline() deadline, ok := ctx.Deadline()
if !ok { if !ok {

View file

@ -69,7 +69,7 @@ func TestInitialSync(t *testing.T) {
r2 := new(Record) r2 := new(Record)
m := &mockServer{ m := &mockServer{
syncLatest: func(req *SyncLatestRequest, stream DataBrokerService_SyncLatestServer) error { syncLatest: func(_ *SyncLatestRequest, stream DataBrokerService_SyncLatestServer) error {
stream.Send(&SyncLatestResponse{ stream.Send(&SyncLatestResponse{
Response: &SyncLatestResponse_Record{ Response: &SyncLatestResponse_Record{
Record: r1, Record: r1,

Some files were not shown because too many files have changed in this diff Show more