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
with:
version: v1.55
version: v1.57
args: --timeout=10m

View file

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

View file

@ -87,7 +87,7 @@ build-ui: yarn
.PHONY: lint
lint: ## Verifies `golint` passes.
@echo "==> $@"
@go run github.com/golangci/golangci-lint/cmd/golangci-lint@v1.55.2 run ./... --fix
@go run github.com/golangci/golangci-lint/cmd/golangci-lint@v1.57.2 run ./... --fix
.PHONY: test
test: get-envoy ## Runs the go tests.

View file

@ -225,7 +225,7 @@ func TestAuthenticate_SignOut(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
a := &Authenticate{
cfg: getAuthenticateConfig(WithGetIdentityProvider(func(options *config.Options, idpID string) (identity.Authenticator, error) {
cfg: getAuthenticateConfig(WithGetIdentityProvider(func(_ *config.Options, _ string) (identity.Authenticator, error) {
return tt.provider, nil
})),
state: atomicutil.NewValue(&authenticateState{
@ -280,7 +280,7 @@ func TestAuthenticate_SignOutDoesNotRequireSession(t *testing.T) {
sessionStore := &mstore.Store{LoadError: errors.New("no session")}
a := &Authenticate{
cfg: getAuthenticateConfig(WithGetIdentityProvider(func(options *config.Options, idpID string) (identity.Authenticator, error) {
cfg: getAuthenticateConfig(WithGetIdentityProvider(func(_ *config.Options, _ string) (identity.Authenticator, error) {
return identity.MockProvider{}, nil
})),
state: atomicutil.NewValue(&authenticateState{
@ -355,7 +355,7 @@ func TestAuthenticate_OAuthCallback(t *testing.T) {
}
authURL, _ := url.Parse(tt.authenticateURL)
a := &Authenticate{
cfg: getAuthenticateConfig(WithGetIdentityProvider(func(options *config.Options, idpID string) (identity.Authenticator, error) {
cfg: getAuthenticateConfig(WithGetIdentityProvider(func(_ *config.Options, _ string) (identity.Authenticator, error) {
return tt.provider, nil
})),
state: atomicutil.NewValue(&authenticateState{
@ -401,7 +401,7 @@ func TestAuthenticate_OAuthCallback(t *testing.T) {
func TestAuthenticate_SessionValidatorMiddleware(t *testing.T) {
t.Parallel()
fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fn := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "RVSI FILIVS CAISAR")
w.WriteHeader(http.StatusOK)
@ -467,7 +467,7 @@ func TestAuthenticate_SessionValidatorMiddleware(t *testing.T) {
t.Fatal(err)
}
a := &Authenticate{
cfg: getAuthenticateConfig(WithGetIdentityProvider(func(options *config.Options, idpID string) (identity.Authenticator, error) {
cfg: getAuthenticateConfig(WithGetIdentityProvider(func(_ *config.Options, _ string) (identity.Authenticator, error) {
return tt.provider, nil
})),
state: atomicutil.NewValue(&authenticateState{

View file

@ -55,7 +55,7 @@ func TestAccessTracker(t *testing.T) {
}
tracker := NewAccessTracker(&testAccessTrackerProvider{
dataBrokerServiceClient: &mockDataBrokerServiceClient{
get: func(ctx context.Context, in *databroker.GetRequest, opts ...grpc.CallOption) (*databroker.GetResponse, error) {
get: func(_ context.Context, in *databroker.GetRequest, _ ...grpc.CallOption) (*databroker.GetResponse, error) {
mu.Lock()
defer mu.Unlock()
@ -88,7 +88,7 @@ func TestAccessTracker(t *testing.T) {
return nil, status.Errorf(codes.InvalidArgument, "unknown type: %s", in.GetType())
}
},
put: func(ctx context.Context, in *databroker.PutRequest, opts ...grpc.CallOption) (*databroker.PutResponse, error) {
put: func(_ context.Context, in *databroker.PutRequest, _ ...grpc.CallOption) (*databroker.PutResponse, error) {
mu.Lock()
defer mu.Unlock()

View file

@ -34,7 +34,7 @@ var (
types.Args(types.S, types.S),
types.NewObject(nil, types.NewDynamicProperty(types.S, types.S)),
),
}, func(bctx rego.BuiltinContext, op1 *ast.Term, op2 *ast.Term) (*ast.Term, error) {
}, func(_ rego.BuiltinContext, op1 *ast.Term, op2 *ast.Term) (*ast.Term, error) {
serviceAccount, ok := op1.Value.(ast.String)
if !ok {
return nil, fmt.Errorf("invalid service account type: %T", op1)
@ -65,7 +65,7 @@ type gcpIdentityTokenSource struct {
}
func (src *gcpIdentityTokenSource) Token() (*oauth2.Token, error) {
res, err, _ := src.singleflight.Do("", func() (interface{}, error) {
res, err, _ := src.singleflight.Do("", func() (any, error) {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, GCPIdentityDocURL+"?"+url.Values{
"format": {"full"},
"audience": {src.audience},

View file

@ -62,7 +62,7 @@ var variableSubstitutionFunctionRegoOption = rego.Function2(&rego.Function{
),
types.Named("output", types.S),
),
}, func(bctx rego.BuiltinContext, op1 *ast.Term, op2 *ast.Term) (*ast.Term, error) {
}, func(_ rego.BuiltinContext, op1 *ast.Term, op2 *ast.Term) (*ast.Term, error) {
inputString, ok := op1.Value.(ast.String)
if !ok {
return nil, fmt.Errorf("invalid input_string type: %T", op1.Value)
@ -143,18 +143,18 @@ func (e *HeadersEvaluator) Evaluate(ctx context.Context, req *HeadersRequest) (*
func (e *HeadersEvaluator) getHeader(vars rego.Vars) http.Header {
h := make(http.Header)
m, ok := vars["result"].(map[string]interface{})
m, ok := vars["result"].(map[string]any)
if !ok {
return h
}
m, ok = m["identity_headers"].(map[string]interface{})
m, ok = m["identity_headers"].(map[string]any)
if !ok {
return h
}
for k := range m {
vs, ok := m[k].([]interface{})
vs, ok := m[k].([]any)
if !ok {
continue
}

View file

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

View file

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

View file

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

View file

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

View file

@ -57,7 +57,7 @@ func (codecType CodecType) ToEnvoy() envoy_http_connection_manager.HttpConnectio
}
func decodeCodecTypeHookFunc() mapstructure.DecodeHookFunc {
return func(f, t reflect.Type, data interface{}) (interface{}, error) {
return func(_, t reflect.Type, data any) (any, error) {
if t != reflect.TypeOf(CodecType("")) {
return data, nil
}

View file

@ -38,7 +38,7 @@ func TestFileWatcherSource(t *testing.T) {
src := NewFileWatcherSource(ctx, ssrc)
var closeOnce sync.Once
ch := make(chan struct{})
src.OnConfigChange(context.Background(), func(ctx context.Context, cfg *Config) {
src.OnConfigChange(context.Background(), func(_ context.Context, _ *Config) {
closeOnce.Do(func() {
close(ch)
})

View file

@ -24,7 +24,7 @@ import (
)
func decodeNullBoolHookFunc() mapstructure.DecodeHookFunc {
return func(f, t reflect.Type, data interface{}) (interface{}, error) {
return func(_, t reflect.Type, data any) (any, error) {
if t != reflect.TypeOf(null.Bool{}) {
return data, nil
}
@ -57,7 +57,7 @@ func NewJWTClaimHeaders(claims ...string) JWTClaimHeaders {
// UnmarshalJSON unmarshals JSON data into the JWTClaimHeaders.
func (hdrs *JWTClaimHeaders) UnmarshalJSON(data []byte) error {
var m map[string]interface{}
var m map[string]any
if json.Unmarshal(data, &m) == nil {
*hdrs = make(map[string]string)
for k, v := range m {
@ -67,7 +67,7 @@ func (hdrs *JWTClaimHeaders) UnmarshalJSON(data []byte) error {
return nil
}
var a []interface{}
var a []any
if json.Unmarshal(data, &a) == nil {
var vs []string
for _, v := range a {
@ -89,8 +89,8 @@ func (hdrs *JWTClaimHeaders) UnmarshalJSON(data []byte) error {
}
// UnmarshalYAML uses UnmarshalJSON to unmarshal YAML data into the JWTClaimHeaders.
func (hdrs *JWTClaimHeaders) UnmarshalYAML(unmarshal func(interface{}) error) error {
var i interface{}
func (hdrs *JWTClaimHeaders) UnmarshalYAML(unmarshal func(any) error) error {
var i any
err := unmarshal(&i)
if err != nil {
return err
@ -110,7 +110,7 @@ func (hdrs *JWTClaimHeaders) UnmarshalYAML(unmarshal func(interface{}) error) er
}
func decodeJWTClaimHeadersHookFunc() mapstructure.DecodeHookFunc {
return func(f, t reflect.Type, data interface{}) (interface{}, error) {
return func(_, t reflect.Type, data any) (any, error) {
if t != reflect.TypeOf(JWTClaimHeaders{}) {
return data, nil
}
@ -198,8 +198,8 @@ func (slc *StringSlice) UnmarshalJSON(data []byte) error {
// UnmarshalYAML unmarshals a YAML document into the string slice. UnmarshalJSON is
// reused as the actual implementation.
func (slc *StringSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {
var i interface{}
func (slc *StringSlice) UnmarshalYAML(unmarshal func(any) error) error {
var i any
err := unmarshal(&i)
if err != nil {
return err
@ -350,8 +350,8 @@ func (ppl *PPLPolicy) UnmarshalJSON(data []byte) error {
}
// UnmarshalYAML parses YAML into a PPL policy.
func (ppl *PPLPolicy) UnmarshalYAML(unmarshal func(interface{}) error) error {
var i interface{}
func (ppl *PPLPolicy) UnmarshalYAML(unmarshal func(any) error) error {
var i any
err := unmarshal(&i)
if err != nil {
return err
@ -364,7 +364,7 @@ func (ppl *PPLPolicy) UnmarshalYAML(unmarshal func(interface{}) error) error {
}
func decodePPLPolicyHookFunc() mapstructure.DecodeHookFunc {
return func(f, t reflect.Type, data interface{}) (interface{}, error) {
return func(_, t reflect.Type, data any) (any, error) {
if t != reflect.TypeOf(&PPLPolicy{}) {
return data, nil
}
@ -383,7 +383,7 @@ func decodePPLPolicyHookFunc() mapstructure.DecodeHookFunc {
// DecodePolicyBase64Hook returns a mapstructure decode hook for base64 data.
func DecodePolicyBase64Hook() mapstructure.DecodeHookFunc {
return func(f, t reflect.Type, data interface{}) (interface{}, error) {
return func(_, t reflect.Type, data any) (any, error) {
if t != reflect.TypeOf([]Policy{}) {
return data, nil
}
@ -402,7 +402,7 @@ func DecodePolicyBase64Hook() mapstructure.DecodeHookFunc {
return nil, fmt.Errorf("base64 decoding policy data: %w", err)
}
var out []map[interface{}]interface{}
var out []map[any]any
if err = yaml.Unmarshal(bytes, &out); err != nil {
return nil, fmt.Errorf("parsing base64-encoded policy data as yaml: %w", err)
}
@ -413,7 +413,7 @@ func DecodePolicyBase64Hook() mapstructure.DecodeHookFunc {
// DecodePolicyHookFunc returns a Decode Hook for mapstructure.
func DecodePolicyHookFunc() mapstructure.DecodeHookFunc {
return func(f, t reflect.Type, data interface{}) (interface{}, error) {
return func(_, t reflect.Type, data any) (any, error) {
if t != reflect.TypeOf(Policy{}) {
return data, nil
}
@ -424,7 +424,7 @@ func DecodePolicyHookFunc() mapstructure.DecodeHookFunc {
if err != nil {
return nil, err
}
ms, ok := mp.(map[string]interface{})
ms, ok := mp.(map[string]any)
if !ok {
return nil, errKeysMustBeStrings
}
@ -433,8 +433,8 @@ func DecodePolicyHookFunc() mapstructure.DecodeHookFunc {
}
}
func parsePolicy(src map[string]interface{}) (out map[string]interface{}, err error) {
out = make(map[string]interface{}, len(src))
func parsePolicy(src map[string]any) (out map[string]any, err error) {
out = make(map[string]any, len(src))
for k, v := range src {
if k == toKey {
if v, err = parseTo(v); err != nil {
@ -453,7 +453,7 @@ func parsePolicy(src map[string]interface{}) (out map[string]interface{}, err er
return out, nil
}
func parseTo(raw interface{}) ([]WeightedURL, error) {
func parseTo(raw any) ([]WeightedURL, error) {
rawBS, err := json.Marshal(raw)
if err != nil {
return nil, err
@ -488,7 +488,7 @@ func weightedString(str string) (string, uint32, error) {
// parseEnvoyClusterOpts parses src as envoy cluster spec https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/cluster/v3/cluster.proto
// on top of some pre-filled default values
func parseEnvoyClusterOpts(src map[string]interface{}) (*envoy_config_cluster_v3.Cluster, error) {
func parseEnvoyClusterOpts(src map[string]any) (*envoy_config_cluster_v3.Cluster, error) {
c := new(envoy_config_cluster_v3.Cluster)
if err := parseJSONPB(src, c, protoPartial); err != nil {
return nil, err
@ -499,7 +499,7 @@ func parseEnvoyClusterOpts(src map[string]interface{}) (*envoy_config_cluster_v3
// parseJSONPB takes an intermediate representation and parses it using protobuf parser
// that correctly handles oneof and other data types
func parseJSONPB(src map[string]interface{}, dst proto.Message, opts protojson.UnmarshalOptions) error {
func parseJSONPB(src map[string]any, dst proto.Message, opts protojson.UnmarshalOptions) error {
data, err := json.Marshal(src)
if err != nil {
return err
@ -510,7 +510,7 @@ func parseJSONPB(src map[string]interface{}, dst proto.Message, opts protojson.U
// decodeSANMatcherHookFunc returns a decode hook for the SANMatcher type.
func decodeSANMatcherHookFunc() mapstructure.DecodeHookFunc {
return func(f, t reflect.Type, data interface{}) (interface{}, error) {
return func(_, t reflect.Type, data any) (any, error) {
if t != reflect.TypeOf(SANMatcher{}) {
return data, nil
}
@ -543,11 +543,11 @@ func decodeStringToMapHookFunc() mapstructure.DecodeHookFunc {
})
}
// serializable converts mapstructure nested map into map[string]interface{} that is serializable to JSON
func serializable(in interface{}) (interface{}, error) {
// serializable converts mapstructure nested map into map[string]any that is serializable to JSON
func serializable(in any) (any, error) {
switch typed := in.(type) {
case map[interface{}]interface{}:
m := make(map[string]interface{})
case map[any]any:
m := make(map[string]any)
for k, v := range typed {
kstr, ok := k.(string)
if !ok {
@ -560,8 +560,8 @@ func serializable(in interface{}) (interface{}, error) {
m[kstr] = val
}
return m, nil
case []interface{}:
out := make([]interface{}, 0, len(typed))
case []any:
out := make([]any, 0, len(typed))
for _, elem := range typed {
val, err := serializable(elem)
if err != nil {

View file

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

View file

@ -149,7 +149,7 @@ func (b *Builder) BuildBootstrapDynamicResources(
// BuildBootstrapLayeredRuntime builds the layered runtime for the envoy bootstrap.
func (b *Builder) BuildBootstrapLayeredRuntime() (*envoy_config_bootstrap_v3.LayeredRuntime, error) {
layer, err := structpb.NewStruct(map[string]interface{}{
layer, err := structpb.NewStruct(map[string]any{
"re2": map[string]any{
"max_program_size": map[string]any{
"error_level": 1024 * 1024,

View file

@ -32,7 +32,7 @@ var (
testDataTemplate = template.Must(template.ParseFS(testDataFS, "testdata/*.json"))
)
func testData(t *testing.T, name string, data interface{}) string {
func testData(t *testing.T, name string, data any) string {
t.Helper()
var buf bytes.Buffer
err := testDataTemplate.ExecuteTemplate(&buf, name, data)

View file

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

View file

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

View file

@ -18,7 +18,7 @@ func getLocalCertPEM(s *httptest.Server) []byte {
}
func TestHTTPTransport(t *testing.T) {
s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer s.Close()
@ -44,7 +44,7 @@ func TestPolicyHTTPTransport(t *testing.T) {
src := NewStaticSource(&Config{Options: &Options{}})
http.DefaultTransport = NewHTTPTransport(src)
s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer s.Close()

View file

@ -21,7 +21,7 @@ func TestLayeredConfig(t *testing.T) {
t.Run("error on initial build", func(t *testing.T) {
underlying := config.NewStaticSource(&config.Config{})
_, err := config.NewLayeredSource(ctx, underlying, func(c *config.Config) error {
_, err := config.NewLayeredSource(ctx, underlying, func(_ *config.Config) error {
return errors.New("error")
})
require.Error(t, err)
@ -39,7 +39,7 @@ func TestLayeredConfig(t *testing.T) {
var dst atomic.Pointer[config.Config]
dst.Store(layered.GetConfig())
layered.OnConfigChange(ctx, func(ctx context.Context, c *config.Config) {
layered.OnConfigChange(ctx, func(_ context.Context, c *config.Config) {
dst.Store(c)
})

View file

@ -22,7 +22,7 @@ func TestMetricsManager(t *testing.T) {
mgr := NewMetricsManager(ctx, src)
srv1 := httptest.NewServer(mgr)
defer srv1.Close()
srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "ERROR", http.StatusInternalServerError)
}))
defer srv2.Close()

View file

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

View file

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

View file

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

View file

@ -102,7 +102,7 @@ func TestTraceManager(t *testing.T) {
incoming := make(chan Request, 100)
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
var objs []struct {
Name string
}

View file

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

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 res.StatusCode == http.StatusForbidden || res.StatusCode == http.StatusUnauthorized
}, msgAndArgs...)

View file

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

View file

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

View file

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

View file

@ -15,7 +15,7 @@ import (
var outboundGRPCConnection = new(grpc.CachedOutboundGRPClientConn)
func populateUserFromClaims(u *user.User, claims map[string]interface{}) {
func populateUserFromClaims(u *user.User, claims map[string]any) {
if v, ok := claims["name"]; ok {
u.Name = fmt.Sprint(v)
}

View file

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

View file

@ -93,7 +93,7 @@ func newManager(ctx context.Context,
return nil, err
}
mgr.certmagic = certmagic.New(certmagic.NewCache(certmagic.CacheOptions{
GetConfigForCert: func(c certmagic.Certificate) (*certmagic.Config, error) {
GetConfigForCert: func(_ certmagic.Certificate) (*certmagic.Config, error) {
return mgr.certmagic, nil
},
Logger: logger,

View file

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

View file

@ -69,7 +69,7 @@ func GetCertMagicStorage(ctx context.Context, dst string) (certmagic.Storage, er
prefix = strings.TrimPrefix(match[3][1:], "/")
options = append(options,
config.WithRegion("us-east-1"),
config.WithEndpointResolver(aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) {
config.WithEndpointResolver(aws.EndpointResolverFunc(func(_, _ string) (aws.Endpoint, error) {
return aws.Endpoint{
PartitionID: "aws",
URL: "http://" + host,

View file

@ -51,11 +51,11 @@ func TestEvents(t *testing.T) {
grpcSrv := grpc.NewServer()
databrokerpb.RegisterDataBrokerServiceServer(grpcSrv, &mockDataBrokerServer{
put: func(ctx context.Context, req *databrokerpb.PutRequest) (*databrokerpb.PutResponse, error) {
put: func(_ context.Context, req *databrokerpb.PutRequest) (*databrokerpb.PutResponse, error) {
putRequest = req
return new(databrokerpb.PutResponse), nil
},
setOptions: func(ctx context.Context, req *databrokerpb.SetOptionsRequest) (*databrokerpb.SetOptionsResponse, error) {
setOptions: func(_ context.Context, req *databrokerpb.SetOptionsRequest) (*databrokerpb.SetOptionsResponse, error) {
setOptionsRequest = req
return new(databrokerpb.SetOptionsResponse), nil
},

View file

@ -21,7 +21,7 @@ type streamState struct {
unsubscribedResources map[string]struct{}
}
var onHandleDeltaRequest = func(state *streamState) {}
var onHandleDeltaRequest = func(_ *streamState) {}
// A Manager manages xDS resources.
type Manager struct {
@ -51,7 +51,7 @@ func (mgr *Manager) DeltaAggregatedResources(
stateByTypeURL := map[string]*streamState{}
getDeltaResponse := func(ctx context.Context, typeURL string) *envoy_service_discovery_v3.DeltaDiscoveryResponse {
getDeltaResponse := func(_ context.Context, typeURL string) *envoy_service_discovery_v3.DeltaDiscoveryResponse {
mgr.mu.Lock()
defer mgr.mu.Unlock()

View file

@ -27,7 +27,7 @@ func TestManager(t *testing.T) {
stateChanged := signal.New()
origOnHandleDeltaRequest := onHandleDeltaRequest
defer func() { onHandleDeltaRequest = origOnHandleDeltaRequest }()
onHandleDeltaRequest = func(state *streamState) {
onHandleDeltaRequest = func(_ *streamState) {
stateChanged.Broadcast(ctx)
}
@ -44,7 +44,7 @@ func TestManager(t *testing.T) {
cc, err := grpc.Dial("test",
grpc.WithInsecure(),
grpc.WithContextDialer(func(ctx context.Context, target string) (net.Conn, error) {
grpc.WithContextDialer(func(_ context.Context, _ string) (net.Conn, error) {
return li.Dial()
}))
if !assert.NoError(t, err) {

View file

@ -18,7 +18,7 @@ func TestEnabler(t *testing.T) {
t.Run("enabled immediately", func(t *testing.T) {
t.Parallel()
e := enabler.New("test", enabler.HandlerFunc(func(ctx context.Context) error {
e := enabler.New("test", enabler.HandlerFunc(func(_ context.Context) error {
return errors.New("ERROR")
}), true)
err := e.Run(context.Background())
@ -27,7 +27,7 @@ func TestEnabler(t *testing.T) {
t.Run("enabled delayed", func(t *testing.T) {
t.Parallel()
e := enabler.New("test", enabler.HandlerFunc(func(ctx context.Context) error {
e := enabler.New("test", enabler.HandlerFunc(func(_ context.Context) error {
return errors.New("ERROR")
}), false)
time.AfterFunc(time.Millisecond*10, e.Enable)

View file

@ -7,7 +7,7 @@ import (
)
// DecodeBase64OrJSON decodes a JSON string that can optionally be base64 encoded.
func DecodeBase64OrJSON(in string, out interface{}) error {
func DecodeBase64OrJSON(in string, out any) error {
in = strings.TrimSpace(in)
// the data can be base64 encoded

View file

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

View file

@ -14,7 +14,7 @@ import (
type JSONWebSigner struct {
Signer jose.Signer
key interface{}
key any
}
// NewHS256Signer creates a SHA256 JWT signer from a 32 byte key.
@ -28,13 +28,13 @@ func NewHS256Signer(key []byte) (encoding.MarshalUnmarshaler, error) {
}
// Marshal signs, and serializes a JWT.
func (c *JSONWebSigner) Marshal(x interface{}) ([]byte, error) {
func (c *JSONWebSigner) Marshal(x any) ([]byte, error) {
s, err := jwt.Signed(c.Signer).Claims(x).CompactSerialize()
return []byte(s), err
}
// Unmarshal parses and validates a signed JWT.
func (c *JSONWebSigner) Unmarshal(value []byte, s interface{}) error {
func (c *JSONWebSigner) Unmarshal(value []byte, s any) error {
tok, err := jwt.ParseSigned(string(value))
if err != nil {
return err

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -91,7 +91,7 @@ func getDefaultClient() *httpClient {
}
// Do provides a simple helper interface to make HTTP requests
func Do(ctx context.Context, method, endpoint, userAgent string, headers map[string]string, params url.Values, response interface{}) error {
func Do(ctx context.Context, method, endpoint, userAgent string, headers map[string]string, params url.Values, response any) error {
var body io.Reader
switch method {
case http.MethodPost:

View file

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

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
// writes are done to w.
// The error message should be application/json.
func RenderJSON(w http.ResponseWriter, code int, v interface{}) {
func RenderJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
b := new(bytes.Buffer)

View file

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

View file

@ -16,7 +16,7 @@ import (
)
func TestMiddleware(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "NEXT")
})
@ -38,7 +38,7 @@ func TestMiddleware(t *testing.T) {
t.Run("proxy", func(t *testing.T) {
h := New()
srv1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "SERVER1")
}))
defer srv1.Close()

View file

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

View file

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

View file

@ -32,7 +32,7 @@ import (
type Authenticator interface {
Refresh(context.Context, *oauth2.Token, identity.State) (*oauth2.Token, error)
Revoke(context.Context, *oauth2.Token) error
UpdateUserInfo(context.Context, *oauth2.Token, interface{}) error
UpdateUserInfo(context.Context, *oauth2.Token, any) error
}
// A Manager refreshes identity information using session and user data.

View file

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

View file

@ -37,7 +37,7 @@ func (mp MockProvider) Revoke(_ context.Context, _ *oauth2.Token) error {
}
// UpdateUserInfo is a mocked providers function.
func (mp MockProvider) UpdateUserInfo(_ context.Context, _ *oauth2.Token, _ interface{}) error {
func (mp MockProvider) UpdateUserInfo(_ context.Context, _ *oauth2.Token, _ any) error {
return mp.UpdateUserInfoError
}

View file

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

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

View file

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

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.
//
// https://openid.net/specs/openid-connect-core-1_0.html#UserInfo
func (p *Provider) UpdateUserInfo(ctx context.Context, t *oauth2.Token, v interface{}) error {
func (p *Provider) UpdateUserInfo(ctx context.Context, t *oauth2.Token, v any) error {
pp, err := p.GetProvider()
if err != nil {
return err
@ -255,7 +255,7 @@ func (p *Provider) Revoke(ctx context.Context, t *oauth2.Token) error {
}
// GetSubject gets the RFC 7519 Subject claim (`sub`) from a
func (p *Provider) GetSubject(v interface{}) (string, error) {
func (p *Provider) GetSubject(v any) (string, error) {
b, err := json.Marshal(v)
if err != nil {
return "", err

View file

@ -18,7 +18,7 @@ func TestRefresh(t *testing.T) {
ctx, clearTimeout := context.WithTimeout(context.Background(), 10*time.Second)
t.Cleanup(clearTimeout)
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{
"access_token": "NEW_TOKEN",
@ -52,7 +52,7 @@ func TestRefresh_errors(t *testing.T) {
ctx, clearTimeout := context.WithTimeout(context.Background(), 10*time.Second)
t.Cleanup(clearTimeout)
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("{}"))
}))
t.Cleanup(s.Close)

View file

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

View file

@ -30,7 +30,7 @@ type Authenticator interface {
Refresh(context.Context, *oauth2.Token, identity.State) (*oauth2.Token, error)
Revoke(context.Context, *oauth2.Token) error
Name() string
UpdateUserInfo(ctx context.Context, t *oauth2.Token, v interface{}) error
UpdateUserInfo(ctx context.Context, t *oauth2.Token, v any) error
SignIn(w http.ResponseWriter, r *http.Request, state string) error
SignOut(w http.ResponseWriter, r *http.Request, idTokenHint, authenticateSignedOutURL, redirectToURL string) error

View file

@ -13,69 +13,69 @@ func init() {
type grpcLogger struct{}
func (c *grpcLogger) Info(args ...interface{}) {
func (c *grpcLogger) Info(args ...any) {
if GetLevel() <= zerolog.DebugLevel {
Logger().Info().Msg(fmt.Sprint(args...))
}
}
func (c *grpcLogger) Infoln(args ...interface{}) {
func (c *grpcLogger) Infoln(args ...any) {
if GetLevel() <= zerolog.DebugLevel {
Logger().Info().Msg(fmt.Sprintln(args...))
}
}
func (c *grpcLogger) Infof(format string, args ...interface{}) {
func (c *grpcLogger) Infof(format string, args ...any) {
if GetLevel() <= zerolog.DebugLevel {
Logger().Info().Msg(fmt.Sprintf(format, args...))
}
}
func (c *grpcLogger) Warning(args ...interface{}) {
func (c *grpcLogger) Warning(args ...any) {
if GetLevel() <= zerolog.DebugLevel {
Logger().Warn().Msg(fmt.Sprint(args...))
}
}
func (c *grpcLogger) Warningln(args ...interface{}) {
func (c *grpcLogger) Warningln(args ...any) {
if GetLevel() <= zerolog.DebugLevel {
Logger().Warn().Msg(fmt.Sprintln(args...))
}
}
func (c *grpcLogger) Warningf(format string, args ...interface{}) {
func (c *grpcLogger) Warningf(format string, args ...any) {
if GetLevel() <= zerolog.DebugLevel {
Logger().Warn().Msg(fmt.Sprintf(format, args...))
}
}
func (c *grpcLogger) Error(args ...interface{}) {
func (c *grpcLogger) Error(args ...any) {
if GetLevel() <= zerolog.DebugLevel {
Logger().Error().Msg(fmt.Sprint(args...))
}
}
func (c *grpcLogger) Errorln(args ...interface{}) {
func (c *grpcLogger) Errorln(args ...any) {
if GetLevel() <= zerolog.DebugLevel {
Logger().Error().Msg(fmt.Sprintln(args...))
}
}
func (c *grpcLogger) Errorf(format string, args ...interface{}) {
func (c *grpcLogger) Errorf(format string, args ...any) {
if GetLevel() <= zerolog.DebugLevel {
Logger().Error().Msg(fmt.Sprintf(format, args...))
}
}
func (c *grpcLogger) Fatal(args ...interface{}) {
func (c *grpcLogger) Fatal(args ...any) {
Logger().Fatal().Msg(fmt.Sprint(args...))
}
func (c *grpcLogger) Fatalln(args ...interface{}) {
func (c *grpcLogger) Fatalln(args ...any) {
Logger().Fatal().Msg(fmt.Sprintln(args...))
}
func (c *grpcLogger) Fatalf(format string, args ...interface{}) {
func (c *grpcLogger) Fatalf(format string, args ...any) {
Logger().Fatal().Msg(fmt.Sprintf(format, args...))
}

View file

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

View file

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

View file

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

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.
func (cs *Store) SaveSession(w http.ResponseWriter, _ *http.Request, x interface{}) error {
func (cs *Store) SaveSession(w http.ResponseWriter, _ *http.Request, x any) error {
var value string
switch v := x.(type) {
case []byte:

View file

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

View file

@ -27,7 +27,7 @@ func testAuthorizer(next http.Handler) http.Handler {
}
func TestVerifier(t *testing.T) {
fnh := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fnh := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK)

View file

@ -27,7 +27,7 @@ func testAuthorizer(next http.Handler) http.Handler {
}
func TestVerifier(t *testing.T) {
fnh := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fnh := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK)

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
// a pointer so it fits in an interface{} without allocation. This technique
// a pointer so it fits in an any without allocation. This technique
// for defining context keys was copied from Go 1.7's new use of context in net/http.
type contextKey struct {
name string

View file

@ -62,7 +62,7 @@ func testAuthorizer(next http.Handler) http.Handler {
}
func TestVerifier(t *testing.T) {
fnh := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fnh := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK)

View file

@ -38,6 +38,6 @@ func (ms Store) LoadSession(*http.Request) (string, error) {
}
// SaveSession returns a save error.
func (ms Store) SaveSession(http.ResponseWriter, *http.Request, interface{}) error {
func (ms Store) SaveSession(http.ResponseWriter, *http.Request, any) error {
return ms.SaveError
}

View file

@ -27,7 +27,7 @@ func testAuthorizer(next http.Handler) http.Handler {
}
func TestVerifier(t *testing.T) {
fnh := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fnh := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, http.StatusText(http.StatusOK))
w.WriteHeader(http.StatusOK)

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`
func (qp *Store) SaveSession(_ http.ResponseWriter, r *http.Request, x interface{}) error {
func (qp *Store) SaveSession(_ http.ResponseWriter, r *http.Request, x any) error {
data, err := qp.encoder.Marshal(x)
if err != nil {
return err

View file

@ -11,7 +11,7 @@ import (
type SessionStore interface {
SessionLoader
ClearSession(http.ResponseWriter, *http.Request)
SaveSession(http.ResponseWriter, *http.Request, interface{}) error
SaveSession(http.ResponseWriter, *http.Request, any) error
}
// SessionLoader defines an interface for loading a session.

View file

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

View file

@ -7,7 +7,7 @@ import (
"go.opencensus.io/metric/metricdata"
)
func testMetricRetrieval(metrics []*metricdata.Metric, t *testing.T, labels []metricdata.LabelValue, value interface{}, name string) {
func testMetricRetrieval(metrics []*metricdata.Metric, t *testing.T, labels []metricdata.LabelValue, value any, name string) {
t.Helper()
switch value.(type) {

View file

@ -44,7 +44,7 @@ func testDataRetrieval(v *view.View, t *testing.T, want string) {
func newTestMux() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/good", func(w http.ResponseWriter, r *http.Request) {
mux.HandleFunc("/good", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, "Hello")
})
@ -123,7 +123,7 @@ func newTestTransport() http.RoundTripper {
}
func newFailingTestTransport() http.RoundTripper {
return tripper.RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
return tripper.RoundTripperFunc(func(_ *http.Request) (*http.Response, error) {
return nil, errors.New("failure")
})
}

View file

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

View file

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

View file

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

View file

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

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)
return c.api.Watch(ctx,
connect_mux.WithOnConnected(func(ctx context.Context) {
connect_mux.WithOnConnected(func(_ context.Context) {
logger.Debug().Msg("connected")
}),
connect_mux.WithOnDisconnected(func(ctx context.Context) {
connect_mux.WithOnDisconnected(func(_ context.Context) {
logger.Debug().Msg("disconnected")
}),
connect_mux.WithOnBootstrapConfigUpdated(func(ctx context.Context) {
connect_mux.WithOnBootstrapConfigUpdated(func(_ context.Context) {
logger.Debug().Msg("bootstrap config updated")
}),
connect_mux.WithOnBundleUpdated(func(ctx context.Context, key string) {
connect_mux.WithOnBundleUpdated(func(_ context.Context, key string) {
logger.Debug().Str("key", key).Msg("bundle updated")
}),
)

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

View file

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

View file

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

View file

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

View file

@ -32,7 +32,7 @@ import (
// Run runs the main pomerium application.
func Run(ctx context.Context, src config.Source) error {
_, _ = maxprocs.Set(maxprocs.Logger(func(s string, i ...interface{}) { log.Debug(context.Background()).Msgf(s, i...) }))
_, _ = maxprocs.Set(maxprocs.Logger(func(s string, i ...any) { log.Debug(context.Background()).Msgf(s, i...) }))
log.Info(ctx).
Str("envoy_version", files.FullVersion()).

View file

@ -55,7 +55,7 @@ func (mc *mergedCtx) Err() error {
return mc.doneCtx.Err()
}
func (mc *mergedCtx) Value(key interface{}) interface{} {
func (mc *mergedCtx) Value(key any) any {
if value := mc.ctx1.Value(key); value != nil {
return value
}

View file

@ -88,7 +88,7 @@ func TestHashProto(t *testing.T) {
// deterministic.
var cur []byte
for i := 0; i < 1000; i++ {
s, err := structpb.NewStruct(map[string]interface{}{
s, err := structpb.NewStruct(map[string]any{
"1": "a", "2": "b", "3": "c", "4": "d",
"5": "e", "6": "f", "7": "g", "8": "h",
})

View file

@ -75,7 +75,7 @@ func loadKeys(data []byte, unmarshal func([]byte) (any, error)) ([]*jose.JSONWeb
return jwks, nil
}
func loadPrivateKey(b []byte) (interface{}, error) {
func loadPrivateKey(b []byte) (any, error) {
var wrappedErr error
var err error
var key any
@ -99,7 +99,7 @@ func loadPrivateKey(b []byte) (interface{}, error) {
}
// https://github.com/square/go-jose/tree/v2.5.1#supported-key-types
func loadPublicKey(b []byte) (interface{}, error) {
func loadPublicKey(b []byte) (any, error) {
var wrappedErr error
var err error
var key any
@ -130,7 +130,7 @@ func loadPublicKey(b []byte) (interface{}, error) {
}
// SignatureAlgorithmForKey returns the signature algorithm for the given key.
func SignatureAlgorithmForKey(key interface{}) (jose.SignatureAlgorithm, error) {
func SignatureAlgorithmForKey(key any) (jose.SignatureAlgorithm, error) {
switch key.(type) {
case *ecdsa.PrivateKey, *ecdsa.PublicKey:
return jose.ES256, nil

View file

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

View file

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

View file

@ -61,7 +61,7 @@ func NewGRPCClientConn(ctx context.Context, opts *Options, other ...grpc.DialOpt
// grpcTimeoutInterceptor enforces per-RPC request timeouts
func grpcTimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
if timeout <= 0 {
return invoker(ctx, method, req, reply, cc, opts...)
}

View file

@ -10,7 +10,7 @@ import (
func Test_grpcTimeoutInterceptor(t *testing.T) {
mockInvoker := func(sleepTime time.Duration, wantFail bool) grpc.UnaryInvoker {
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error {
return func(ctx context.Context, _ string, _, _ any, _ *grpc.ClientConn, _ ...grpc.CallOption) error {
time.Sleep(sleepTime)
deadline, ok := ctx.Deadline()
if !ok {

View file

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

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